using System.Text.Json;
using Avalonia.Threading;
using SopHelper.Engine.Sop;
using SopHelper.Training;
/// 显式指定 --live 时,用真实视频、手部模型和当前视觉服务验证整轮流程。
internal static class LiveVideoFlowChecks
{
// dotnet run --project tests/VideoFlowTest.Smoke -- --live --config 配方.yaml --report 输出目录
public static void Run(string[] args)
{
string? Value(string key)
{
var index = Array.IndexOf(args, key);
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
}
var path = Path.GetFullPath(Value("--config") ?? throw new ArgumentException("--live 需要 --config 配方路径"));
var video = Path.GetFullPath(Value("--video") ?? Path.Combine(Path.GetDirectoryName(path)!, "sop_stand", "sop.avi"));
if (!File.Exists(video)) throw new FileNotFoundException("标准视频不存在", video);
var report = Path.GetFullPath(Value("--report") ?? Path.Combine(Path.GetTempPath(), "sop-video-verification-" + Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(report);
using var test = new SopVideoFlowTest(SopConfigLoader.Load(path));
var playback = new RecordedVideoPlayback();
var traceGate = new object();
var lastDetails = "";
var imageCount = 0;
string? error = null;
test.Changed += (status, details) =>
{
lock (traceGate)
{
if (details == lastDetails) return;
lastDetails = details;
var line = $"{DateTimeOffset.Now:O} {status}{Environment.NewLine}{details}{Environment.NewLine}";
File.AppendAllText(Path.Combine(report, "trace.log"), line);
Console.WriteLine(line);
}
};
test.DecisionImageCaptured += (jpeg, frameId) =>
{
var sequence = Interlocked.Increment(ref imageCount);
File.WriteAllBytes(Path.Combine(report, $"request-{sequence:D3}-frame-{frameId:D6}.jpg"), jpeg);
};
playback.Failed += message => error = message;
try
{
Pump(Task.Run(test.LoadModels));
test.Start();
playback.FrameProcessor = test.ProcessFrame;
Pump(playback.PlayAsync(video));
Until(() => playback.IsAtEnd || error is not null);
if (error is not null) throw new IOException(error);
Pump(test.FinishPendingDecisionAsync());
var summary = test.Finish("真实标准视频回放结束");
File.WriteAllText(Path.Combine(report, "result.json"), JsonSerializer.Serialize(new
{
Config = path, Video = video, Completed = test.IsCompleted, Summary = summary,
Details = test.Details, AiRequests = imageCount
}, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine(summary);
Console.WriteLine("REPORT " + report);
if (!test.IsCompleted) throw new InvalidOperationException("真实视频未通过整轮验证,详见报告:" + report);
}
finally { Pump(playback.StopAsync()); }
}
private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); }
private static void Until(Func ready)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!ready() && watch.Elapsed < TimeSpan.FromMinutes(15))
{
using var cancellation = new CancellationTokenSource(10);
Dispatcher.UIThread.MainLoop(cancellation.Token);
}
if (!ready()) throw new TimeoutException("真实视频验证超时");
Dispatcher.UIThread.RunJobs();
}
}