统一配方目录并迁移设置录像标注与模型

This commit is contained in:
tfarcraw 2026-11-09 14:33:06 +08:00
parent e05fd2c483
commit dab92c08e0
16 changed files with 458 additions and 56 deletions

1
.gitignore vendored
View File

@ -398,6 +398,7 @@ FodyWeavers.xsd
/.venv/
/.cache/
/workspace/
/recipes/
*.pt
/python/

View File

@ -12,13 +12,14 @@ SopHelper.Avalonia.slnx
src/
SopHelper.Avalonia/ 统一桌面界面、ViewModel、平台适配
SopHelper.CrossPlatform.Engine/ 独立共享引擎:相机、推理、SOP、录像、训练数据
configs/sop/ YAML 配方
models/、yolo_models/ 模型
configs/sop/ 随程序提供的初始配方模板
recipes/配方名/ 配方设置、录像、标注数据、训练参数和模型(不入 Git)
models/、yolo_models/ 共用推理资源及初始模型
libs/ Windows/Linux 海康绑定及可选 CUDA 库
tools/ worker、运行环境、发布和部署脚本
tests/ Avalonia、引擎和硬件回归检查
python/ 本地 Python 运行环境(不入 Git)
workspace/ 设置、录像和工作数据(不入 Git)
workspace/ 旧版工作数据,迁移后保留作为回退副本(不入 Git)
artifacts/ 构建和测试输出(不入 Git)
```
@ -45,16 +46,24 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
2. 配方编辑器保留步骤、区域、全局设置、检测模型四个标签页;区域坐标使用原图像素。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
- 在标注页选择所属配方,每个视频录入一个零件;导入数据自动保存在 `workspace/training/配方名/parts`。
- 在标注页选择所属配方,每个视频录入一个零件;录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。
- 点击“训练并更新配方模型”,自动累计导出该配方所有已加入视频的复核数据,并使用上一版配方模型开始新训练;首次使用 `yolo11n.pt`。无需手选权重。
- 同名零件的多个视频共用类别,新增零件自动分配类别编号。每个视频均需完成足够的训练段和末尾验证段复核。
- 模型保存为各次训练结果目录内的 `配方名.pt`,配方目录的 `latest-model.json` 指向最新成功版本;旧版本保留。ONNX 导出使用此最新配方模型,配方编辑器仍需选择导出的 ONNX 用于检测。
- 旧版独立标注项目打开后,选择所属配方并执行导出或训练即可加入;原视频帧目录需保留。
- 训练成功后自动将 `配方名.pt` 和 `配方名.onnx` 发布到同配方的 `models/训练版本/`;训练曲线和日志保存在 `runs`,数据集保存在 `datasets`。`latest-model.json` 指向最新完整版本,重新应用配方即可加载。
- “保存参数”写入所选配方的 `training-settings.json`,切换配方时恢复各自参数。打开外部标注项目会将其复制到所属配方目录。
4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。
模型文件:`palm_detection_full_Nx3x192x192_post.onnx`、`hand_landmark_sparse_Nx3x224x224.onnx`;
目标检测模型由配方选择。测试用 `yolo11n.onnx` 和训练依赖沿用其上游许可。
## 配方存储与迁移
实际配方统一保存在 `recipes/<配方名>/<配方名>.yaml`。新建配方自动创建同名目录;编辑器选择的外部 ONNX 会复制到该配方的 `models`,运行快照保存在 `snaps`。
首次启动会从旧 `configs/sop` 和 `workspace/training` 复制配方及关联数据,并修正标注项目、视频、模型和类别注册表的路径。已有的新目录不被旧数据覆盖;原文件保留作回退副本。无法确认归属的公共录像留在原位置。也可运行 `SopHelper.Avalonia --migrate-recipes` 单独完成迁移。
源码运行时 `recipes` 位于仓库根目录,发布程序默认位于程序目录。可通过 `SOPHELPER_WORKSPACE_ROOT` 指定统一数据根目录;升级或搬迁程序时应保留整个 `recipes` 目录。手部模型、SAM2 等共用运行资源仍在程序资源目录。
## 验证
```powershell

View File

