From 60b093a13fd05368d008520d958ab2b2d85fe265 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Mon, 9 Nov 2026 11:48:54 +0800
Subject: [PATCH] =?UTF-8?q?=E8=AE=AD=E7=BB=83=E5=90=8E=E8=87=AA=E5=8A=A8?=
=?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=B9=B6=E6=8C=89=E9=85=8D=E6=96=B9=E5=8A=A0?=
=?UTF-8?q?=E8=BD=BDONNX=E6=A8=A1=E5=9E=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Presentation/DesktopPlatform.cs | 9 +++++
.../Training/MainViewModel.cs | 10 +++--
.../Training/TrainingPage.axaml | 5 ++-
.../VVMs/SopPage/SopPageViewModel.cs | 32 ++++++++++++++-
tests/Avalonia.Smoke/Program.cs | 26 ++++++++++++
tests/Training.Smoke/test_recipe_training.py | 40 ++++++++++++++++++-
tests/test_worker.py | 11 ++---
tools/worker.py | 31 ++++++++++----
8 files changed, 144 insertions(+), 20 deletions(-)
diff --git a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
index 0ebd754..3dc66d6 100644
--- a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
+++ b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
@@ -7,6 +7,15 @@ namespace SopHelper.Presentation;
internal static class DesktopPlatform
{
+ public static string WorkspaceRoot
+ {
+ get
+ {
+ for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
+ if (File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.slnx"))) return directory.FullName;
+ return AppContext.BaseDirectory;
+ }
+ }
public static Window Owner => ((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current!.ApplicationLifetime!).MainWindow!;
public static string PythonPath
{
diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs
index ad1ec73..41a09a7 100644
--- a/src/SopHelper.Avalonia/Training/MainViewModel.cs
+++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs
@@ -33,6 +33,8 @@ public sealed class MainViewModel : BindableBase
public string TrainingStatus { get => _trainingStatus; private set => SetProperty(ref _trainingStatus, value); }
public string TrainingMetrics { get => _trainingMetrics; private set => SetProperty(ref _trainingMetrics, value); }
public string LatestWeights { get => _latestWeights; private set => SetProperty(ref _latestWeights, value); }
+ private string _latestOnnx = "";
+ public string LatestOnnx { get => _latestOnnx; private set => SetProperty(ref _latestOnnx, value); }
public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
public string TrainingOutputDirectory { get; set; } = "";
public string? VideoImportDirectory { get; set; }
@@ -120,9 +122,7 @@ public sealed class MainViewModel : BindableBase
public MainViewModel(WorkerClient worker)
{
_worker = worker;
- var directory = new DirectoryInfo(AppContext.BaseDirectory);
- while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.slnx"))) directory = directory.Parent;
- Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.slnx")) ? directory.FullName : AppContext.BaseDirectory;
+ Root = DesktopPlatform.WorkspaceRoot;
LoadSettings();
SaveParametersCommand = Command(() =>
{
@@ -326,6 +326,7 @@ public sealed class MainViewModel : BindableBase
if (item.TryGetProperty("runDirectory", out var directory)) TrainingRunDirectory = directory.GetString() ?? "";
if (item.TryGetProperty("weights", out var weights)) LatestWeights = weights.GetString() ?? "";
}
+ if (item.TryGetProperty("onnx", out var onnx)) LatestOnnx = onnx.GetString() ?? "";
});
if (item.TryGetProperty("modules", out var modules)) Append(modules.ToString());
if (item.TryGetProperty("output", out var output)) Append(output.GetString() ?? "");
@@ -358,13 +359,14 @@ public sealed class MainViewModel : BindableBase
private void LoadTrainingResult()
{
if (IsTraining) return;
- LatestWeights = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
+ LatestWeights = ""; LatestOnnx = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(string.IsNullOrWhiteSpace(RequireProject().RecipeDirectory) ? RequireProject().DirectoryPath : RequireProject().RecipeDirectory, "latest-model.json");
if (!File.Exists(file)) return;
try
{
using var result = JsonDocument.Parse(File.ReadAllText(file));
LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
+ if (result.RootElement.TryGetProperty("onnx", out var onnx)) LatestOnnx = onnx.GetString() ?? "";
TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
}
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml
index 5bb205e..8ec80e7 100644
--- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml
+++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml
@@ -111,8 +111,9 @@
-
-
+
+
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 5dc03fc..54d1a06 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -5,6 +5,7 @@ using System.Text.Json;
using Avalonia.Media;
using ImageSource = Avalonia.Media.IImage;
using SopHelper.Presentation.Imaging;
+using SopHelper.Presentation;
using SopHelper.Presentation.Threading;
using OpenCvSharp;
using Prism.Commands;
@@ -612,9 +613,10 @@ public class SopPageViewModel : ViewModelBase
var config = SopConfigLoader.Load(path);
+ LoadTrainedRecipeModel(config);
_engine.Load(config);
- // 模型:配方写了就用配方的,没写就跳过(只有手部/计时类条件能工作)
+ // 优先使用本配方训练发布的 ONNX,否则使用配方配置中的模型。
var options = new PipelineOptions
{
YoloModelPath = ResolveModel(config.Sop.Model?.Path),
@@ -652,6 +654,34 @@ public class SopPageViewModel : ViewModelBase
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
}
+ private void LoadTrainedRecipeModel(SopConfig config)
+ {
+ var recipeName = Path.GetFileNameWithoutExtension(SelectedRecipe);
+ var manifest = Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "training", recipeName!, "latest-model.json");
+ if (!File.Exists(manifest)) return;
+ try
+ {
+ using var document = JsonDocument.Parse(File.ReadAllText(manifest));
+ var model = document.RootElement;
+ if (!model.TryGetProperty("onnx", out var onnx)) return; // 兼容尚未导出的旧训练结果。
+ if (model.GetProperty("recipeName").GetString() != recipeName)
+ throw new InvalidDataException("模型与当前配方不匹配");
+ var modelPath = onnx.GetString();
+ if (string.IsNullOrWhiteSpace(modelPath) || !Path.IsPathRooted(modelPath) || !File.Exists(modelPath))
+ throw new FileNotFoundException("配方 ONNX 文件不存在", modelPath);
+ var classes = model.GetProperty("classes").Deserialize>() ?? [];
+ var size = model.GetProperty("imageSize").GetInt32();
+ if (classes.Count == 0 || size < 32 || size > 2048 || size % 32 != 0)
+ throw new InvalidDataException("配方模型类别或输入尺寸无效");
+ config.Sop.Model = new ModelDef { Path = modelPath, Classes = classes, InputSize = size };
+ Log("info", $"已加载配方训练模型:{modelPath}");
+ }
+ catch (Exception error) when (error is IOException or InvalidDataException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException)
+ {
+ Log("warn", "读取配方训练模型失败,使用配方配置:" + error.Message);
+ }
+ }
+
///
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
///
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index b83dfeb..9a2cce0 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -118,6 +118,32 @@ internal static class Smoke
var restoredTrainer=new SopHelper.Training.MainViewModel(new WorkerClient());
Check(restoredTrainer.ExtractStride==3&&restoredTrainer.MaxFrames==420&&restoredTrainer.ExportEvery==2&&restoredTrainer.ImageSize==960&&restoredTrainer.Epochs==12&&restoredTrainer.Batch==2,"Explicit save restores annotation and training parameters in a new view model");
Check(trainer.Status=="参数已保存,下次打开时自动恢复"&&!trainer.IsBusy,"Saving confirms success without starting a worker task");
+ var recipeId="onnx-smoke-"+Guid.NewGuid().ToString("N");
+ var recipeFile=Path.Combine(AppContext.BaseDirectory,"configs","sop",recipeId+".yaml");
+ var recipeWorkspace=Path.Combine(trainer.Root,"workspace","training",recipeId);
+ Directory.CreateDirectory(recipeWorkspace);
+ var modelFile=Path.Combine(recipeWorkspace,recipeId+".onnx");
+ var manifestFile=Path.Combine(recipeWorkspace,"latest-model.json");
+ try
+ {
+ File.Copy(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"),recipeFile);
+ // The model loader may reject this stub; this checks recipe routing and metadata independently.
+ File.WriteAllBytes(modelFile,[]);
+ File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
+ sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
+ var engine=app.Container.Resolve();
+ Check(engine.Config.Sop.Model is {InputSize:960} trained&&trained.Path==modelFile&&trained.Classes.SequenceEqual(new[]{"测试零件"}),"Applying a recipe selects its trained ONNX, class order and input size");
+ sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
+ Check(engine.Config.Sop.Model?.Path!=modelFile,"Switching recipes does not reuse the previous recipe's ONNX");
+ File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName="another-recipe",onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
+ sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
+ Check(engine.Config.Sop.Model is null,"Mismatched recipe metadata cannot replace the configured model");
+ }
+ finally
+ {
+ sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
+ File.Delete(recipeFile);File.Delete(modelFile);File.Delete(manifestFile);Directory.Delete(recipeWorkspace);
+ }
var trainingTabs=trainingView.GetVisualDescendants().OfType().Single();
trainingTabs.SelectedIndex=1;await Task.Delay(80);
Check(trainingView.GetVisualDescendants().OfType