增加不向模型泄露期望结果的正例和边界反例审计
This commit is contained in:
parent
94d26ec507
commit
788a274e95
71
tests/VideoFlowTest.Smoke/EvidenceAuditChecks.cs
Normal file
71
tests/VideoFlowTest.Smoke/EvidenceAuditChecks.cs
Normal file
@ -0,0 +1,71 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>显式测试清单指定完成、未开始和接近完成的证据;期望标签绝不发送给视觉服务。</summary>
|
||||
internal static class EvidenceAuditChecks
|
||||
{
|
||||
public sealed record Case(int StepId, string Kind, double[] Times, bool ExpectedCompleted);
|
||||
public static async Task RunAsync(string configPath, string videoPath, string settingsPath, string reportPath, string manifestPath, bool disableThinking)
|
||||
{
|
||||
Directory.CreateDirectory(reportPath);
|
||||
var original = File.ReadAllBytes(configPath);
|
||||
var config = SopConfigLoader.Load(configPath);
|
||||
var cases = JsonSerializer.Deserialize<Case[]>(File.ReadAllText(manifestPath), new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath));
|
||||
var root = settings.RootElement;
|
||||
string Text(string key) => root.TryGetProperty(key, out var value) ? value.GetString() ?? "" : "";
|
||||
using var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
var client = new ConfiguredVisionDecisionClient(http, new SequenceVisionDecisionClient(http,
|
||||
new(Text("endpoint"), Text("model"), Text("apiKey"), disableThinking ? false : null)));
|
||||
using var capture = new VideoCapture(videoPath);
|
||||
if (!capture.IsOpened() || capture.Fps <= 0) throw new IOException("无法打开审计视频");
|
||||
var results = new List<object>(); var allCorrect = true;
|
||||
for (var index = 0; index < cases.Length; index++)
|
||||
{
|
||||
var sample = cases[index];
|
||||
var step = config.Sop.Steps.Single(s => s.Id == sample.StepId); var options = step.AiConfirmation!;
|
||||
var frames = new List<VisionEvidenceFrame>();
|
||||
foreach (var seconds in sample.Times)
|
||||
{
|
||||
var id = (long)Math.Round(seconds * capture.Fps);
|
||||
capture.Set(VideoCaptureProperties.PosFrames, id);
|
||||
using var image = new Mat();
|
||||
if (!capture.Read(image) || image.Empty()) throw new IOException("无法读取审计证据");
|
||||
var mode = VisionImageMode.Resolve(options);
|
||||
if (mode == VisionImageMode.Hand) throw new InvalidOperationException("动态跟手范围必须运行回放审计");
|
||||
var crop = mode == VisionImageMode.FixedRegion ? config.Sop.Regions[options.ImageRegion] : null;
|
||||
var jpeg = VisionDecisionImage.Encode(image, crop);
|
||||
frames.Add(new(id, DateTime.UnixEpoch.AddSeconds(id / capture.Fps), jpeg, id / capture.Fps));
|
||||
File.WriteAllBytes(Path.Combine(reportPath, $"case-{index:D2}-frame-{id:D6}.jpg"), jpeg);
|
||||
}
|
||||
if (frames.Count == 0 || options.EvidenceMode == VisionEvidenceMode.SingleFrame && frames.Count != 1)
|
||||
throw new ArgumentException("单帧审计必须恰有一张图,时序审计须包含真实按序画面");
|
||||
var last = frames[^1];
|
||||
var request = new VisionDecisionRequest(config.Sop.Name, step.Id, step.Name, step.Description, step.Description,
|
||||
last.FrameId, last.CapturedAt, last.Jpeg, options.EvidenceMode,
|
||||
options.EvidenceMode == VisionEvidenceMode.Sequence ? frames : null, last.SourceSeconds);
|
||||
var watch = Stopwatch.StartNew(); VisionDecisionResult? decision = null; string? error = null;
|
||||
try
|
||||
{
|
||||
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(options.TimeoutSeconds));
|
||||
decision = await client.DecideAsync(request, deadline.Token);
|
||||
}
|
||||
catch (Exception failure) { error = failure.GetType().Name; }
|
||||
var accepted = decision is { Completed: true } && decision.EffectiveStatus == VisionDecisionStatus.Completed
|
||||
&& double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1;
|
||||
var correct = error is null && decision?.EffectiveStatus != VisionDecisionStatus.Unsupported && accepted == sample.ExpectedCompleted;
|
||||
allCorrect &= correct;
|
||||
results.Add(new { sample.StepId, sample.Kind, sample.ExpectedCompleted, Accepted = accepted, Correct = correct,
|
||||
Status = decision?.EffectiveStatus.ToString(), decision?.Confidence, decision?.Reason, decision?.EvidenceFrameIds, decision?.CompletionFrameId,
|
||||
Error = error, WallSeconds = watch.Elapsed.TotalSeconds, options.EvidenceMode, Threshold = options.MinConfidence,
|
||||
Frames = frames.Select(f => new { f.FrameId, f.SourceSeconds }).ToArray() });
|
||||
File.WriteAllText(Path.Combine(reportPath, "result.json"), JsonSerializer.Serialize(new
|
||||
{ Config = configPath, Video = videoPath, AllCorrect = allCorrect, Cases = results, ConfigUnchanged = original.SequenceEqual(File.ReadAllBytes(configPath)) },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"审计步骤 {sample.StepId} {sample.Kind}: 正确={correct}, 放行={accepted}, 期望={sample.ExpectedCompleted}, {decision?.Reason ?? error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,13 @@ internal static class LiveVideoFlowChecks
|
||||
}
|
||||
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,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user