using System.Text.Json; using Avalonia.Threading; using SopHelper.Engine.Sop; using SopHelper.Training; using SopHelper.Engine.SopAgent; /// 显式指定 --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 (Value("--evidence-audit") is { } manifest) { Pump(Task.Run(() => EvidenceAuditChecks.RunAsync(path, video, Value("--agent-settings") ?? throw new ArgumentException("需要 --agent-settings"), Value("--report") ?? throw new ArgumentException("需要 --report"), manifest, args.Contains("--disable-thinking")))); return; } if (args.Contains("--sequence-trial")) { Pump(Task.Run(() => SequenceTrialChecks.RunAsync(path, video, Value("--agent-settings") ?? throw new ArgumentException("需要 --agent-settings"), Value("--report") ?? throw new ArgumentException("需要 --report"), double.Parse(Value("--stop-seconds") ?? "Infinity", System.Globalization.CultureInfo.InvariantCulture), args.Contains("--disable-thinking")))); return; } if (args.Contains("--agent-benchmark")) { Pump(Task.Run(() => AgentBenchmarkChecks.RunAsync(path, video, Value("--agent-settings") ?? throw new ArgumentException("需要 --agent-settings"), Value("--report") ?? throw new ArgumentException("需要 --report"), Value("--reuse-draft"), args.Contains("--verify-current-first"), args.Contains("--disable-thinking"), Value("--draft-file"), int.Parse(Value("--reference-step") ?? "0"), args.Contains("--replay-only"), Value("--instructions"), Value("--boundary-manifest")))); return; } if (args.Contains("--agent-generate")) { CheckAgentGeneration(path, video, Value("--agent-settings") ?? throw new ArgumentException("需要 --agent-settings"), Value("--report") ?? throw new ArgumentException("需要 --report")); return; } if (args.Contains("--verify-draft")) { CheckDraftVerifier(path, video, Value("--report")); return; } 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 CheckDraftVerifier(string path, string videoPath, string? reportPath) { var template = SopConfigLoader.Load(path); var video = SopVideoSampler.ReadInfo(videoPath, default); var duration = video.DurationSeconds / template.Sop.Steps.Count; var frames = SopVideoSampler.ReadFrames(video, template.Sop.Steps.Select((s, i) => (i + .5) * duration).ToArray(), 0, default); video = video with { Frames = frames }; var draft = new SopVideoDraft { Steps = template.Sop.Steps.Select((step, i) => new SopDraftStep { Name = step.Name, Description = step.Description, StartSeconds = i * duration, EndSeconds = (i + 1) * duration, EvidenceFrame = i, Method = step.Detection!.Method, Region = step.Detection.Region, FromRegion = step.Detection.FromRegion, ToRegion = step.Detection.ToRegion, Hand = step.Detection.Hand, StableFrames = step.Detection.StableFrames, Tolerance = step.Detection.Tolerance, ImageMode = step.AiConfirmation!.ImageMode, ImageRegion = step.AiConfirmation.ImageRegion }).ToList() }; SopVideoDraftClient.Validate(draft, video, template.Sop.Regions.Keys.ToArray(), template.Sop.Regions); var before = File.ReadAllBytes(path); var verification = Task.Run(() => new SopDraftVideoVerifier().VerifyAsync(draft, video, template, new Progress(message => Console.WriteLine(message)), default)); Pump(verification); var result = verification.GetAwaiter().GetResult(); if (reportPath is not null) { Directory.CreateDirectory(reportPath); File.WriteAllText(Path.Combine(reportPath, "draft-verification.json"), JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true })); foreach (var image in result.Images) File.WriteAllBytes(Path.Combine(reportPath, $"step-{image.StepId}-frame-{image.FrameId}.jpg"), image.Jpeg); } if (!before.SequenceEqual(File.ReadAllBytes(path))) throw new Exception("回测修改了原配方"); if (!result.Passed || result.Steps.Any(s => !s.Completed)) throw new Exception("草稿真实视频验证未通过:" + result.Summary); Console.WriteLine("PASS: Agent真实视频草稿验证器、后台线程调用、原配方不变:" + result.Summary); } private static void CheckAgentGeneration(string path, string videoPath, string settingsPath, string reportPath) { using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath)); var options = settings.RootElement; string Text(string key) => options.TryGetProperty(key, out var value) ? value.GetString() ?? "" : ""; int Number(string key, int fallback) => options.TryGetProperty(key, out var value) ? value.GetInt32() : fallback; var connection = new SopAgentConnection(Text("endpoint"), Text("model"), Text("apiKey"), Number("contextLength", 131702), Number("maxTokens", 8192), TimeoutSeconds: Number("timeoutSeconds", 300)); var template = SopConfigLoader.Load(path); template.Sop.Steps = []; var before = File.ReadAllBytes(path); var video = SopVideoSampler.ReadInfo(videoPath, default); Directory.CreateDirectory(reportPath); var round = 0; var progress = new Progress(message => Console.WriteLine(message)); using var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(10)); var request = new SopVideoAnalysisRequest(template.Sop.Name, "按标准视频中的实际工艺生成完整有序步骤,并用真实回测结果修订。", video, template.Sop.Regions.Keys.ToArray(), Number("maxFrames", 3), progress, RegionDefinitions: template.Sop.Regions, VerifyDraft: async (draft, observed, token) => { var index = Interlocked.Increment(ref round); var report = await new SopDraftVideoVerifier().VerifyAsync(draft, observed, template, progress, token); File.WriteAllText(Path.Combine(reportPath, $"round-{index}-draft.json"), JsonSerializer.Serialize(draft, new JsonSerializerOptions { WriteIndented = true })); File.WriteAllText(Path.Combine(reportPath, $"round-{index}-result.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); foreach (var image in report.Images) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-step-{image.StepId}-frame-{image.FrameId}.jpg"), image.Jpeg); return report; }); var analysis = Task.Run(() => new SopVideoAgentClient(http).AnalyzeAsync(request, connection, cancellation.Token)); Pump(analysis); var final = analysis.GetAwaiter().GetResult(); if (!before.SequenceEqual(File.ReadAllBytes(path))) throw new Exception("Agent 自动回测修改了原配方"); if (final.Verification?.Passed != true) throw new Exception("Agent 在三轮内未通过标准视频回测:" + final.Verification?.Summary); Console.WriteLine($"PASS: 当前Agent模型生成并自动回测修订:{round}轮,{final.Steps.Count}步,原配方不变"); } 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(); } }