训练后自动导出并按配方加载ONNX模型

This commit is contained in:
tfarcraw 2026-11-09 11:48:54 +08:00
parent ef41b97037
commit 60b093a13f
8 changed files with 144 additions and 20 deletions

View File

@ -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
{

View File

@ -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);
}

View File

@ -111,8 +111,9 @@
<Button Content="训练并更新配方模型" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}" />
<Button Content="打开最新训练结果" Command="{Binding OpenTrainingResultsCommand}" />
<TextBlock Text="{Binding LatestWeights}" Classes="Hint" />
<Button Content="导出最新模型为 ONNX" Command="{Binding OnnxCommand}" />
<TextBlock Text="每次训练累计使用本配方已加入的零件视频复核数据。模型按配方名命名,每次训练保留独立版本;训练成功后更新最新模型。" Classes="Hint" />
<Button Content="重新导出配方 ONNX" Command="{Binding OnnxCommand}" />
<TextBlock Text="{Binding LatestOnnx}" TextWrapping="Wrap" />
<TextBlock Text="每次训练累计使用本配方已加入的零件视频复核数据,自动导出配方同名 ONNX 并保留独立版本。导出成功后更新最新模型;运行前重新应用配方即可加载。" Classes="Hint" />
</StackPanel>
</ScrollViewer>
</TabItem>

View File

@ -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<List<string>>() ?? [];
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);
}
}
/// <summary>
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
/// </summary>

View File

@ -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<SopHelper.Engine.Sop.SopEngine>();
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<TabControl>().Single();
trainingTabs.SelectedIndex=1;await Task.Delay(80);
Check(trainingView.GetVisualDescendants().OfType<Button>().Any(b=>b.Content?.ToString()=="训练并更新配方模型"),"Recipe model update action is visible on the training tab");

View File

@ -31,11 +31,14 @@ class RecipeTrainingTests(unittest.TestCase):
first = part("零件1", "first")
loaded = []
options = []
exports = []
class FakeYolo:
task = "detect"
fail = False
fail_export = False
def __init__(self, weights):
loaded.append(str(weights))
self.weights = Path(weights)
def add_callback(self, *args):
pass
def train(self, **kwargs):
@ -47,17 +50,31 @@ class RecipeTrainingTests(unittest.TestCase):
best = directory / "best.pt"
best.write_bytes(b"checkpoint")
self.trainer = SimpleNamespace(best=best, save_dir=directory, metrics={"mAP": 0.9})
def export(self, **kwargs):
exports.append(kwargs)
if self.fail_export:
raise RuntimeError("simulated export failure")
output = self.weights.with_suffix(".onnx")
output.write_bytes(b"onnx-model")
return str(output)
request = {"project": str(first), "every": 1, "epochs": 1, "imageSize": 32}
with patch.dict(sys.modules, {"ultralytics": SimpleNamespace(YOLO=FakeYolo),
"torch": SimpleNamespace(cuda=SimpleNamespace(is_available=lambda: False))}):
worker.train(request)
previous = worker.read_json(root / "latest-model.json")
self.assertEqual(Path(previous["weights"]).name, "装配配方.pt")
self.assertEqual(Path(previous["onnx"]).name, "装配配方.onnx")
self.assertTrue(Path(previous["onnx"]).is_file())
second = part("零件2", "second")
request["project"] = str(second)
worker.train(request)
latest = worker.read_json(root / "latest-model.json")
self.assertEqual(loaded, ["yolo11n.pt", previous["weights"]])
self.assertEqual(loaded, ["yolo11n.pt", previous["weights"], previous["weights"], latest["weights"]])
self.assertEqual(exports[-1], {"format": "onnx", "imgsz": 32, "opset": 17,
"dynamic": False, "simplify": False, "nms": False})
self.assertNotEqual(previous["onnx"], latest["onnx"])
self.assertTrue(Path(previous["onnx"]).is_file())
self.assertEqual(worker.read_json(Path(latest["runDirectory"]) / "training-result.json"), latest)
self.assertFalse(options[-1]["resume"])
self.assertEqual(latest["classes"], ["零件1", "零件2"])
dataset = Path(latest["dataset"]).parent
@ -67,6 +84,27 @@ class RecipeTrainingTests(unittest.TestCase):
# Reopening an older video retains all classes and their identifiers.
worker.export_dataset({**request, "project": str(first)})
self.assertEqual(worker.read_json(root / "recipe-training.json")["classes"], ["零件1", "零件2"])
worker.export_onnx({**request, "imageSize": 640})
self.assertEqual(exports[-1]["imgsz"], 32)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
# A different recipe publishes into its own directory and starts independently.
other = Path(temporary) / "另一配方"
other.mkdir()
(other / "frame.jpg").write_bytes(b"test-image")
other_project = other / "project.json"
worker.save_json(other_project, {**worker.read_json(second), "recipeName": other.name,
"recipeDirectory": str(other)})
worker.train({**request, "project": str(other_project)})
other_latest = worker.read_json(other / "latest-model.json")
self.assertEqual(loaded[-2], "yolo11n.pt")
self.assertEqual(Path(other_latest["onnx"]).name, "另一配方.onnx")
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
FakeYolo.fail_export = True
with self.assertRaisesRegex(RuntimeError, "ONNX 导出失败"):
worker.train(request)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
self.assertTrue(Path(latest["onnx"]).is_file())
FakeYolo.fail_export = False
FakeYolo.fail = True
with self.assertRaisesRegex(RuntimeError, "simulated failure"):
worker.train(request)

