85 lines
6.0 KiB
C#
85 lines
6.0 KiB
C#
using System.Net;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using OpenCvSharp;
|
|
using SopHelper.Engine.SopAgent;
|
|
|
|
static void Check(bool value,string message) { if(!value)throw new Exception(message); }
|
|
var folder=Path.Combine(Path.GetTempPath(),"sop-agent-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(folder);
|
|
try
|
|
{
|
|
var path=Path.Combine(folder,"standard.avi");
|
|
using(var writer=new VideoWriter())
|
|
{
|
|
Check(writer.Open(path,FourCC.MJPG,10,new Size(64,48)),"测试视频创建失败");
|
|
for(var i=0;i<40;i++) {using var frame=new Mat(48,64,MatType.CV_8UC3,i<20?new Scalar(0,0,240):new Scalar(240,0,0));writer.Write(frame);}
|
|
}
|
|
var sample=SopVideoSampler.Sample(path,4,default);
|
|
Check(sample.Frames.Count==3&&Math.Abs(sample.DurationSeconds-4)<.01,"应按时长抽样并覆盖首尾");
|
|
Check(sample.Frames[0].Seconds==0&&sample.Frames[^1].Seconds>3.8,"应保留真实时间戳");
|
|
using(var first=Cv2.ImDecode(sample.Frames[0].Jpeg,ImreadModes.Color))
|
|
using(var last=Cv2.ImDecode(sample.Frames[^1].Jpeg,ImreadModes.Color))
|
|
Check(first.At<Vec3b>(0,0).Item2>220&&last.At<Vec3b>(0,0).Item0>220,"应读取各时刻的真实画面,不能重复第一张");
|
|
using var handler=new AgentHttp();using var http=new HttpClient(handler);
|
|
var client=new SopVideoDraftClient(http);
|
|
var request=new SopVideoAnalysisRequest("装盒","按实际动作分两步",sample,["work"]);
|
|
var connection=new SopAgentConnection("https://vision.invalid/custom/chat/completions","custom-vision","test-key",
|
|
ContextLength:16384,MaxTokens:2048,Temperature:.4,TopP:.8,TimeoutSeconds:90);
|
|
var models=await client.GetModelsAsync(connection.Endpoint,connection.ApiKey,default);
|
|
Check(handler.Url=="https://vision.invalid/custom/models"&&handler.Authorization=="Bearer test-key"
|
|
&&models.SequenceEqual(new[]{"a-vision","b-vision"}),"应从配置地址获取模型列表、鉴权并去重排序");
|
|
var draft=await client.AnalyzeAsync(request,connection,default);
|
|
Check(draft.Steps.Count==2&&draft.Steps[0].Region=="work","应解析并规范化已存在的区域引用");
|
|
Check(handler.Url==connection.Endpoint&&handler.Authorization=="Bearer test-key","接口地址与密钥应使用用户配置");
|
|
using(var body=JsonDocument.Parse(handler.Body!))
|
|
{
|
|
Check(body.RootElement.GetProperty("model").GetString()==connection.Model,"应使用配置的模型名");
|
|
Check(body.RootElement.GetProperty("max_tokens").GetInt32()==2048
|
|
&&body.RootElement.GetProperty("temperature").GetDouble()==.4&&body.RootElement.GetProperty("top_p").GetDouble()==.8,
|
|
"应发送配置的输出长度、温度和Top P");
|
|
var parts=body.RootElement.GetProperty("messages")[1].GetProperty("content");
|
|
Check(parts.EnumerateArray().Count(p=>p.GetProperty("type").GetString()=="image_url")==3,"必须上传抽样图片");
|
|
Check(parts[1].GetProperty("text").GetString()!.Contains("time=0.000s"),"必须发送时间戳");
|
|
}
|
|
var limited=false;
|
|
try{await client.AnalyzeAsync(request,connection with {ContextLength=4096,MaxTokens=2048},default);}catch(ArgumentException){limited=true;}
|
|
Check(limited,"上下文预算不足时应拒绝发送");
|
|
var invalidSettings=false;
|
|
try{SopVideoDraftClient.ValidateSettings(connection with {TopP=0});}catch(ArgumentException){invalidSettings=true;}
|
|
Check(invalidSettings,"无效采样参数应被拒绝");
|
|
Check(SopVideoSampler.Sample(path,3,default).Frames.Count==3,"最大抽帧数应支持3张");
|
|
foreach(var bad in new[]{handler.Json.Replace("\"end_seconds\":4","\"end_seconds\":400"),handler.Json.Replace("\"WORK\"","\"invented\""),handler.Json.Replace("\"evidence_frame\":1","\"evidence_frame\":99"),"{\"steps\":null}"})
|
|
{
|
|
handler.Override=bad;var rejected=false;
|
|
try{await client.AnalyzeAsync(request,connection,default);}catch(Exception){rejected=true;}
|
|
Check(rejected,"无效草稿必须拒绝");
|
|
}
|
|
handler.Override=null;handler.Finish="length";
|
|
var truncated=false;try{await client.AnalyzeAsync(request,connection,default);}catch(FormatException){truncated=true;}
|
|
Check(truncated,"截断输出不能作为步骤草稿");
|
|
handler.Finish="stop";handler.Status=HttpStatusCode.Unauthorized;
|
|
var failed=false;try{await client.AnalyzeAsync(request,connection,default);}catch(InvalidOperationException){failed=true;}
|
|
Check(failed,"HTTP 失败不能生成步骤");
|
|
using var cancellation=new CancellationTokenSource();cancellation.Cancel();
|
|
var cancelled=false;try{SopVideoSampler.Sample(path,4,cancellation.Token);}catch(OperationCanceledException){cancelled=true;}
|
|
Check(cancelled,"抽帧必须支持取消");
|
|
Console.WriteLine("PASS: 视频抽样与首尾时间戳、真实画面、可配置接口和模型、步骤解析、区域/时间/证据校验、截断/HTTP错误拒绝和取消");
|
|
}
|
|
finally{Directory.Delete(folder,true);}
|
|
|
|
sealed class AgentHttp:HttpMessageHandler
|
|
{
|
|
public string? Body,Url,Authorization,Override;
|
|
public string Finish="stop";
|
|
public HttpStatusCode Status=HttpStatusCode.OK;
|
|
public string Json="""{"summary":"放入并取走","warnings":[],"steps":[{"name":"放入零件","description":"盒子里有零件","start_seconds":0,"end_seconds":2,"region":"WORK","evidence_frame":1},{"name":"取走零件","description":"盒子里没有零件","start_seconds":2,"end_seconds":4,"region":"work","evidence_frame":2}]}""";
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message,CancellationToken token)
|
|
{
|
|
Url=message.RequestUri!.ToString();Authorization=message.Headers.Authorization?.ToString();
|
|
if(message.Method==HttpMethod.Get)
|
|
return new(Status){Content=new StringContent("""{"data":[{"id":"b-vision"},{"id":"a-vision"},{"id":"a-vision"}]}""")};
|
|
Body=await message.Content!.ReadAsStringAsync(token);
|
|
return new(Status){Content=new StringContent(JsonSerializer.Serialize(new{choices=new[]{new{finish_reason=Finish,message=new{content=Override??Json}}}}),Encoding.UTF8,"application/json")};
|
|
}
|
|
}
|