From b90c8781fd13df85302ffb0b2461460f40c645d7 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Tue, 17 Nov 2026 23:12:10 +0800 Subject: [PATCH] =?UTF-8?q?SOP=E6=B5=81=E7=A8=8B=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=A0=87=E5=87=86=E5=BD=95=E5=83=8F=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E6=A3=80=E6=B5=8B=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Training/CameraFlowTest.cs | 88 +++++++++++ .../Training/CameraViewModel.cs | 22 ++- .../Training/RecordedVideoPlayback.cs | 4 + .../Training/SopVideoFlowTest.cs | 104 +++++++++++++ .../VVMs/RecipeEditor/RecipeEditor.axaml | 7 +- .../RecipeEditor/RecipeEditorViewModel.cs | 1 + .../Sop/SopEngine.cs | 2 + tests/VideoFlowTest.Smoke/Program.cs | 142 ++++++++++++++++++ .../VideoFlowTest.Smoke.csproj | 7 + 9 files changed, 369 insertions(+), 8 deletions(-) create mode 100644 src/SopHelper.Avalonia/Training/CameraFlowTest.cs create mode 100644 src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs create mode 100644 tests/VideoFlowTest.Smoke/Program.cs create mode 100644 tests/VideoFlowTest.Smoke/VideoFlowTest.Smoke.csproj diff --git a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs new file mode 100644 index 0000000..18677f2 --- /dev/null +++ b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs @@ -0,0 +1,88 @@ +using Prism.Commands; +using SopHelper.Engine.Sop; + +namespace SopHelper.Training; + +public sealed partial class CameraViewModel +{ + private SopVideoFlowTest? _flowTest; + private Func? _flowTestConfigProvider; + private bool _testingFlow; + private string _flowTestStatus = "", _flowTestDetails = ""; + public Func? FlowTestConfigProvider + { + get => _flowTestConfigProvider; + set { _flowTestConfigProvider = value; UpdateCommands(); } + } + public DelegateCommand TestFlowCommand { get; } + public bool IsTestingFlow + { + get => _testingFlow; + private set { SetProperty(ref _testingFlow, value); StateChanged(); } + } + public bool CanSeekVideo => Playback.IsLoaded && !IsTestingFlow && !IsBusy; + public string FlowTestStatus { get => _flowTestStatus; private set => SetProperty(ref _flowTestStatus, value); } + public string FlowTestDetails { get => _flowTestDetails; private set => SetProperty(ref _flowTestDetails, value); } + + private async Task StartFlowTestAsync() + { + if (IsRecording || IsTestingFlow) return; + await Playback.StopAsync(); + EndFlowTest("开始新的测试"); + FlowTestDetails = ""; + FlowTestStatus = "正在准备流程测试…"; + try + { + var test = new SopVideoFlowTest(FlowTestConfigProvider!()); + _flowTest = test; + IsTestingFlow = true; + if (IsPreviewing) + { + await Task.Run(_camera.Disconnect); + ClearPreview(); IsPreviewing = false; + } + test.Changed += (status, details) => _dispatcher.BeginInvoke(() => + { + if (!ReferenceEquals(_flowTest, test) || _closing) return; + FlowTestStatus = status; FlowTestDetails = details; + }); + await Task.Run(test.LoadModels); + test.Start(); + FlowTestDetails = test.Details; + FlowTestStatus = "正在播放标准视频并检测流程(使用当前编辑配置)"; + Playback.FrameProcessor = test.ProcessFrame; + await Playback.PlayAsync(StandardVideoPath); + if (IsTestingFlow) Status = "正在测试流程;点击“停止播放”可停止测试"; + } + catch (Exception error) + { + await Playback.StopAsync(); + EndFlowTest("测试失败"); + FlowTestStatus = "测试失败:" + error.Message; + throw; + } + } + + // 仅在解码任务结束后调用,避免释放正在推理的模型。 + private async Task CompleteFlowTestAsync() + { + var test = _flowTest; + if (test is null) return; + FlowTestStatus = "标准视频播放结束,正在收取最后的 AI 判定…"; + await test.FinishPendingDecisionAsync(); + if (ReferenceEquals(_flowTest, test)) EndFlowTest("标准视频播放结束"); + } + + private void EndFlowTest(string reason) + { + Playback.FrameProcessor = null; + if (_flowTest is { } test) + { + FlowTestStatus = test.Finish(reason); + FlowTestDetails = test.Details; + _flowTest = null; + test.Dispose(); + } + IsTestingFlow = false; + } +} diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index 6773952..68d9f41 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -13,7 +13,7 @@ using Prism.Mvvm; namespace SopHelper.Training; -public sealed class CameraViewModel : BindableBase +public sealed partial class CameraViewModel : BindableBase { private readonly ICameraService _camera; private readonly VideoRecorder _recorder; @@ -90,21 +90,27 @@ public sealed class CameraViewModel : BindableBase SaveDirectory = _recipeRecordingDirectory ?? ReadSaveDirectory(root); } catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; } - PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null)); + PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && !IsTestingFlow && (IsPreviewing || SelectedCamera != null)); StartRecordingCommand = Command(StartRecordingAsync, () => !IsBusy && !_closing && !IsRecording && !HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame); StopRecordingCommand = Command(() => { StopRecording(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording); PauseCommand = Command(() => { TogglePause(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording); - RestartCommand = Command(RestartRecordingAsync, () => _sopStandard && !IsBusy && !_closing && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame); - PlayVideoCommand = Command(ToggleVideoPlaybackAsync, () => _sopStandard && !IsBusy && !_closing && !IsRecording && HasStandardVideo); - StopVideoCommand = Command(async () => { await Playback.StopAsync(); Status = "视频播放已停止"; }, () => !IsBusy && !_closing && Playback.IsLoaded); + RestartCommand = Command(RestartRecordingAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame); + PlayVideoCommand = Command(ToggleVideoPlaybackAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo); + TestFlowCommand = Command(StartFlowTestAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && FlowTestConfigProvider is not null); + StopVideoCommand = Command(async () => { await Playback.StopAsync(); EndFlowTest("测试已停止"); Status = "视频播放已停止"; }, () => !IsBusy && !_closing && Playback.IsLoaded); Playback.PropertyChanged += (_, e) => { if (e.PropertyName is nameof(Playback.Frame) or nameof(Playback.IsLoaded)) RaisePropertyChanged(nameof(DisplayImage)); if (e.PropertyName is nameof(Playback.IsPlaying) or nameof(Playback.IsLoaded) or nameof(Playback.IsAtEnd)) { RaisePropertyChanged(nameof(PlayVideoButtonText)); UpdateCommands(); } - if (e.PropertyName == nameof(Playback.IsAtEnd) && Playback.IsAtEnd) Status = "视频播放结束,可点击“重新播放”再次观看"; + if (e.PropertyName == nameof(Playback.IsLoaded)) RaisePropertyChanged(nameof(CanSeekVideo)); + if (e.PropertyName == nameof(Playback.IsAtEnd) && Playback.IsAtEnd) + { + if (IsTestingFlow) _ = CompleteFlowTestAsync(); + Status = "视频播放结束,可点击“重新播放”再次观看"; + } }; - Playback.Failed += message => Status = message; + Playback.Failed += message => { EndFlowTest(message); Status = message; }; BrowseCommand = Command(async () => { var picker = new OpenFolderDialog { Title = "选择录像保存目录" }; @@ -153,6 +159,7 @@ public sealed class CameraViewModel : BindableBase RaisePropertyChanged(nameof(CanChangeDirectory)); RaisePropertyChanged(nameof(SelectedCameraName)); RaisePropertyChanged(nameof(PreviewButtonText)); UpdateCommands(); RaisePropertyChanged(nameof(PauseButtonText)); RaisePropertyChanged(nameof(HasStandardVideo)); + RaisePropertyChanged(nameof(CanSeekVideo)); } private async Task TogglePreviewAsync() { @@ -383,6 +390,7 @@ public sealed class CameraViewModel : BindableBase _closing = true; _timer.Stop(); StateChanged(); await _operation; await Playback.StopAsync(); + EndFlowTest("测试已关闭"); try { await Task.Run(_camera.Dispose); } finally { diff --git a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs index 3fd2230..5369d17 100644 --- a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs +++ b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs @@ -38,6 +38,8 @@ public sealed class RecordedVideoPlayback : BindableBase } public string TimeText => $"{TimeSpan.FromSeconds(_position):mm\\:ss} / {TimeSpan.FromSeconds(_duration):mm\\:ss}"; public event Action? Failed; + /// 在解码线程处理即将显示的原始帧;Mat 仅在回调期间有效。 + public Action? FrameProcessor { get; set; } public RecordedVideoPlayback() { @@ -213,6 +215,8 @@ public sealed class RecordedVideoPlayback : BindableBase if (!capture.Grab()) return new(null, 0); using var frame = new Mat(); if (!capture.Read(frame) || frame.Empty()) return new(null, 0); + var frameId = Math.Max(0, (long)capture.PosFrames - 1); + FrameProcessor?.Invoke(frame, frameId, frameId / _fps); var stride = checked((int)frame.Step()); var image = BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, null, frame.Data, checked(stride * frame.Height), stride); diff --git a/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs new file mode 100644 index 0000000..87730fc --- /dev/null +++ b/src/SopHelper.Avalonia/Training/SopVideoFlowTest.cs @@ -0,0 +1,104 @@ +using System.Net.Http; +using OpenCvSharp; +using SopHelper.Engine.Common; +using SopHelper.Engine.Inference; +using SopHelper.Engine.Sop; + +namespace SopHelper.Training; + +/// 独立的录像测试轮次,使用生产 SOP 引擎,不影响运行页统计。 +public sealed class SopVideoFlowTest : IDisposable +{ + private static readonly HttpClient VisionHttp = new() { Timeout = Timeout.InfiniteTimeSpan }; + private readonly MediaPipeHandDetector _hands = new(); + private readonly SopEngine _engine = new(); + private readonly Dictionary _steps = []; + private readonly int _stride; + private long _seen; + private readonly object _gate = new(); + private FrameResult? _lastResult; + private bool _disposed; + public event Action? Changed; + 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}")); } + } + public string Progress { get { lock (_gate) return $"已完成 {_steps.Values.Count(s => s.IsMet)}/{_steps.Count} 步"; } } + + public SopVideoFlowTest(SopConfig config, IVisionDecisionClient? visionClient = null) + { + if (config.Sop.Steps.Count == 0) throw new InvalidOperationException("请先添加流程步骤,再测试流程"); + // 深拷贝,测试轮次不修改编辑中的配方,也不自动开始下一轮。 + var snapshot = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config)); + snapshot.Sop.Settings.AutoResetOnComplete = false; + snapshot.Sop.Model = null; + _stride = Math.Max(1, snapshot.Sop.Settings.FrameStride); + _engine.VisionDecisionClient = visionClient ?? new ConfiguredVisionDecisionClient(VisionHttp); + _engine.StepSnapshotChanged += step => + { + if (_steps.TryGetValue(step.StepId, out var previous) && previous.IsMet && !step.IsMet) return; + _steps[step.StepId] = step; + Changed?.Invoke(IsCompleted ? $"流程检测通过,{Progress}" : $"正在测试流程,{Progress}", Details); + }; + _engine.Completed += () => Changed?.Invoke($"流程检测通过,{Progress}", Details); + _engine.Load(snapshot); + } + + public void Start() => _engine.Start(); + + public void LoadModels() + { + if (!_engine.Config.Sop.Steps.Any(s => ConditionMethod.RequiresHandDetection(s.Detection?.Method))) return; + _hands.Load(Path.Combine(AppContext.BaseDirectory, "models/palm_detection_full_Nx3x192x192_post.onnx"), + Path.Combine(AppContext.BaseDirectory, "models/hand_landmark_sparse_Nx3x224x224.onnx"), requireGpu: OperatingSystem.IsLinux()); + if (!_hands.IsReady) throw new InvalidOperationException("手部模型缺失,无法测试流程,请检查 models 目录"); + } + + public void ProcessFrame(Mat image, long frameId, double seconds) + { + if (++_seen % _stride != 0 || IsCompleted) return; + var result = new FrameResult { FrameId = frameId, Timestamp = DateTime.Now, Size = (image.Width, image.Height) }; + if (_engine.RequiresHandDetection) result.Hands = _hands.Detect(image); + ProcessResult(result, image); + } + + /// 使用与正式运行相同的原帧裁剪、手部门控和 AI 完成判定。 + public void ProcessResult(FrameResult result, Mat image) + { + lock (_gate) + { + if (_disposed) return; + _lastResult = result; + _engine.ProcessFrame(result, captureDecisionImage: region => VisionDecisionImage.Encode(image, region)); + } + } + + public async Task FinishPendingDecisionAsync() + { + while (true) + { + lock (_gate) + { + if (_disposed || !_engine.HasPendingDecision || _lastResult is null) return; + // 只消费已发送的判定,不在结束画面重复触发新的送检。 + _engine.ProcessFrame(_lastResult); + if (!_engine.HasPendingDecision) return; + } + await Task.Delay(20).ConfigureAwait(false); + } + } + + public string Finish(string reason) + { + lock (_gate) return IsCompleted + ? $"{reason};流程检测通过,{Progress}" + : $"{reason};流程未完成,{Progress},停在步骤 {_engine.CurrentStep?.Id}「{_engine.CurrentStep?.Name}」"; + } + + public void Dispose() + { + lock (_gate) { _disposed = true; _engine.Stop(); _hands.Dispose(); } + } +} diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index 3e75d65..47ce770 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -436,17 +436,22 @@