diff --git a/.gitignore b/.gitignore index 94e2380..0123ea7 100644 --- a/.gitignore +++ b/.gitignore @@ -398,6 +398,7 @@ FodyWeavers.xsd /.venv/ /.cache/ /workspace/ +/recipes/ *.pt /python/ diff --git a/README.md b/README.md index 8ce1058..517aa51 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs index 3dc66d6..da8e3f1 100644 --- a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs +++ b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs @@ -7,7 +7,23 @@ namespace SopHelper.Presentation; internal static class DesktopPlatform { + private static readonly Lazy 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 { diff --git a/src/SopHelper.Avalonia/Program.cs b/src/SopHelper.Avalonia/Program.cs index 5635c20..d24571d 100644 --- a/src/SopHelper.Avalonia/Program.cs +++ b/src/SopHelper.Avalonia/Program.cs @@ -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(); diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index ac7c506..65239c6 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -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); diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs index 05c5143..27dba1c 100644 --- a/src/SopHelper.Avalonia/Training/MainViewModel.cs +++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs @@ -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 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 = "设置文件不可读,已使用默认配置"; } diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml index 8ec80e7..3663aeb 100644 --- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml +++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml @@ -15,14 +15,14 @@ - +