按配方累计零件数据并自动更新命名模型

This commit is contained in:
tfarcraw 2026-11-09 10:45:41 +08:00
parent 29a00fc349
commit c7aab2f96e
8 changed files with 223 additions and 48 deletions

View File

@ -45,6 +45,11 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
2. 配方编辑器保留步骤、区域、全局设置、检测模型四个标签页;区域坐标使用原图像素。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
- 在标注页选择所属配方,每个视频录入一个零件;导入数据自动保存在 `workspace/training/配方名/parts`。
- 点击“训练并更新配方模型”,自动累计导出该配方所有已加入视频的复核数据,并使用上一版配方模型开始新训练;首次使用 `yolo11n.pt`。无需手选权重。
- 同名零件的多个视频共用类别,新增零件自动分配类别编号。每个视频均需完成足够的训练段和末尾验证段复核。
- 模型保存为各次训练结果目录内的 `配方名.pt`,配方目录的 `latest-model.json` 指向最新成功版本;旧版本保留。ONNX 导出使用此最新配方模型,配方编辑器仍需选择导出的 ONNX 用于检测。
- 旧版独立标注项目打开后,选择所属配方并执行导出或训练即可加入;原视频帧目录需保留。
4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。
模型文件:`palm_detection_full_Nx3x192x192_post.onnx`、`hand_landmark_sparse_Nx3x224x224.onnx`;

View File