@ -7,7 +7,23 @@ namespace SopHelper.Presentation;
internal static class DesktopPlatform
{
private static readonly Lazy<SopHelper.Engine.Training.RecipeWorkspace> RecipeStorage = new(() =>
{
var storage = new SopHelper.Engine.Training.RecipeWorkspace(WorkspaceRoot);
storage.Initialize(Path.Combine(AppContext.BaseDirectory, "configs", "sop"), Path.Combine(WorkspaceRoot, "configs", "sop"));
return storage;
});
public static SopHelper.Engine.Training.RecipeWorkspace Recipes => RecipeStorage.Value;
public static string WorkspaceRoot
{
get
{
var configured = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
if (!string.IsNullOrWhiteSpace(configured)) return Path.GetFullPath(configured);
return ApplicationRoot;
}
}
public static string ApplicationRoot
{
get
{

View File

@ -6,6 +6,16 @@ internal static class Program
[STAThread]
public static int Main(string[] args)
{
if (args.Contains("--migrate-recipes"))
{
try
{
var storage = Presentation.DesktopPlatform.Recipes;
Console.WriteLine($"配方目录已就绪:{storage.RecipesDirectory}({storage.Names().Count()} 个配方)");
return 0;
}
catch (Exception error) { Console.Error.WriteLine("配方迁移失败:" + error.Message); return 1; }
}
if(args.Contains("--check-training"))return Diagnostics.TrainingRuntimeCheck.Run();
if(args.Contains("--check-gpu"))return Diagnostics.RuntimeCheck.Run(requireGpu:true);
if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run();

View File

@ -22,6 +22,7 @@ public sealed class CameraViewModel : BindableBase
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _timer;
private readonly string _settingsPath;
private readonly string? _recipeRecordingDirectory;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
@ -47,11 +48,11 @@ public sealed class CameraViewModel : BindableBase
public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } }
public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing;
public bool CanChangeDirectory => _recipeRecordingDirectory is null && !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); }
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, _recipeRecordingDirectory ?? value); }
public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
public double RecordingFps { get; set; } = 30;
public DelegateCommand RefreshCommand { get; }
@ -60,14 +61,16 @@ public sealed class CameraViewModel : BindableBase
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public CameraViewModel(ICameraService camera, string root)
public CameraViewModel(ICameraService camera, string root, string? recipeName = null)
{
_camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
_directory = Path.Combine(root, "workspace", "recordings");
_settingsPath = Path.Combine(root, "workspace", "camera-settings.json");
var recipeDirectory = string.IsNullOrWhiteSpace(recipeName) ? null : new SopHelper.Engine.Training.RecipeWorkspace(root).DirectoryFor(recipeName);
_recipeRecordingDirectory = recipeDirectory is null ? null : Path.Combine(recipeDirectory, "recordings");
_directory = _recipeRecordingDirectory ?? Path.Combine(root, "workspace", "recordings");
_settingsPath = recipeDirectory is null ? Path.Combine(root, "workspace", "camera-settings.json") : Path.Combine(recipeDirectory, "camera-settings.json");
try
{
SaveDirectory = ReadSaveDirectory(root);
SaveDirectory = _recipeRecordingDirectory ?? ReadSaveDirectory(root);
}
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);

View File

