aisop/tests/SopVideoAgent.Smoke/Program.cs

68 lines
4.7 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");
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,"应使用配置的模型名");
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"),"必须发送时间戳");
}
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)
{
Body=await message.Content!.ReadAsStringAsync(token);Url=message.RequestUri!.ToString();Authorization=message.Headers.Authorization?.ToString();
return new(Status){Content=new StringContent(JsonSerializer.Serialize(new{choices=new[]{new{finish_reason=Finish,message=new{content=Override??Json}}}}),Encoding.UTF8,"application/json")};
}
}