diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index a484f3f..948774b 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -162,7 +162,7 @@ public class SopPageViewModel : ViewModelBase
ResetCountsCommand = ConfigurationCommand(ResetCounts, () => StepCards.Count > 0);
PlayStandardSopCommand = ConfigurationCommand(async () => await ToggleStandardSopAsync(), () => !_isCameraBusy && !_deletingRecipe && !_transferringRecipe
&& (_standardSopCancellation is not null || StandardSopVideoPath is { } path && File.Exists(path)));
- ApplyRecipeCommand = ConfigurationCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
+ ApplyRecipeCommand = ConfigurationCommand(() => ApplyRecipe(), () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = ConfigurationCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = ConfigurationCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = ConfigurationCommand(NewRecipe, () => CanSelectCamera);
@@ -1011,7 +1011,7 @@ public class SopPageViewModel : ViewModelBase
if (!await SopHelper.Models.CameraSettingsStore.Current.ConnectAsync(_camera, SelectedCamera)) return;
- ApplyRecipe();
+ if (!ApplyRecipe()) return;
try
{
@@ -1043,25 +1043,24 @@ public class SopPageViewModel : ViewModelBase
StatusText = "运行中";
}
- /// 读取所选配方并覆盖独立运行设置,按手部需求加载模型,再重建步骤卡和区域列表。
- private void ApplyRecipe()
+ /// 准备所选配方和模型,成功后一起切换引擎及界面。未选中配方或文件已移除时返回 false。
+ private bool ApplyRecipe()
{
- HandResult = null;
- if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
+ var selected = SelectedRecipe;
+ if (string.IsNullOrWhiteSpace(selected)) return false;
- var path = RecipePath(SelectedRecipe);
+ var path = RecipePath(selected);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
- return;
+ return false;
}
var config = SopConfigLoader.Load(path);
- _runtimeOptions = _runtimeStore.LoadOrMigrate(config);
- _runtimeOptions.Apply(config);
- RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
-
- _engine.Load(config);
+ var runtimeOptions = _runtimeStore.LoadOrMigrate(config);
+ runtimeOptions.Apply(config);
+ // 提前读取统计,避免在切换管线之后才遇到存储错误。
+ _engine.GetStatistics(config.Sop.Name);
var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
var options = new PipelineOptions
@@ -1073,9 +1072,13 @@ public class SopPageViewModel : ViewModelBase
RequireGpu = OperatingSystem.IsLinux(),
};
- try { _pipeline.LoadModels(options); }
- finally { RaisePropertyChanged(nameof(InferenceBackendText)); }
- ActiveRecipe = SelectedRecipe;
+ _pipeline.LoadModels(options);
+ _engine.Load(config);
+ _runtimeOptions = runtimeOptions;
+ HandResult = null;
+ ActiveRecipe = selected;
+ RaisePropertyChanged(nameof(InferenceBackendText));
+ RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
Log("info", $"推理设备:手部={_pipeline.HandBackend},步骤确认={VisionProviderName}");
ClearProcessImages();
@@ -1106,6 +1109,7 @@ public class SopPageViewModel : ViewModelBase
if (needsHands && (options.PalmModelPath is null || options.LandmarkModelPath is null))
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
+ return true;
}
///
diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
index ff2fab1..d3a3d87 100644
--- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
@@ -39,7 +39,7 @@ public class PipelineOptions
public class DetectionPipeline : IDisposable
{
private readonly ICameraService _camera;
- private readonly MediaPipeHandDetector _hand = new();
+ private MediaPipeHandDetector _hand = new();
private PipelineOptions _options = new();
private long _seen;
@@ -83,39 +83,50 @@ public class DetectionPipeline : IDisposable
_camera.FrameArrived += OnFrame;
}
- ///
- /// 加载模型。缺文件不抛异常——记进 Warnings,让界面提示,程序照常起。
- ///
+ /// 先准备新模型,再停止处理并切换。必需的 GPU 初始化失败时保留原模型和管线配置;缺文件仍只记录警告。
public void LoadModels(PipelineOptions options)
{
- StopProcessing();
- _options = options;
- Warnings = [];
- _hand.Dispose();
-
- if (options.PalmModelPath is not null && options.LandmarkModelPath is not null)
+ var next = new MediaPipeHandDetector();
+ var warnings = new List();
+ try
{
- if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
+ if (options.PalmModelPath is not null && options.LandmarkModelPath is not null)
{
- try
+ if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
{
- _hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu, options.RequireGpu);
- if (_hand.GpuFallbackReason is not null) Warnings.Add($"手部 GPU 不可用,已回退 CPU:{_hand.GpuFallbackReason}");
+ try
+ {
+ next.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu, options.RequireGpu);
+ if (next.GpuFallbackReason is not null) warnings.Add($"手部 GPU 不可用,已回退 CPU:{next.GpuFallbackReason}");
+ }
+ catch (Exception ex)
+ {
+ if (options.RequireGpu) throw;
+ warnings.Add("手部模型加载失败:" + ex.Message);
+ }
}
- catch (Exception ex)
+ else
{
- Warnings.Add("手部模型加载失败:" + ex.Message);
- if (options.RequireGpu) throw;
+ warnings.Add("MediaPipe 手部模型缺失,手部类条件不会判定");
}
}
- else
- {
- Warnings.Add("MediaPipe 手部模型缺失,手部类条件不会判定");
- }
+
+ next.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold,
+ MediaPipeHandDetector.DefaultKeypointThreshold, Math.Max(1, options.MaxHands));
+ StopProcessing();
+ }
+ catch
+ {
+ next.Dispose();
+ throw;
}
- _hand.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold,
- MediaPipeHandDetector.DefaultKeypointThreshold, Math.Max(1, options.MaxHands));
+ // 旧工作线程退出后,交接模型所有权并释放旧会话。
+ var previous = _hand;
+ _hand = next;
+ _options = options;
+ Warnings = warnings;
+ previous.Dispose();
}
///
diff --git a/tests/Pipeline.Smoke/Program.cs b/tests/Pipeline.Smoke/Program.cs
index 3617de3..9f77287 100644
--- a/tests/Pipeline.Smoke/Program.cs
+++ b/tests/Pipeline.Smoke/Program.cs
@@ -61,6 +61,17 @@ pipeline.ResultArrived += frame =>
if(frame.FrameId == 1) { entered.Set(); if(!release.Wait(TimeSpan.FromSeconds(5)))throw new Exception("Worker release timed out"); }
};
if(!await pipeline.StartAsync())throw new Exception("Start failed");
+// 用程序集模拟存在但不可加载的模型,验证失败不会停止原来的帧处理。
+var previousWarnings = pipeline.Warnings;
+var invalidModel = typeof(DetectionPipeline).Assembly.Location;
+var modelLoadRejected = false;
+try
+{
+ pipeline.LoadModels(new PipelineOptions { PalmModelPath = invalidModel, LandmarkModelPath = invalidModel, RequireGpu = true });
+}
+catch (Exception) { modelLoadRejected = true; }
+if (!modelLoadRejected || !ReferenceEquals(previousWarnings, pipeline.Warnings))
+ throw new Exception("模型加载失败后应保留原管线状态");
try
{
await Task.Run(() => camera.Emit(1)).WaitAsync(TimeSpan.FromSeconds(2));