diff --git a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs index 18677f2..ed19ef0 100644 --- a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs @@ -1,5 +1,7 @@ using Prism.Commands; using SopHelper.Engine.Sop; +using OpenCvSharp; +using SopHelper.Presentation.Imaging; namespace SopHelper.Training; @@ -9,6 +11,14 @@ public sealed partial class CameraViewModel private Func? _flowTestConfigProvider; private bool _testingFlow; private string _flowTestStatus = "", _flowTestDetails = ""; + private BitmapSource? _flowTestDecisionImage; + private string _flowTestDecisionLabel = ""; + public BitmapSource? FlowTestDecisionImage + { + get => _flowTestDecisionImage; + private set { var old = _flowTestDecisionImage; SetProperty(ref _flowTestDecisionImage, value); old?.Dispose(); } + } + public string FlowTestDecisionLabel { get => _flowTestDecisionLabel; private set => SetProperty(ref _flowTestDecisionLabel, value); } public Func? FlowTestConfigProvider { get => _flowTestConfigProvider; @@ -30,6 +40,8 @@ public sealed partial class CameraViewModel await Playback.StopAsync(); EndFlowTest("开始新的测试"); FlowTestDetails = ""; + FlowTestDecisionImage = null; + FlowTestDecisionLabel = ""; FlowTestStatus = "正在准备流程测试…"; try { @@ -46,11 +58,21 @@ public sealed partial class CameraViewModel if (!ReferenceEquals(_flowTest, test) || _closing) return; FlowTestStatus = status; FlowTestDetails = details; }); + test.DecisionImageCaptured += (jpeg, frameId) => _dispatcher.BeginInvoke(() => + { + if (!ReferenceEquals(_flowTest, test) || _closing) return; + using var image = Cv2.ImDecode(jpeg, ImreadModes.Color); + var stride = checked((int)image.Step()); + FlowTestDecisionImage = BitmapSource.Create(image.Width, image.Height, 96, 96, PixelFormats.Bgr24, + null, image.Data, checked(stride * image.Height), stride); + FlowTestDecisionLabel = $"AI 实际送检图 · 视频帧 {frameId}"; + }); await Task.Run(test.LoadModels); test.Start(); FlowTestDetails = test.Details; FlowTestStatus = "正在播放标准视频并检测流程(使用当前编辑配置)"; Playback.FrameProcessor = test.ProcessFrame; + Playback.WaitForFrameProcessingAsync = test.FinishPendingDecisionAsync; await Playback.PlayAsync(StandardVideoPath); if (IsTestingFlow) Status = "正在测试流程;点击“停止播放”可停止测试"; } @@ -76,6 +98,7 @@ public sealed partial class CameraViewModel private void EndFlowTest(string reason) { Playback.FrameProcessor = null; + Playback.WaitForFrameProcessingAsync = null; if (_flowTest is { } test) { FlowTestStatus = test.Finish(reason); diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index 68d9f41..6984a8a 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -391,6 +391,7 @@ public sealed partial class CameraViewModel : BindableBase await _operation; await Playback.StopAsync(); EndFlowTest("测试已关闭"); + FlowTestDecisionImage = null; try { await Task.Run(_camera.Dispose); } finally { diff --git a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs index 5369d17..b0d3ec7 100644 --- a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs +++ b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs @@ -21,6 +21,7 @@ public sealed class RecordedVideoPlayback : BindableBase private bool _seeking, _reportingProgress; private double? _pendingSeek; private Task _seekTask = Task.CompletedTask; + private CancellationTokenSource? _readCancellation; public BitmapSource? Frame { get => _frame; private set { var old = _frame; SetProperty(ref _frame, value); old?.Dispose(); } } public bool IsPlaying { get => _playing; private set => SetProperty(ref _playing, value); } @@ -40,6 +41,8 @@ public sealed class RecordedVideoPlayback : BindableBase public event Action? Failed; /// 在解码线程处理即将显示的原始帧;Mat 仅在回调期间有效。 public Action? FrameProcessor { get; set; } + /// 流程测试时先收取上一帧的 AI 结果,再读取下一帧。 + public Func? WaitForFrameProcessingAsync { get; set; } public RecordedVideoPlayback() { @@ -78,6 +81,7 @@ public sealed class RecordedVideoPlayback : BindableBase catch { await StopAsync(); throw; } } _startPosition = _position; + _readCancellation ??= new CancellationTokenSource(); _clock.Restart(); IsPlaying = true; _timer.Interval = TimeSpan.FromMilliseconds(Math.Clamp(1000 / _fps, 15, 200)); _timer.Start(); NotifyTime(); @@ -92,10 +96,12 @@ public sealed class RecordedVideoPlayback : BindableBase public async Task StopAsync() { Pause(); _generation++; + _readCancellation?.Cancel(); _pendingSeek = null; await _seekTask; _pendingSeek = null; await WaitForReadAsync(); + _readCancellation?.Dispose(); _readCancellation = null; _readTask = null; _reading = false; var capture = _capture; _capture = null; if (capture is not null) await Task.Run(capture.Dispose); @@ -105,7 +111,7 @@ public sealed class RecordedVideoPlayback : BindableBase public Task SeekAsync(double percent) { - if (!IsLoaded || !double.IsFinite(percent)) return Task.CompletedTask; + if (!IsLoaded || FrameProcessor is not null || !double.IsFinite(percent)) return Task.CompletedTask; _pendingSeek = Math.Clamp(percent, 0, 100); if (!_seeking) _seekTask = SeekPendingAsync(); return _seekTask; @@ -184,8 +190,16 @@ public sealed class RecordedVideoPlayback : BindableBase _reading = true; var capture = _capture; var generation = _generation; - var target = (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps); - var read = _readTask = Task.Run(() => Decode(capture, target)); + // 普通观看追赶实时时钟;流程测试逐帧前进,模型耗时不能丢掉中间动作。 + var target = FrameProcessor is null ? (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps) : (long)capture.PosFrames; + var waitForProcessing = WaitForFrameProcessingAsync; + var token = _readCancellation?.Token ?? CancellationToken.None; + var read = _readTask = Task.Run(async () => + { + if (waitForProcessing is not null) await waitForProcessing(token); + token.ThrowIfCancellationRequested(); + return Decode(capture, target); + }); try { var decoded = await read; diff --git a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs index 87730fc..2927106 100644 --- a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs @@ -18,12 +18,15 @@ public sealed class SopVideoFlowTest : IDisposable private readonly object _gate = new(); private FrameResult? _lastResult; private bool _disposed; + private readonly Dictionary _lastAiFailures = []; public event Action? Changed; + public event Action? DecisionImageCaptured; public bool IsCompleted => _engine.State == EngineState.Completed; public string Details { get { lock (_gate) return string.Join(Environment.NewLine, _steps.Values.OrderBy(s => s.StepId) - .Select(s => $"{(s.IsMet ? "✓" : s.IsCurrent ? "▶" : "○")} {s.StepId} {s.Name}:{s.Message}")); } + .Select(s => $"{(s.IsMet ? "✓" : s.IsCurrent ? "▶" : "○")} {s.StepId} {s.Name}:{s.Message}" + + (!s.IsMet && _lastAiFailures.TryGetValue(s.StepId, out var failure) && failure != s.Message ? $"(最近判定:{failure})" : ""))); } } public string Progress { get { lock (_gate) return $"已完成 {_steps.Values.Count(s => s.IsMet)}/{_steps.Count} 步"; } } @@ -40,6 +43,7 @@ public sealed class SopVideoFlowTest : IDisposable { if (_steps.TryGetValue(step.StepId, out var previous) && previous.IsMet && !step.IsMet) return; _steps[step.StepId] = step; + if (step.Message.StartsWith("AI 未确认完成")) _lastAiFailures[step.StepId] = step.Message; Changed?.Invoke(IsCompleted ? $"流程检测通过,{Progress}" : $"正在测试流程,{Progress}", Details); }; _engine.Completed += () => Changed?.Invoke($"流程检测通过,{Progress}", Details); @@ -71,14 +75,20 @@ public sealed class SopVideoFlowTest : IDisposable { if (_disposed) return; _lastResult = result; - _engine.ProcessFrame(result, captureDecisionImage: region => VisionDecisionImage.Encode(image, region)); + _engine.ProcessFrame(result, captureDecisionImage: region => + { + var jpeg = VisionDecisionImage.Encode(image, region); + DecisionImageCaptured?.Invoke(jpeg, result.FrameId); + return jpeg; + }); } } - public async Task FinishPendingDecisionAsync() + public async Task FinishPendingDecisionAsync(CancellationToken cancellationToken = default) { while (true) { + cancellationToken.ThrowIfCancellationRequested(); lock (_gate) { if (_disposed || !_engine.HasPendingDecision || _lastResult is null) return; @@ -86,7 +96,7 @@ public sealed class SopVideoFlowTest : IDisposable _engine.ProcessFrame(_lastResult); if (!_engine.HasPendingDecision) return; } - await Task.Delay(20).ConfigureAwait(false); + await Task.Delay(20, cancellationToken).ConfigureAwait(false); } } diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index 47ce770..33855c7 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -449,9 +449,15 @@ - - - + + + + + + + + + diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs index 179fbbe..d04f1c7 100644 --- a/tests/VideoFlowTest.Smoke/Program.cs +++ b/tests/VideoFlowTest.Smoke/Program.cs @@ -54,11 +54,14 @@ internal static class Program var fake = new FakeDecision(); using var test = new SopVideoFlowTest(config, fake); test.Start(); + byte[]? sentImage = null; + test.DecisionImageCaptured += (jpeg, frameId) => { sentImage = jpeg; Check(frameId == 12, "Diagnostic image identifies the actual submitted video frame"); }; using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); var frame = new FrameResult { FrameId = 12, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] }; test.ProcessResult(frame, image); Until(() => fake.Request is not null); Check(!test.IsCompleted && fake.Request!.FrameId == 12 && fake.Request.Jpeg.Length > 0, "Hand trigger submits the exact video frame to AI without completing early"); + Check(ReferenceEquals(sentImage, fake.Request!.Jpeg), "Diagnostic image is exactly the image sent to AI"); var drain = test.FinishPendingDecisionAsync(); Check(!drain.IsCompleted, "End of video waits for the outstanding AI decision"); fake.Result.SetResult(new(true, .99, "已安装")); @@ -71,6 +74,13 @@ internal static class Program var cancelledDrain = cancelled.FinishPendingDecisionAsync(); cancelled.Dispose(); Pump(cancelledDrain); Check(!cancelled.IsCompleted, "Stopping a test cancels pending AI without reporting success"); + var rejectedClient = new FakeDecision(); + using var rejected = new SopVideoFlowTest(config, rejectedClient); rejected.Start(); + rejected.ProcessResult(frame, image); + rejectedClient.Result.SetResult(new(false, .15, "裁剪图没有纸盒")); + Pump(rejected.FinishPendingDecisionAsync()); + rejected.ProcessResult(new FrameResult { FrameId = 13, Size = (64, 48) }, image); + Check(rejected.Details.Contains("裁剪图没有纸盒") && rejected.Details.Contains("未检出手"), "A later hand message preserves the last AI rejection reason"); } private static void CheckVideoPage(string root) @@ -91,6 +101,7 @@ internal static class Program using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); writer.Write(image); } } + CheckSequentialPlayback(model.StandardVideoPath); // Unsupported condition exercises playback and incomplete results without hardware/models/API. config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }]; model.FlowTestConfigProvider = () => config; @@ -119,6 +130,28 @@ internal static class Program window.Close(); vm.OnDialogClosed(); } + private static void CheckSequentialPlayback(string path) + { + var playback = new RecordedVideoPlayback(); + var ids = new System.Collections.Concurrent.ConcurrentQueue(); + var acknowledgement = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + playback.FrameProcessor = (_, id, _) => { Thread.Sleep(140); ids.Enqueue(id); }; + playback.WaitForFrameProcessingAsync = token => ids.IsEmpty ? Task.CompletedTask : acknowledgement.Task.WaitAsync(token); + Pump(playback.PlayAsync(path)); + using (var wait = new CancellationTokenSource(350)) Dispatcher.UIThread.MainLoop(wait.Token); + Check(ids.Count == 1 && playback.IsPlaying, "Playback holds the trigger frame while its AI decision is pending"); + acknowledgement.SetResult(); + Until(() => playback.IsAtEnd); + Check(ids.SequenceEqual(Enumerable.Range(0, 10).Select(i => (long)i)), "Slow flow detection processes every video frame in order without clock catch-up or dropped actions"); + Pump(playback.StopAsync()); + ids.Clear(); + acknowledgement = new(TaskCreationOptions.RunContinuationsAsynchronously); + Pump(playback.PlayAsync(path)); + using (var wait = new CancellationTokenSource(200)) Dispatcher.UIThread.MainLoop(wait.Token); + Pump(playback.StopAsync()); + Check(!playback.IsLoaded && ids.Count == 1, "Stop cancels a pending AI wait without reading later frames"); + } + private static void Until(Func ready) { var watch = System.Diagnostics.Stopwatch.StartNew();