View File

@ -36,11 +36,12 @@ class DatasetTests(unittest.TestCase):
self.save()
yaml = worker.export_dataset({"project": str(self.project), "every": 5})
manifest = worker.read_json(yaml.parent / "manifest.json")
self.assertNotIn(0, manifest["train"])
self.assertNotIn(5, manifest["train"])
self.assertGreater(min(manifest["val"]) - max(manifest["train"]), 5)
self.assertEqual((yaml.parent / "labels/train/000010.txt").read_text(), "")
values = (yaml.parent / "labels/train/000015.txt").read_text().split()
samples = manifest["projects"][0]
self.assertNotIn(0, samples["train"])
self.assertNotIn(5, samples["train"])
self.assertGreater(min(samples["val"]) - max(samples["train"]), 5)
self.assertEqual((yaml.parent / "labels/train/0000_000010.txt").read_text(), "")
values = (yaml.parent / "labels/train/0000_000015.txt").read_text().split()
self.assertEqual(values[0], "0")
self.assertEqual([float(v) for v in values[1:]], [0.3, 0.5, 0.4, 0.5])
import yaml as pyyaml

View File

@ -364,21 +364,38 @@ def train(request):
safe_name = "".join("_" if c in '<>:"/\\|?*' or ord(c) < 32 else c for c in recipe_name).strip(" .") or "recipe"
published = Path(model.trainer.save_dir) / (safe_name + ".pt")
shutil.copy2(best, published)
emit("训练已结束,正在导出配方 ONNX…", event="onnx_export_started", weights=str(published),
runDirectory=str(model.trainer.save_dir))
try:
onnx = export_checkpoint_onnx(published, size)
except Exception as error:
raise RuntimeError(f"训练权重已保存到 {published};ONNX 导出失败,配方继续保留上一版模型:{error}") from error
summary = {"recipeName": recipe_name, "classes": classes, "weights": str(published), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir),
"metrics": finite_metrics(model.trainer.metrics or {}), "epochs": reported_epoch,
"imageSize": size, "device": str(device)}
"imageSize": size, "device": str(device), "onnx": str(onnx)}
save_json(Path(model.trainer.save_dir) / "training-result.json", summary)
save_json(root / "latest-model.json", summary)
emit("训练完成", event="training_completed", **summary, output=str(published), progress=1)
emit("训练完成,配方 ONNX 已自动导出", event="training_completed", **summary, output=str(onnx), progress=1)
def export_checkpoint_onnx(weights, size):
from ultralytics import YOLO
output = Path(YOLO(str(weights)).export(format="onnx", imgsz=size,
opset=17, dynamic=False, simplify=False, nms=False))
if not output.is_file():
raise RuntimeError("未生成 ONNX 文件")
return output.resolve()
def export_onnx(request):
from ultralytics import YOLO
root, _, _ = recipe_context(request)
weights = read_json(root / "latest-model.json")["weights"]
output = YOLO(weights).export(format="onnx", imgsz=int(request.get("imageSize", 640)),
opset=17, dynamic=False, simplify=False, nms=False)
emit("ONNX 导出完成(检测框输出,不含 NMS)", output=str(output), progress=1)
summary = read_json(root / "latest-model.json")
# A manual re-export must retain the trained recipe's input size.
output = export_checkpoint_onnx(summary["weights"], int(summary.get("imageSize", request.get("imageSize", 640))))
summary["onnx"] = str(output)
save_json(Path(summary["runDirectory"]) / "training-result.json", summary)
save_json(root / "latest-model.json", summary)
emit("配方 ONNX 导出完成(检测框输出,不含 NMS)", onnx=str(output), output=str(output), progress=1)
def suggest(request):