@ -36,7 +36,6 @@ public sealed class MainViewModel : BindableBase
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; }
public string Root { get; }
public TrainingProject? Project => _project;
@ -75,12 +74,29 @@ public sealed class MainViewModel : BindableBase
private static string PythonPath => DesktopPlatform.PythonPath;
public ObservableCollection<string> Recipes { get; } = [];
private string _recipeName = "";
public string RecipeName { get => _recipeName; set => SetProperty(ref _recipeName, value); }
public string RecipeName
{
get => _recipeName;
set
{
if (!SetProperty(ref _recipeName, value)) return;
LoadSettings();
if (_project is not null && _project.RecipeName != value)
{
_project=null;SelectedFrame=null;Frames.Clear();Preview=null;
RaisePropertyChanged(nameof(Project));RaisePropertyChanged(nameof(Summary));RaisePropertyChanged(nameof(ProjectPath));
Status="已切换配方,请导入视频或打开该配方的标注项目";
}
LoadTrainingResult();
RaisePropertyChanged(nameof(RecipeFolder));
}
}
public string RecipeFolder => string.IsNullOrWhiteSpace(RecipeName) ? "请先选择配方" : RecipeDirectoryFor(RecipeName);
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);
return DesktopPlatform.Recipes.DirectoryFor(name);
}
public string Label { get; set; } = "零件";
public int ExtractStride { get; set; } = 1;
@ -105,7 +121,6 @@ public sealed class MainViewModel : BindableBase
public DelegateCommand ExportCommand { get; }
public DelegateCommand TrainCommand { get; }
public DelegateCommand PickTrainingModelCommand { get; }
public DelegateCommand PickTrainingOutputCommand { get; }
public DelegateCommand OpenTrainingResultsCommand { get; }
public DelegateCommand OnnxCommand { get; }
public DelegateCommand SuggestCommand { get; }
@ -144,11 +159,6 @@ public sealed class MainViewModel : BindableBase
var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" };
if (await dialog.ShowDialogAsync() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
});
PickTrainingOutputCommand = Command(async () =>
{
var dialog = new OpenFolderDialog { Title = "选择训练结果保存目录" };
if (await dialog.ShowDialogAsync() == true) { TrainingOutputDirectory = dialog.FolderName; RaisePropertyChanged(nameof(TrainingOutputDirectory)); }
});
OpenTrainingResultsCommand = Command(() =>
{
var directory = TrainingRunDirectory;
@ -170,7 +180,10 @@ public sealed class MainViewModel : BindableBase
PreviousCommand = Command(() => Move(-1));
NextCommand = Command(() => Move(1));
CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
RevealCommand = Command(() => DesktopPlatform.Reveal(_project?.DirectoryPath ?? Root));
RevealCommand = Command(() =>
{
var directory=RecipeDirectoryFor(RecipeName);Directory.CreateDirectory(directory);DesktopPlatform.Reveal(directory);
});
}
private DelegateCommand Command(Action action)
{
@ -189,7 +202,7 @@ 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 = "yolo11n.pt", device = Device,
outputDirectory = TrainingOutputDirectory };
outputDirectory = Path.Combine(RequireProject().RecipeDirectory, "runs") };
private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
private void SaveLabel()
{
@ -208,7 +221,7 @@ public sealed class MainViewModel : BindableBase
try
{
var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
try { video.InitialDirectory = VideoImportDirectory ?? CameraViewModel.ReadSaveDirectory(Root); }
try { video.InitialDirectory = Path.Combine(RecipeDirectoryFor(RecipeName), "recordings"); }
catch (Exception e) { Append("录像目录配置读取失败:" + e.Message); }
if (await video.ShowDialogAsync() != true) return;
var recipeDirectory = RecipeDirectoryFor(RecipeName);
@ -221,6 +234,9 @@ public sealed class MainViewModel : BindableBase
}
public void Load(string path, int index = 0)
{
var incoming = TrainingProject.Load(path);
var name = string.IsNullOrWhiteSpace(incoming.RecipeName) ? RecipeName : incoming.RecipeName;
path = DesktopPlatform.Recipes.ImportProject(name, path);
_project = TrainingProject.Load(path);
if (!string.IsNullOrWhiteSpace(_project.RecipeName))
{
@ -307,7 +323,7 @@ public sealed class MainViewModel : BindableBase
SaveSettings();
if (!File.Exists(PythonPath))
throw new FileNotFoundException(DesktopPlatform.MissingPythonMessage, PythonPath);
await _worker.RunAsync(PythonPath, Path.Combine(Root, "tools", "worker.py"), request, line =>
await _worker.RunAsync(PythonPath, Path.Combine(DesktopPlatform.ApplicationRoot, "tools", "worker.py"), request, line =>
{
try
{
@ -360,7 +376,8 @@ public sealed class MainViewModel : BindableBase
{
if (IsTraining) return;
LatestWeights = ""; LatestOnnx = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(string.IsNullOrWhiteSpace(RequireProject().RecipeDirectory) ? RequireProject().DirectoryPath : RequireProject().RecipeDirectory, "latest-model.json");
if (string.IsNullOrWhiteSpace(RecipeName)) return;
var file = Path.Combine(RecipeDirectoryFor(RecipeName), "latest-model.json");
if (!File.Exists(file)) return;
try
{
@ -375,13 +392,20 @@ public sealed class MainViewModel : BindableBase
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.Combine(Root, "workspace"));
File.WriteAllText(Path.Combine(Root, "workspace", "settings.json"), JsonSerializer.Serialize(new
{ Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, TrainingOutputDirectory, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
var directory = RecipeDirectoryFor(RecipeName);
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "training-settings.json"), JsonSerializer.Serialize(new
{ Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
}
private void LoadSettings()
{
var path = Path.Combine(Root, "workspace", "settings.json");
var path = string.IsNullOrWhiteSpace(RecipeName) ? Path.Combine(Root, "workspace", "settings.json")
: Path.Combine(RecipeDirectoryFor(RecipeName), "training-settings.json");
// 新配方使用默认参数,避免沿用刚刚查看的其他配方。
ExtractStride=1; MaxFrames=600; ExportEvery=5; Epochs=50; Batch=4; ImageSize=640;
Checkpoint=""; SamConfig="configs/sam2.1/sam2.1_hiera_t.yaml"; Device="auto";
Model="yolo11n.pt"; Endpoint="https://api.example.com/v1"; ApiModel=""; Description="";
foreach (var property in GetType().GetProperties().Where(p => p.CanWrite)) RaisePropertyChanged(property.Name);
if (!File.Exists(path)) return;
try
{
@ -391,6 +415,7 @@ public sealed class MainViewModel : BindableBase
var property = GetType().GetProperty(item.Name);
if (property?.CanWrite == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
else if (property?.CanWrite == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
if (property?.CanWrite == true) RaisePropertyChanged(property.Name);
}
}
catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }

View File

@ -15,14 +15,14 @@
<DockPanel Margin="0,0,0,14">
<StackPanel DockPanel.Dock="Left" Margin="0,0,28,0">
<TextBlock Text="零件标注与训练" FontSize="23" FontWeight="Bold" Foreground="{StaticResource Accent}" />
<TextBlock Text="视频 → 标注 → 复核 → YOLO" Foreground="{StaticResource Dim}" />
<TextBlock Text="{Binding RecipeFolder}" Foreground="{StaticResource Dim}" TextTrimming="CharacterEllipsis" MaxWidth="360" ToolTip.Tip="{Binding RecipeFolder}" />
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
<Button Content="相机与录像" Click="OpenCameraClicked" />
<Button Content="导入视频" Command="{Binding ImportCommand}" />
<Button Content="打开项目" Command="{Binding OpenCommand}" />
<Button Content="保存参数" Command="{Binding SaveParametersCommand}" ToolTip.Tip="保存标注、训练和设置参数,下次打开时自动恢复" />
<Button Content="项目文件夹" Command="{Binding RevealCommand}" />
<Button Content="配方文件夹" Command="{Binding RevealCommand}" />
<Button Content="取消任务" Command="{Binding CancelCommand}" IsEnabled="{Binding IsBusy}" />
</StackPanel>
</DockPanel>

View File

@ -46,7 +46,8 @@ public partial class TrainingPage : UserControl
if(_sop is { CanSelectCamera:false } || _sop is { IsConnected:true })
{_model.Status="请先停止 SOP 采集并等待相机操作完成,再打开录像";return;}
if(TopLevel.GetTopLevel(this) is not Window owner)return;
_cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root));
if(string.IsNullOrWhiteSpace(_model.RecipeName)){_model.Status="请先选择配方,再打开录像";return;}
_cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root,_model.RecipeName));
try { await _cameraWindow.ShowDialog(owner); }
finally { _model.VideoImportDirectory=_cameraWindow.Model.SaveDirectory;_cameraWindow=null; }
}

View File

@ -10,6 +10,7 @@ using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Training;
namespace SopHelper.VVMs.RecipeEditor;
@ -178,7 +179,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
{
if (!string.IsNullOrWhiteSpace(Recipe.Model.Path))
{
var currentPath = Path.GetFullPath(Recipe.Model.Path, AppContext.BaseDirectory);
var currentPath = Path.GetFullPath(Recipe.Model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
var directory = Path.GetDirectoryName(currentPath);
if (Directory.Exists(directory)) dialog.InitialDirectory = directory;
if (File.Exists(currentPath)) dialog.FileName = Path.GetFileName(currentPath);
@ -259,12 +260,26 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
// 只取文件名部分,别让人在这儿塞路径
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName, fileName + ".yaml") : _path;
try
{
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
var saved = SopConfigLoader.Save(Recipe.ToConfig(), path);
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var config = Recipe.ToConfig();
if (config.Sop.Model is { Path.Length: > 0 } model)
{
var source = Path.GetFullPath(model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
var workspace = new RecipeWorkspace(Path.GetDirectoryName(_directory)!);
if (File.Exists(source))
{
var imported = workspace.ImportFile(fileName, source, "models");
model.Path = Path.GetRelativePath(Path.GetDirectoryName(path)!, imported);
}
}
var saved = SopConfigLoader.Save(config, path);
if (Recipe.Model is not null && config.Sop.Model is not null) Recipe.Model.Path = config.Sop.Model.Path;
_path = path;
_isNew = false;

View File

@ -36,6 +36,7 @@
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4" Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
</Grid>
<Button Content="打开配方文件夹" Command="{Binding OpenRecipeFolderCommand}" Margin="0,8,0,0" HorizontalAlignment="Left" />
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />

View File

@ -27,7 +27,8 @@ public class SopPageViewModel : ViewModelBase
private const int MaxTopViolations = 3;
/// <summary>配方目录(相对程序目录)</summary>
private static string RecipeDirectory => Path.Combine(AppContext.BaseDirectory, "configs", "sop");
private static string RecipeDirectory => DesktopPlatform.Recipes.RecipesDirectory;
private static string RecipePath(string fileName) => DesktopPlatform.Recipes.ConfigPath(Path.GetFileNameWithoutExtension(fileName));
private static string LastCameraPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
@ -117,6 +118,11 @@ public class SopPageViewModel : ViewModelBase
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning && !_isCameraBusy);
OpenRecipeFolderCommand = new DelegateCommand(() =>
{
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
catch (Exception error) { Log("warn", "打开配方目录失败:" + error.Message); }
}, () => !string.IsNullOrWhiteSpace(SelectedRecipe));
StatusText = "就绪,请确认运行设置后开始";
LoadLastCamera();
@ -286,6 +292,7 @@ public class SopPageViewModel : ViewModelBase
/// <summary>新建配方(弹窗)</summary>
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
public DelegateCommand OpenRecipeFolderCommand { get; private set; } = null!;
private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
@ -314,6 +321,7 @@ public class SopPageViewModel : ViewModelBase
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
}
/// <summary>
@ -349,7 +357,8 @@ public class SopPageViewModel : ViewModelBase
{
if (_pending is null) return;
var dir = Path.Combine(AppContext.BaseDirectory, "snaps");
if (string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方") return;
var dir = Path.Combine(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe)), "snaps");
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, $"{frame.FrameId}_{frame.Timestamp:HHmmss_fff}.png");
@ -389,8 +398,7 @@ public class SopPageViewModel : ViewModelBase
{
if (!Directory.Exists(RecipeDirectory)) return;
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
foreach (var name in DesktopPlatform.Recipes.Names()) Recipes.Add(name + ".yaml");
if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
}
@ -403,8 +411,7 @@ public class SopPageViewModel : ViewModelBase
Recipes.Clear();
if (Directory.Exists(RecipeDirectory))
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
foreach (var name in DesktopPlatform.Recipes.Names()) Recipes.Add(name + ".yaml");
var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
if (pick is not null) SelectedRecipe = pick;
@ -417,7 +424,7 @@ public class SopPageViewModel : ViewModelBase
/// </summary>
private void EditRecipe()
{
var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
var path = RecipePath(SelectedRecipe!);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
@ -605,7 +612,7 @@ public class SopPageViewModel : ViewModelBase
HandResult = null;
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = Path.Combine(RecipeDirectory, SelectedRecipe);
var path = RecipePath(SelectedRecipe);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
@ -620,7 +627,7 @@ public class SopPageViewModel : ViewModelBase
// 优先使用本配方训练发布的 ONNX,否则使用配方配置中的模型。
var options = new PipelineOptions
{
YoloModelPath = ResolveModel(config.Sop.Model?.Path),
YoloModelPath = ResolveRecipeModel(config.Sop.Model?.Path, Path.GetDirectoryName(path)!),
YoloClasses = config.Sop.Model?.Classes ?? [],
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
@ -658,7 +665,7 @@ public class SopPageViewModel : ViewModelBase
private void LoadTrainedRecipeModel(SopConfig config)
{
var recipeName = Path.GetFileNameWithoutExtension(SelectedRecipe);
var manifest = Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "training", recipeName!, "latest-model.json");
var manifest = Path.Combine(DesktopPlatform.Recipes.DirectoryFor(recipeName!), "latest-model.json");
if (!File.Exists(manifest)) return;
try
{
@ -701,6 +708,13 @@ public class SopPageViewModel : ViewModelBase
return File.Exists(path) ? path : null;
}
private static string? ResolveRecipeModel(string? model, string recipeDirectory)
{
if (string.IsNullOrWhiteSpace(model)) return null;
var local = Path.GetFullPath(model, recipeDirectory);
return File.Exists(local) ? local : ResolveModel(model);
}
private void OnResult(FrameResult result)
{
if (_destroyed || !IsRunning) return;

View File

@ -0,0 +1,209 @@
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Training;
/// <summary>配方设置及其全部数据的统一存储入口。</summary>
public sealed class RecipeWorkspace(string root)
{
public string Root { get; } = Path.GetFullPath(root);
public string RecipesDirectory => Path.Combine(Root, "recipes");
public string DirectoryFor(string name)
{
if (string.IsNullOrWhiteSpace(name) || name is "." or ".." || name.EndsWith('.') ||
name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name.Contains('/') || name.Contains('\\'))
throw new ArgumentException("请先选择有效的配方名");
return Path.Combine(RecipesDirectory, name);
}
public string ConfigPath(string name) => Path.Combine(DirectoryFor(name), name + ".yaml");
public IEnumerable<string> Names() => Directory.Exists(RecipesDirectory)
? Directory.GetDirectories(RecipesDirectory).Select(Path.GetFileName).OfType<string>()
.Where(n => File.Exists(ConfigPath(n))).OrderBy(n => n)
: [];
public static bool IsWithin(string path, string directory) =>
Path.GetFullPath(path).StartsWith(Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
public string ImportFile(string name, string source, string subdirectory)
{
source = Path.GetFullPath(source);
var recipe = DirectoryFor(name);
if (IsWithin(source, recipe)) return source;
if (!File.Exists(source)) throw new FileNotFoundException("配方关联文件不存在", source);
var targetDirectory = Path.Combine(recipe, subdirectory);
Directory.CreateDirectory(targetDirectory);
var target = Path.Combine(targetDirectory, Path.GetFileName(source));
if (File.Exists(target) && !SameContent(source, target))
{
var suffix = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source)))[..10];
target = Path.Combine(targetDirectory, Path.GetFileNameWithoutExtension(source) + "-" + suffix + Path.GetExtension(source));
if (File.Exists(target) && !SameContent(source, target))
throw new IOException("配方中已有同名但内容不同的文件:" + target);
}
if (!File.Exists(target)) File.Copy(source, target);
return target;
}
private static bool SameContent(string first, string second)
{
if (new FileInfo(first).Length != new FileInfo(second).Length) return false;
using var a = File.OpenRead(first); using var b = File.OpenRead(second);
return SHA256.HashData(a).SequenceEqual(SHA256.HashData(b));
}
public string ImportProject(string name, string projectPath)
{
var recipe = DirectoryFor(name);
projectPath = Path.GetFullPath(projectPath);
if (IsWithin(projectPath, recipe)) return projectPath;
var legacy = Path.Combine(Root, "workspace", "training", name);
if (IsWithin(projectPath, legacy))
{
var migrated = Path.Combine(recipe, Path.GetRelativePath(legacy, projectPath));
if (File.Exists(migrated)) return migrated;
}
var source = Path.GetDirectoryName(projectPath)!;
var key = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(projectPath)))[..12];
var destination = Path.Combine(recipe, "parts", "import-" + key);
var target = Path.Combine(destination, "project.json");
if (File.Exists(target)) return target;
CopyTree(source, destination);
var data = JsonNode.Parse(File.ReadAllText(target))!;
RewritePaths(data, new() { [source] = destination });
data["recipeName"] = name; data["recipeDirectory"] = recipe;
var video = data["video"]?.GetValue<string>();
if (!string.IsNullOrWhiteSpace(video) && File.Exists(video)) data["video"] = ImportFile(name, video, "recordings");
WriteJson(target, data);
return target;
}
/// <summary>一次性复制旧数据并修正路径。保留旧文件供回退,后续只使用新目录。</summary>
public void Initialize(params string[] legacyConfigDirectories)
{
Directory.CreateDirectory(RecipesDirectory);
var configs = legacyConfigDirectories.Where(Directory.Exists).Distinct()
.SelectMany(d => Directory.GetFiles(d, "*.yaml"))
.GroupBy(Path.GetFileNameWithoutExtension);
foreach (var group in configs)
{
var name = group.Key!;
var destination = DirectoryFor(name);
var configPath = ConfigPath(name);
if (File.Exists(configPath)) continue;
Directory.CreateDirectory(destination);
var source = group.OrderByDescending(File.GetLastWriteTimeUtc).First();
var oldTraining = Path.Combine(Root, "workspace", "training", name);
var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [oldTraining] = destination };
if (Directory.Exists(oldTraining)) CopyTree(oldTraining, destination);
var registry = Path.Combine(destination, "recipe-training.json");
if (File.Exists(registry))
{
var projects = JsonNode.Parse(File.ReadAllText(registry))?["projects"]?.AsArray();
foreach (var project in projects ?? [])
{
var original = project?.GetValue<string>();
if (string.IsNullOrWhiteSpace(original) || !File.Exists(original) || IsWithin(original, oldTraining)) continue;
var imported = ImportProject(name, original);
mappings[Path.GetDirectoryName(original)!] = Path.GetDirectoryName(imported)!;
}
}
var settings = Path.Combine(Root, "workspace", "settings.json");
if (File.Exists(settings) && !File.Exists(Path.Combine(destination, "training-settings.json")))
File.Copy(settings, Path.Combine(destination, "training-settings.json"));
// 自定义训练输出目录也迁入配方,避免最新模型仍指向外部目录。
var latestPath = Path.Combine(destination, "latest-model.json");
if (File.Exists(latestPath))
{
var latest = JsonNode.Parse(File.ReadAllText(latestPath))!;
var run = latest["runDirectory"]?.GetValue<string>();
if (!string.IsNullOrEmpty(run) && Directory.Exists(run) && !IsWithin(run, oldTraining) && !IsWithin(run, destination))
{
var target = Path.Combine(destination, "runs", Path.GetFileName(run));
CopyTree(run, target); mappings[run] = target;
}
}
var config = SopConfigLoader.Load(source);
if (config.Sop.Model is { Path.Length: > 0 } model)
{
var original = model.Path;
var candidates = new[] { original, Path.Combine(Path.GetDirectoryName(source)!, "..", "..", original), Path.Combine(Root, original) };
var existing = candidates.Where(Path.IsPathRooted).FirstOrDefault(File.Exists);
if (existing is not null)
model.Path = Path.GetRelativePath(destination, ImportFile(name, existing, "models"));
}
// Copy each referenced video; frame/image paths stay relative to their annotation project.
foreach (var project in Directory.GetFiles(destination, "project.json", SearchOption.AllDirectories))
{
var data = JsonNode.Parse(File.ReadAllText(project))!;
var video = data["video"]?.GetValue<string>();
if (!string.IsNullOrWhiteSpace(video) && File.Exists(video))
mappings[video] = ImportFile(name, video, "recordings");
}
foreach (var file in Directory.GetFiles(destination, "*.json", SearchOption.AllDirectories))
{
var node = JsonNode.Parse(File.ReadAllText(file));
RewritePaths(node, mappings);
if (Path.GetFileName(file) == "project.json" && node is JsonObject project)
{ project["recipeName"] = name; project["recipeDirectory"] = destination; }
WriteJson(file, node);
}
foreach (var yaml in Directory.GetFiles(destination, "data.yaml", SearchOption.AllDirectories))
{
var text = File.ReadAllText(yaml);
foreach (var mapping in mappings)
text = text.Replace(mapping.Key.Replace('\\', '/'), mapping.Value.Replace('\\', '/'));
File.WriteAllText(yaml, text);
}
// The config is the commit marker: interrupted migration is safe to retry.
SopConfigLoader.Save(config, configPath + ".migrating");
File.Move(configPath + ".migrating", configPath);
}
}
private static void CopyTree(string source, string destination)
{
if (IsWithin(destination, source)) throw new IOException("导入目录不能包含配方目标目录:" + source);
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source))
{
var target = Path.Combine(destination, Path.GetFileName(file));
if (!File.Exists(target)) File.Copy(file, target);
}
foreach (var child in Directory.GetDirectories(source))
CopyTree(child, Path.Combine(destination, Path.GetFileName(child)));
}
private static string Remap(string value, Dictionary<string, string> mappings)
{
foreach (var (source, target) in mappings.OrderByDescending(p => p.Key.Length))
if (value.Equals(source, StringComparison.OrdinalIgnoreCase)) return target;
else if (value.StartsWith(source.TrimEnd('\\', '/') + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return target + value[source.Length..];
return value;
}
private static void RewritePaths(JsonNode? node, Dictionary<string, string> mappings)
{
if (node is JsonObject obj)
foreach (var (key, value) in obj.ToArray())
{
if (value is JsonValue v && v.TryGetValue<string>(out var text)) obj[key] = Remap(text, mappings);
else RewritePaths(value, mappings);
var mapped = Remap(key, mappings);
if (mapped != key) { var child = obj[key]; obj.Remove(key); obj[mapped] = child; }
}
else if (node is JsonArray array)
for (var i = 0; i < array.Count; i++)
if (array[i] is JsonValue v && v.TryGetValue<string>(out var text)) array[i] = Remap(text, mappings);
else RewritePaths(array[i], mappings);
}
private static void WriteJson(string file, JsonNode? node)
{
var temporary = file + ".tmp";
File.WriteAllText(temporary, node?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, file, true);
}
}

View File

@ -28,7 +28,11 @@ internal static class Smoke
[STAThread]
public static int Main()
{
var settingsPath=Path.GetFullPath("workspace/settings.json");
var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dataRoot);
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",dataRoot);
var settingsPath=Path.Combine(dataRoot,"workspace","settings.json");
var settingsBefore=File.Exists(settingsPath)?File.ReadAllBytes(settingsPath):null;
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
@ -47,6 +51,9 @@ internal static class Smoke
{
if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore);
else if(File.Exists(settingsPath))File.Delete(settingsPath);
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",previousRoot);
if(!Path.GetFullPath(dataRoot).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected test data root");
Directory.Delete(dataRoot,true);
}
return _exit;
}
@ -116,11 +123,29 @@ internal static class Smoke
trainer.ExtractStride=3;trainer.MaxFrames=420;trainer.ExportEvery=2;trainer.ImageSize=960;trainer.Epochs=12;trainer.Batch=2;
saveParameters.Command!.Execute(null);
var restoredTrainer=new SopHelper.Training.MainViewModel(new WorkerClient());
restoredTrainer.RecipeName=trainer.RecipeName;
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 savedRecipe=trainer.RecipeName;
restoredTrainer.RecipeName=savedRecipe;
Check(restoredTrainer.ImageSize==960,"Reopening the same recipe restores its saved training parameters");
trainer.RecipeName="另一配方";
Check(trainer.ImageSize==640&&trainer.ExtractStride==1,"New recipes have independent default parameters");
trainer.ImageSize=320;trainer.SaveParametersCommand.Execute();trainer.RecipeName=savedRecipe;
Check(trainer.ImageSize==960&&trainer.ExtractStride==3,"Switching recipes restores each recipe's own parameters");
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);
var storage=new RecipeWorkspace(trainer.Root);
var createEditor=new RecipeEditorViewModel();
createEditor.OnDialogOpened(new DialogParameters{{"directory",storage.RecipesDirectory},{"new",true},{"config",new SopHelper.Engine.Sop.SopConfig()}});
createEditor.Recipe.FileName="新建配方";createEditor.Recipe.Name="新建配方";createEditor.SaveCommand.Execute();
Check(File.Exists(storage.ConfigPath("新建配方")),"Creating a recipe writes its config inside its own named directory");
createEditor.OnDialogClosed();
var recipeCamera=new CameraViewModel(new FakeCamera(),trainer.Root,savedRecipe);
recipeCamera.SaveDirectory=Path.GetTempPath();
Check(recipeCamera.SaveDirectory==Path.Combine(storage.DirectoryFor(savedRecipe),"recordings")&&!recipeCamera.BrowseCommand.CanExecute(),"Recipe recordings stay in the selected recipe directory");
await recipeCamera.ShutdownAsync();
var recipeFile=storage.ConfigPath(recipeId);
var recipeWorkspace=storage.DirectoryFor(recipeId);
Directory.CreateDirectory(recipeWorkspace);
var modelFile=Path.Combine(recipeWorkspace,recipeId+".onnx");
var manifestFile=Path.Combine(recipeWorkspace,"latest-model.json");
@ -157,17 +182,20 @@ internal static class Smoke
var project=new TrainingProject { FilePath=Path.Combine(temporary,"project.json"),Name="测试零件",Width=640,Height=480,
Frames=[new FrameAnnotation {Index=0,Image="frame.png",Status="unlabeled"}] };
project.Save();trainer.Load(project.FilePath);trainer.DrawBox([10,20,100,200]);trainer.ApproveCommand.Execute();
Check(TrainingProject.Load(project.FilePath).Frames[0].Status=="reviewed","Training annotation and review still save the original project format");
Check(TrainingProject.Load(trainer.Project!.FilePath).Frames[0].Status=="reviewed"&&RecipeWorkspace.IsWithin(trainer.Project.FilePath,storage.DirectoryFor(savedRecipe)),"Opened annotation projects are copied into their recipe and review saves there");
navigation.SelectedIndex=0;navigation.SelectedIndex=1;await Task.Delay(80);
Check(ReferenceEquals(trainer,app.Container.Resolve<SopHelper.Training.MainViewModel>())&&trainer.SelectedFrame?.Box is { Length:4 },"Navigation preserves the training project and annotation state");
trainer.RecipeName="另一配方";
Check(trainer.Project is null&&trainer.Frames.Count==0,"Switching recipes clears the previous recipe's annotation project");
trainer.RecipeName=savedRecipe;trainer.Load(project.FilePath);
Save(window,"training-project");
trainer.DoctorCommand.Execute();
for(var i=0;i<300&&trainer.IsBusy;i++)await Task.Delay(100);
Check(!trainer.IsBusy&&trainer.Progress==100&&trainer.Logs.Contains("Python ")&&trainer.Logs.Contains("PyTorch"),"Training worker command completes using the repository Python runtime");
var editorVm=new RecipeEditorViewModel();
editorVm.OnDialogOpened(new DialogParameters { {"directory",Path.Combine(AppContext.BaseDirectory,"configs","sop")},
{"config",SopHelper.Engine.Sop.SopConfigLoader.Load(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"))},
{"path",Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml")}, {"new",false} });
editorVm.OnDialogOpened(new DialogParameters { {"directory",storage.RecipesDirectory},
{"config",SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("demo"))},
{"path",storage.ConfigPath("demo")}, {"new",false} });
var editor=new RecipeEditor { DataContext=editorVm };
var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);

View File

@ -1,4 +1,6 @@
using SopHelper.Engine.Training;
using SopHelper.Engine.Sop;
using System.Text.Json.Nodes;
var root = Path.Combine(Path.GetTempPath(), "parttrainer-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
@ -18,6 +20,44 @@ try
try { TrainingProject.Load(loaded.FilePath); throw new Exception("Traversal accepted"); }
catch (InvalidDataException) { }
Console.WriteLine("PASS: project persistence, Unicode, invalid box rejection, path traversal rejection");
var storageRoot=Path.Combine(root,"layout");
var store=new RecipeWorkspace(storageRoot);
var legacyConfigs=Path.Combine(storageRoot,"configs","sop");Directory.CreateDirectory(legacyConfigs);
var legacyTraining=Path.Combine(storageRoot,"workspace","training","配方甲");
var part=Path.Combine(legacyTraining,"parts","part1");Directory.CreateDirectory(part);
var video=Path.Combine(root,"source.avi");File.WriteAllText(video,"video");
File.WriteAllText(Path.Combine(part,"frame.jpg"),"image");
var oldProject=new TrainingProject {FilePath=Path.Combine(part,"project.json"),RecipeName="配方甲",RecipeDirectory=legacyTraining,Name="零件甲",Video=video,Width=100,Height=100,
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};oldProject.Save();
var externalPart=Path.Combine(root,"external-part");Directory.CreateDirectory(externalPart);
File.WriteAllText(Path.Combine(externalPart,"frame.jpg"),"image");
var externalProject=new TrainingProject {FilePath=Path.Combine(externalPart,"project.json"),Name="零件乙",Video=video,Width=100,Height=100,
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};externalProject.Save();
var externalRun=Path.Combine(root,"external-run");Directory.CreateDirectory(externalRun);
var weights=Path.Combine(externalRun,"配方甲.pt");File.WriteAllText(weights,"weights");
var onnx=Path.ChangeExtension(weights,".onnx");File.WriteAllText(onnx,"model");
File.WriteAllText(Path.Combine(legacyTraining,"latest-model.json"),System.Text.Json.JsonSerializer.Serialize(new {weights,onnx,runDirectory=externalRun,recipeName="配方甲",classes=new[]{"零件甲"},imageSize=640}));
File.WriteAllText(Path.Combine(legacyTraining,"recipe-training.json"),new JsonObject { ["projects"]=new JsonArray(oldProject.FilePath,externalProject.FilePath),["labels"]=new JsonObject{[oldProject.FilePath]="零件甲",[externalProject.FilePath]="零件乙"},["classes"]=new JsonArray("零件甲","零件乙")}.ToJsonString());
var config=new SopConfig();config.Sop.Name="配方甲";config.Sop.Model=new ModelDef{Path=onnx};
SopConfigLoader.Save(config,Path.Combine(legacyConfigs,"配方甲.yaml"));
store.Initialize(legacyConfigs);
var recipe=store.DirectoryFor("配方甲");
var migratedProject=TrainingProject.Load(Path.Combine(recipe,"parts","part1","project.json"));
if(migratedProject.RecipeDirectory!=recipe||!RecipeWorkspace.IsWithin(migratedProject.Video,recipe)||!File.Exists(migratedProject.Video))throw new Exception("Project/video migration failed");
var latest=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"latest-model.json")))!;
if(!RecipeWorkspace.IsWithin(latest["weights"]!.GetValue<string>(),recipe)||!File.Exists(latest["onnx"]!.GetValue<string>()))throw new Exception("External training output was not migrated");
var registry=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"recipe-training.json")))!;
if(registry["projects"]![0]!.GetValue<string>()!=migratedProject.FilePath||registry["labels"]![migratedProject.FilePath]!.GetValue<string>()!="零件甲")throw new Exception("Registry references were not rebased");
var relocatedExternal=registry["projects"]![1]!.GetValue<string>();
if(!RecipeWorkspace.IsWithin(relocatedExternal,recipe)||TrainingProject.Load(relocatedExternal).RecipeDirectory!=recipe)throw new Exception("External annotation projects were not migrated");
var managedModel=SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Model!.Path;
if(Path.IsPathRooted(managedModel)||!File.Exists(Path.Combine(recipe,managedModel)))throw new Exception("Configured model was not localized");
File.WriteAllText(Path.Combine(legacyConfigs,"配方甲.yaml"),"obsolete");store.Initialize(legacyConfigs);
if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Migration overwrote managed settings");
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Migration modified original data");
foreach(var bad in new[]{"..","../escape","a/b","a\\b"})
try{store.DirectoryFor(bad);throw new Exception("Unsafe recipe name accepted");}catch(ArgumentException){}
Console.WriteLine("PASS: Unified recipe migration, model/video copies, registry rebasing, independent config and safe names");
if (args.Length > 0)
{
var script = Path.Combine(root, "worker.py");

View File

@ -83,6 +83,26 @@ class DatasetTests(unittest.TestCase):
self.assertTrue(result["prompt"])
self.assertNotIn("local-test-secret", self.project.read_text(encoding="utf-8"))
def test_import_stores_video_in_recipe(self):
import cv2
import numpy as np
video = self.root / "source.avi"
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"MJPG"), 10, (64, 64))
self.assertTrue(writer.isOpened())
for _ in range(8):
writer.write(np.full((64, 64, 3), 128, dtype=np.uint8))
writer.release()
recipe = (self.root / "recipes" / "配方甲").resolve()
output = recipe / "parts" / "part1"
worker.extract({"video": str(video), "output": str(output), "recipeName": "配方甲",
"recipeDirectory": str(recipe), "maxFrames": 10})
project = worker.read_json(output / "project.json")
self.assertEqual(Path(project["video"]).parent, recipe / "recordings")
self.assertTrue(Path(project["video"]).is_file())
self.assertTrue(video.is_file())
self.assertEqual(len(project["frames"]), 8)
self.assertEqual(worker.read_json(recipe / "recipe-training.json")["projects"], [str(output / "project.json")])
if __name__ == "__main__":
unittest.main()

View File

@ -102,6 +102,16 @@ def extract(request):
staging = target.with_name(target.name + ".importing-" + uuid.uuid4().hex[:8])
staging.mkdir(parents=True)
try:
if request.get("recipeDirectory"):
directory = Path(request["recipeDirectory"]).resolve() / "recordings"
directory.mkdir(parents=True, exist_ok=True)
if not video.is_relative_to(directory.parent):
stored = directory / video.name
if stored.exists() and sha256_file(stored) != sha256_file(video):
stored = directory / (video.stem + "-" + sha256_file(video)[:10] + video.suffix)
if not stored.exists():
shutil.copy2(video, stored)
video = stored
frames_dir = staging / "frames"
frames_dir.mkdir()
fps = cap.get(cv2.CAP_PROP_FPS)
@ -351,8 +361,7 @@ def train(request):
device = (0 if torch.cuda.is_available() else "cpu") if device == "auto" else device
if device == "cuda":
device = "0"
output_directory = str(request.get("outputDirectory", "")).strip()
output_directory = Path(output_directory).resolve() if output_directory else root / "runs"
output_directory = 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, resume=False, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
@ -362,7 +371,8 @@ def train(request):
# 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")
published = root / "models" / Path(model.trainer.save_dir).name / (safe_name + ".pt")
published.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(best, published)
emit("训练已结束,正在导出配方 ONNX…", event="onnx_export_started", weights=str(published),
runDirectory=str(model.trainer.save_dir))