@ -71,6 +71,15 @@ public sealed class MainViewModel : BindableBase
}
// Configuration is saved locally, except the API key which is passed only through the worker environment.
private static string PythonPath => DesktopPlatform.PythonPath;
public ObservableCollection<string> Recipes { get; } = [];
private string _recipeName = "";
public string RecipeName { get => _recipeName; set => SetProperty(ref _recipeName, value); }
private string RecipeDirectoryFor(string name)
{
if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name is "." or "..")
throw new ArgumentException("请先选择有效的配方");
return Path.Combine(Root, "workspace", "training", name);
}
public string Label { get; set; } = "零件";
public int ExtractStride { get; set; } = 1;
public int MaxFrames { get; set; } = 600;
@ -140,7 +149,7 @@ public sealed class MainViewModel : BindableBase
if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
DesktopPlatform.Reveal(directory);
});
OnnxCommand = Command(async () => await Run(Request("onnx")));
OnnxCommand = Command(async () => { SaveLabel(); await Run(Request("onnx")); });
SuggestCommand = Command(async () =>
{
SaveLabel();
@ -173,13 +182,19 @@ public sealed class MainViewModel : BindableBase
}
// Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting.
private object Request(string action) => new { action, project = RequireProject().FilePath, every = ExportEvery,
valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = Model, device = Device,
valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = "yolo11n.pt", device = Device,
outputDirectory = TrainingOutputDirectory };
private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
private void SaveLabel()
{
var project = RequireProject();
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
if (string.IsNullOrWhiteSpace(project.RecipeDirectory))
{
project.RecipeDirectory = RecipeDirectoryFor(RecipeName);
project.RecipeName = RecipeName;
}
if (project.RecipeName != RecipeName) throw new InvalidOperationException("当前视频属于配方“" + project.RecipeName + "”,请切回该配方;新配方请导入新视频");
project.Name = Label.Trim(); project.Save();
}
private async void Import()
@ -190,11 +205,10 @@ public sealed class MainViewModel : BindableBase
try { video.InitialDirectory = VideoImportDirectory ?? CameraViewModel.ReadSaveDirectory(Root); }
catch (Exception e) { Append("录像目录配置读取失败:" + e.Message); }
if (await video.ShowDialogAsync() != true) return;
var folder = new OpenFolderDialog { Title = "选择项目保存的父文件夹(会自动新建子文件夹)" };
if (await folder.ShowDialogAsync() != true) return;
var recipeDirectory = RecipeDirectoryFor(RecipeName);
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
var output = Path.Combine(folder.FolderName, "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
var output = Path.Combine(recipeDirectory, "parts", "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), recipeName = RecipeName, recipeDirectory, stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
Load(Path.Combine(output, "project.json"));
}
catch (Exception e) { Status = e.Message; Append(e.Message); }
@ -202,6 +216,11 @@ public sealed class MainViewModel : BindableBase
public void Load(string path, int index = 0)
{
_project = TrainingProject.Load(path);
if (!string.IsNullOrWhiteSpace(_project.RecipeName))
{
if (!Recipes.Contains(_project.RecipeName)) Recipes.Add(_project.RecipeName);
RecipeName = _project.RecipeName;
}
Label = _project.Name; RaisePropertyChanged(nameof(Label));
_selected = null; Frames.Clear();
foreach (var frame in _project.Frames) Frames.Add(frame);
@ -334,7 +353,7 @@ public sealed class MainViewModel : BindableBase
{
if (IsTraining) return;
LatestWeights = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(RequireProject().DirectoryPath, "latest-model.json");
var file = Path.Combine(string.IsNullOrWhiteSpace(RequireProject().RecipeDirectory) ? RequireProject().DirectoryPath : RequireProject().RecipeDirectory, "latest-model.json");
if (!File.Exists(file)) return;
try
{

View File

@ -71,6 +71,9 @@
<TabItem Header="标注">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<TextBlock Text="所属配方" />
<ComboBox ItemsSource="{Binding Recipes}" SelectedItem="{Binding RecipeName, Mode=TwoWay}" HorizontalAlignment="Stretch" />
<TextBlock Text="每个视频录入一个零件;新零件会加入当前配方。配方可在运行设置中创建。" Classes="Hint" />
<TextBlock Text="01 导入旋转视频" FontWeight="Bold" Foreground="{StaticResource Accent}" />
<TextBlock Text="零件类别名称" Margin="0,12,0,0" />
<TextBox Text="{Binding Label, Mode=TwoWay}" />
@ -94,8 +97,9 @@
<TextBlock Text="按时间分段:前段训练、末尾20%验证,边界留出间隔。正式评估请另拍独立测试视频。" Classes="Hint" />
<TextBlock Text="训练抽样间隔(导入后的帧数)" />
<TextBox Text="{Binding ExportEvery, Mode=TwoWay}" />
<TextBlock Text="YOLO 初始模型 / 本地 .pt 路径" />
<TextBox Text="{Binding Model, Mode=TwoWay}" />
<TextBlock Text="配方模型(自动管理)" />
<TextBlock Text="{Binding RecipeName}" FontWeight="Bold" />
<TextBlock Text="首次自动使用预训练模型,之后自动加载上一版配方模型。" Classes="Hint" />
<TextBlock Text="训练轮数" />
<TextBox Text="{Binding Epochs, Mode=TwoWay}" />
<TextBlock Text="图像尺寸(32的倍数)" />
@ -103,9 +107,11 @@
<TextBlock Text="批次大小" />
<TextBox Text="{Binding Batch, Mode=TwoWay}" />
<Button Content="导出 YOLO 数据集" Command="{Binding ExportCommand}" />
<Button Content="开始训练" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}" />
<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="每次训练重新导出当前复核数据。best.pt、ONNX 和训练指标保存在项目 runs 文件夹。默认 yolo11n,检测框格式便于接入 SopHelper,仍需现场验证。" Classes="Hint" />
<TextBlock Text="每次训练累计使用本配方已加入的零件视频复核数据。模型按配方名命名,每次训练保留独立版本;训练成功后更新最新模型。" Classes="Hint" />
</StackPanel>
</ScrollViewer>
</TabItem>

View File

@ -23,6 +23,12 @@ public partial class TrainingPage : UserControl
model.ReadApiKey=()=>ApiKey.Text??"";
AttachedToVisualTree+=(_,_)=>
{
if (!model.IsBusy && sop != null)
{
foreach (var recipe in sop.Recipes.Select(System.IO.Path.GetFileNameWithoutExtension).OfType<string>())
if (!model.Recipes.Contains(recipe)) model.Recipes.Add(recipe);
if (string.IsNullOrWhiteSpace(model.RecipeName)) model.RecipeName = System.IO.Path.GetFileNameWithoutExtension(sop.SelectedRecipe) ?? "";
}
if(_host!=null || TopLevel.GetTopLevel(this) is not Window host)return;
_host=host;host.Closing+=HostClosing;
};

View File

@ -17,6 +17,8 @@ public sealed class FrameAnnotation
public sealed class TrainingProject
{
public string Name { get; set; } = "零件";
public string RecipeName { get; set; } = "";
public string RecipeDirectory { get; set; } = "";
public string Video { get; set; } = "";
public int Width { get; set; }
public int Height { get; set; }

View File

@ -109,6 +109,13 @@ internal static class Smoke
navigation.SelectedIndex=1;await Task.Delay(150);Save(window,"training");
Check(window.GetVisualDescendants().OfType<TrainingPage>().Any(),"Training page navigates");
var trainer=app.Container.Resolve<SopHelper.Training.MainViewModel>();
Check(trainer.Recipes.Contains(Path.GetFileNameWithoutExtension(sop.SelectedRecipe)!) && trainer.RecipeName==Path.GetFileNameWithoutExtension(sop.SelectedRecipe),"Training offers the current SOP recipe automatically");
var trainingView=window.GetVisualDescendants().OfType<TrainingPage>().Single();
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");
Save(window,"training-recipe-model");
trainingTabs.SelectedIndex=0;
var temporary=Path.Combine(Path.GetTempPath(),"sophelper-avalonia-project-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(temporary);
using(var trainingFrame=new Mat(480,640,MatType.CV_8UC3,new Scalar(30,60,90)))Cv2.ImWrite(Path.Combine(temporary,"frame.png"),trainingFrame);
var project=new TrainingProject { FilePath=Path.Combine(temporary,"project.json"),Name="测试零件",Width=640,Height=480,

View File

@ -0,0 +1,82 @@
"""Recipe training regression: real dataset export, simulated training lifecycle."""
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("worker", Path(__file__).parents[2] / "tools" / "worker.py")
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
class RecipeTrainingTests(unittest.TestCase):
def test_incremental_recipe(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary) / "装配配方"
def part(name, folder):
directory = root / "parts" / folder
directory.mkdir(parents=True)
(directory / "frame.jpg").write_bytes(b"test-image")
path = directory / "project.json"
worker.save_json(path, {"name": name, "recipeName": root.name, "recipeDirectory": str(root),
"width": 100, "height": 100, "frames": [
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
for i in range(30)]})
worker.recipe_context({"project": str(path)})
return path
first = part("零件1", "first")
loaded = []
options = []
class FakeYolo:
task = "detect"
fail = False
def __init__(self, weights):
loaded.append(str(weights))
def add_callback(self, *args):
pass
def train(self, **kwargs):
options.append(kwargs)
if self.fail:
raise RuntimeError("simulated failure")
directory = Path(kwargs["project"]) / kwargs["name"]
directory.mkdir(parents=True)
best = directory / "best.pt"
best.write_bytes(b"checkpoint")
self.trainer = SimpleNamespace(best=best, save_dir=directory, metrics={"mAP": 0.9})
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")
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.assertFalse(options[-1]["resume"])
self.assertEqual(latest["classes"], ["零件1", "零件2"])
dataset = Path(latest["dataset"]).parent
self.assertEqual(len(list((dataset / "images" / "train").glob("*.jpg"))), 46)
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"0", "1"})
self.assertTrue(Path(previous["weights"]).is_file())
# 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"])
FakeYolo.fail = True
with self.assertRaisesRegex(RuntimeError, "simulated failure"):
worker.train(request)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
# Missing old data must stop the update, never silently drop an old part.
first.unlink()
with self.assertRaises(FileNotFoundError):
worker.export_dataset(request)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
if __name__ == "__main__":
unittest.main()

View File

@ -109,7 +109,8 @@ def extract(request):
# Bound RAM/disk use and preserve coverage across the entire source video.
stride = max(stride, math.ceil(total / limit)) if total > 0 else stride
data = {"name": request.get("name", "零件"), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
"width": 0, "height": 0, "stride": stride, "frames": []}
"width": 0, "height": 0, "stride": stride, "frames": [],
"recipeName": request.get("recipeName", ""), "recipeDirectory": request.get("recipeDirectory", "")}
index = 0
while True:
ok, image = cap.read()
@ -136,6 +137,8 @@ def extract(request):
raise ValueError("视频有效帧不足两帧")
save_json(staging / "project.json", data)
staging.rename(target)
if data.get("recipeDirectory"):
recipe_context({"project": str(target / "project.json")})
emit(f"导入完成:{len(data['frames'])} 帧,原视频每 {stride} 帧采样一次", progress=1)
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
@ -224,41 +227,77 @@ def default_checkpoint():
return target
def export_dataset(request):
def recipe_context(request):
path, data = load_project(request["project"])
directory = data.get("recipeDirectory", "")
if not directory:
return path.parent, [(path, data)], [data["name"]]
root = Path(directory).resolve()
root.mkdir(parents=True, exist_ok=True)
registry = root / "recipe-training.json"
state = read_json(registry) if registry.exists() else {"projects": [], "classes": []}
current = str(path)
if current not in state["projects"]:
state["projects"].append(current)
projects = [load_project(item) for item in state["projects"]]
labels = state.setdefault("labels", {})
for source, project in projects:
previous = labels.get(str(source))
# A corrected name keeps its class ID when it is the sole video for that part.
if previous and previous != project["name"] and previous in state["classes"] and project["name"] not in state["classes"]:
others = [p["name"] for other, p in projects if other != source]
if previous not in others:
state["classes"][state["classes"].index(previous)] = project["name"]
labels[str(source)] = project["name"]
if Path(project.get("recipeDirectory", "")).resolve() != root:
raise ValueError(f"零件项目的配方归属不一致:{source}")
if project["name"] not in state["classes"]:
state["classes"].append(project["name"])
save_json(registry, state)
return root, projects, state["classes"]
def export_dataset(request):
root, projects, classes = recipe_context(request)
every = int(request.get("every", 5))
ratio = float(request.get("valRatio", 0.2))
if every < 1 or not 0 < ratio < 0.5:
raise ValueError("训练抽样间隔需 ≥1,验证比例需在 0–0.5 之间")
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
if any(f["status"] == "reviewed" and not f.get("box") for f in selected):
raise ValueError("已复核的正样本缺少标注框")
# Hold out one contiguous time segment, with a gap around the boundary.
boundary = int(len(data["frames"]) * (1 - ratio))
training = [f for f in selected if f["index"] < boundary - every and f["index"] % every == 0]
validation = [f for f in selected if f["index"] >= boundary and f["index"] % every == 0]
if len(training) < 2 or not validation or not any(f.get("box") for f in training) or not any(f.get("box") for f in validation):
raise ValueError("复核样本不足:训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。可减小训练抽样间隔")
output = path.parent / "datasets" / ("dataset-" + uuid.uuid4().hex[:10])
samples = []
for path, data in projects:
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
if any(f["status"] == "reviewed" and not f.get("box") for f in selected):
raise ValueError(f"{data['name']}:已复核的正样本缺少标注框")
boundary = int(len(data["frames"]) * (1 - ratio))
training = [f for f in selected if f["index"] < boundary - every and f["index"] % every == 0]
validation = [f for f in selected if f["index"] >= boundary and f["index"] % every == 0]
if len(training) < 2 or not validation or not any(f.get("box") for f in training) or not any(f.get("box") for f in validation):
raise ValueError(f"{data['name']}:复核样本不足,训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。请补充复核或减小训练抽样间隔")
samples.append((path, data, training, validation))
output = root / "datasets" / ("dataset-" + uuid.uuid4().hex[:10])
output.mkdir(parents=True)
for split, frames in (("train", training), ("val", validation)):
(output / "images" / split).mkdir(parents=True)
(output / "labels" / split).mkdir(parents=True)
for frame in frames:
stem = f"{frame['index']:06d}"
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
label = ""
if frame.get("box") is not None and frame["status"] != "absent":
x1, y1, x2, y2 = validate_box(frame["box"], data["width"], data["height"])
label = "0 " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
(x2-x1)/data["width"], (y2-y1)/data["height"])) + "\n"
(output / "labels" / split / (stem + ".txt")).write_text(label, encoding="utf-8")
# JSON-quoted scalars are valid YAML and safely handle user-entered class names and Windows paths.
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n 0: {json.dumps(data['name'], ensure_ascii=False)}\n"
manifest = []
for number, (path, data, training, validation) in enumerate(samples):
class_id = classes.index(data["name"])
for split, frames in (("train", training), ("val", validation)):
(output / "images" / split).mkdir(parents=True, exist_ok=True)
(output / "labels" / split).mkdir(parents=True, exist_ok=True)
for frame in frames:
stem = f"{number:04d}_{frame['index']:06d}"
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
label = ""
if frame.get("box") is not None and frame["status"] != "absent":
x1, y1, x2, y2 = validate_box(frame["box"], data["width"], data["height"])
label = str(class_id) + " " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
(x2-x1)/data["width"], (y2-y1)/data["height"])) + "\n"
(output / "labels" / split / (stem + ".txt")).write_text(label, encoding="utf-8")
manifest.append({"project": str(path), "classId": class_id, "train": [f["index"] for f in training], "val": [f["index"] for f in validation]})
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n"
yaml += "".join(f" {i}: {json.dumps(name, ensure_ascii=False)}\n" for i, name in enumerate(classes))
(output / "data.yaml").write_text(yaml, encoding="utf-8")
save_json(output / "manifest.json", {"project": str(path), "train": [f["index"] for f in training], "val": [f["index"] for f in validation], "gap": every})
save_json(path.parent / "latest-dataset.json", {"yaml": str(output / "data.yaml")})
emit(f"导出完成 · 训练 {len(training)} / 验证 {len(validation)}", output=str(output), progress=1)
save_json(output / "manifest.json", {"projects": manifest, "classes": classes, "gap": every})
save_json(root / "latest-dataset.json", {"yaml": str(output / "data.yaml")})
emit(f"配方数据导出完成 · {len(classes)} 类零件 / {len(projects)} 个视频", output=str(output), progress=1)
return output / "data.yaml"
@ -272,7 +311,11 @@ def train(request):
if not 1 <= epochs <= 10000 or not 32 <= size <= 2048 or size % 32 or batch < 1:
raise ValueError("训练参数无效:尺寸需为32的倍数,轮数与批次需为正数")
yaml = export_dataset(request) # Fresh export prevents training with stale review changes.
model = YOLO(request.get("model", "yolo11n.pt"))
root, _, classes = recipe_context(request)
latest = root / "latest-model.json"
initial = read_json(latest)["weights"] if latest.exists() else request.get("model", "yolo11n.pt")
emit(f"自动加载初始模型:{initial}")
model = YOLO(initial)
if model.task != "detect":
raise ValueError("当前项目导出矩形检测框,请选择 YOLO detect 模型(非 seg / pose / classify)")
reported_epoch = 0
@ -309,25 +352,30 @@ def train(request):
if device == "cuda":
device = "0"
output_directory = str(request.get("outputDirectory", "")).strip()
output_directory = Path(output_directory).resolve() if output_directory else path.parent / "runs"
output_directory = Path(output_directory).resolve() if output_directory else root / "runs"
output_directory.mkdir(parents=True, exist_ok=True)
model.train(data=str(yaml), epochs=epochs, imgsz=size, batch=batch, device=device,
workers=0, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
workers=0, resume=False, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
best = Path(model.trainer.best)
if not best.is_file():
raise RuntimeError("训练未生成 best.pt")
summary = {"weights": str(best), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir),
# Publish a versioned recipe-named checkpoint before atomically switching the latest pointer.
recipe_name = data.get("recipeName") or data["name"]
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)
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)}
save_json(Path(model.trainer.save_dir) / "training-result.json", summary)
save_json(path.parent / "latest-model.json", summary)
emit("训练完成", event="training_completed", **summary, output=str(best), progress=1)
save_json(root / "latest-model.json", summary)
emit("训练完成", event="training_completed", **summary, output=str(published), progress=1)
def export_onnx(request):
from ultralytics import YOLO
path, _ = load_project(request["project"])
weights = read_json(path.parent / "latest-model.json")["weights"]
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)