From d92214b6f478348b2dc256bde3b0ccfd45099250 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Tue, 10 Nov 2026 11:29:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=BC=E5=85=A5=E8=AE=AD=E7=BB=83=E8=A7=86?= =?UTF-8?q?=E9=A2=91=E5=89=8D=E9=80=89=E6=8B=A9=E7=9B=AE=E6=A0=87=E9=9B=B6?= =?UTF-8?q?=E4=BB=B6=E5=B9=B6=E9=94=81=E5=AE=9A=E9=A1=B9=E7=9B=AE=E7=9B=AE?= =?UTF-8?q?=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../Training/ImportPartDialog.cs | 32 ++++++++ .../Training/MainViewModel.cs | 80 ++++++++++++------- .../Training/TrainingPage.axaml | 7 +- .../Training/TrainingPage.axaml.cs | 26 ++++++ tests/Avalonia.Smoke/Program.cs | 74 ++++++++++++++++- tests/PartCatalog.Smoke/Program.cs | 7 +- 7 files changed, 192 insertions(+), 36 deletions(-) create mode 100644 src/SopHelper.Avalonia/Training/ImportPartDialog.cs diff --git a/README.md b/README.md index 28af062..8d6f877 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部 - 每份配方保留一段标准视频;“重新录制”先弹窗确认,确认后删除旧视频并重新开始,取消会保留原视频。录制中发起重新录制时会先暂停,取消后恢复原先的录制状态。 3. 在“运行设置 → 编辑配方 → 零件标注与训练”中进行相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。侧栏只保留 SOP 辅助和运行设置。 - 每段相机录像最长 5 分钟,达到上限后自动停止、保存文件并弹窗提示保存位置;相机预览继续运行,可再次开始录像。 - - 所属配方固定为当前编辑的配方,在标注页选择已有零件类别,每个视频录入一个零件;新配方先保存后再标注或训练。录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。 + - 所属配方固定为当前编辑的配方。“导入视频”先弹窗选择已有目标零件,再选择视频;每个视频只标注该零件,导入后目标只读锁定,标注和训练不能切换,重新打开项目仍沿用原目标。取消任一步均保留当前项目。新配方先保存后再标注或训练。录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。 - 点击“训练并更新配方模型”,自动累计导出该配方所有已加入视频的复核数据,并使用上一版配方模型开始新训练;首次使用 `yolo11n.pt`。无需手选权重。 - 同名零件的多个视频共用类别,训练导出按零件列表顺序分配类别编号,并拒绝列表以外的项目类别。每个视频均需完成足够的训练段和末尾验证段复核。 - 训练成功后自动将 `配方名.pt` 和 `配方名.onnx` 发布到同配方的 `models/训练版本/`;训练曲线和日志保存在 `runs`,数据集保存在 `datasets`。`latest-model.json` 指向最新完整版本,重新应用配方即可加载。 diff --git a/src/SopHelper.Avalonia/Training/ImportPartDialog.cs b/src/SopHelper.Avalonia/Training/ImportPartDialog.cs new file mode 100644 index 0000000..bc2a0f8 --- /dev/null +++ b/src/SopHelper.Avalonia/Training/ImportPartDialog.cs @@ -0,0 +1,32 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; + +namespace SopHelper.Training; + +/// 每次导入显式选择目标,确认前不修改当前标注项目。 +public sealed class ImportPartDialog : Window +{ + public ImportPartDialog(IReadOnlyList parts) + { + Title = "选择目标零件"; Width = 460; SizeToContent = SizeToContent.Height; + CanResize = false; WindowStartupLocation = WindowStartupLocation.CenterOwner; + var picker = new ComboBox { Name = "ImportTargetPartPicker", ItemsSource = parts, HorizontalAlignment = HorizontalAlignment.Stretch, PlaceholderText = "请选择本视频要标注的零件" }; + var confirm = new Button { Content = "下一步:选择视频", IsEnabled = false, IsDefault = true }; + var cancel = new Button { Content = "取消", IsCancel = true }; + picker.SelectionChanged += (_, _) => confirm.IsEnabled = picker.SelectedItem is string; + confirm.Click += (_, _) => { if (picker.SelectedItem is string target) Close(target); }; + cancel.Click += (_, _) => Close(null); + Content = new StackPanel + { + Margin = new Thickness(20), Spacing = 16, + Children = + { + new TextBlock { Text = "每个视频只标注一个目标零件。导入后,目标零件将锁定,标注和训练时不能切换。", TextWrapping = TextWrapping.Wrap }, + picker, + new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Spacing = 8, Children = { cancel, confirm } } + } + }; + } +} diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs index da79298..305dfe0 100644 --- a/src/SopHelper.Avalonia/Training/MainViewModel.cs +++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs @@ -22,6 +22,8 @@ public sealed class MainViewModel : BindableBase private FrameAnnotation? _selected; private BitmapImage? _preview; private bool _busy; + private bool _importing, _stopping; + private Task? _importTask; private double _progress; private string _status = "新建项目:导入视频,在任意清晰帧拖动画框"; private string _logs = ""; @@ -42,7 +44,12 @@ public sealed class MainViewModel : BindableBase public TrainingProject? Project => _project; public ObservableCollection Frames { get; } = []; public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); } } - public bool IsIdle => !IsBusy; + public bool IsIdle => !IsBusy && !IsImporting && !_stopping; + public bool IsImporting + { + get => _importing; + private set { SetProperty(ref _importing, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); } + } public double Progress { get => _progress; set => SetProperty(ref _progress, value); } public string Status { get => _status; set => SetProperty(ref _status, value); } public string Logs { get => _logs; set => SetProperty(ref _logs, value); } @@ -91,7 +98,7 @@ public sealed class MainViewModel : BindableBase LoadSettings(); if (_project is not null && _project.RecipeName != value) { - _project=null;SelectedFrame=null;Frames.Clear();Preview=null; + _project=null;Label="";SelectedFrame=null;Frames.Clear();Preview=null; RaisePropertyChanged(nameof(Project));RaisePropertyChanged(nameof(Summary));RaisePropertyChanged(nameof(ProjectPath)); Status="已切换配方,请导入视频或打开该配方的标注项目"; } @@ -109,10 +116,11 @@ public sealed class MainViewModel : BindableBase } public ObservableCollection PartNames { get; } = []; private string _label = ""; - public string Label { get => _label; set => SetProperty(ref _label, value); } + public string Label { get => _label; private set => SetProperty(ref _label, value); } + public Func, Task>? SelectImportPartAsync { get; set; } + public Func>? SelectImportVideoAsync { get; set; } public void RefreshPartNames() { - var selected = Label; PartNames.Clear(); if (!string.IsNullOrWhiteSpace(RecipeName)) { @@ -120,12 +128,11 @@ public sealed class MainViewModel : BindableBase if (File.Exists(path)) foreach (var name in PartCatalog.Read(SopConfigLoader.Load(path), RecipeDirectoryFor(RecipeName))) PartNames.Add(name); } - Label = PartNames.Contains(selected) ? selected : ""; } - private void ValidatePartSelection() + private void ValidatePart(string name) { RefreshPartNames(); - if (!PartNames.Contains(Label)) throw new InvalidOperationException("请先在配方编辑的“零件列表”中添加零件,再选择零件类别"); + if (!PartNames.Contains(name)) throw new InvalidOperationException("目标零件不在当前配方的零件列表中,请先维护并保存零件列表,再重新导入视频"); } public int ExtractStride { get; set; } = 1; public int MaxFrames { get; set; } = 600; @@ -172,7 +179,8 @@ public sealed class MainViewModel : BindableBase SaveSettings(); Status = "参数已保存,下次打开时自动恢复"; }); - ImportCommand = Command(Import); + ImportCommand = new DelegateCommand(() => _importTask = ImportAsync(), () => IsIdle); + Commands.Add(ImportCommand); OpenCommand = Command(async () => { var partsDirectory = Path.Combine(RecipeDirectoryFor(RecipeName), "parts"); @@ -181,9 +189,9 @@ public sealed class MainViewModel : BindableBase if (await dialog.ShowDialogAsync() == true) Load(dialog.FileName); }); DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false)); - PropagateCommand = Command(async () => { SaveLabel(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); }); - ExportCommand = Command(async () => { SaveLabel(); await Run(Request("export")); }); - TrainCommand = Command(async () => { SaveLabel(); await Run(Request("train")); }); + PropagateCommand = Command(async () => { ValidateProjectTarget(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); }); + ExportCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("export")); }); + TrainCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("train")); }); PickTrainingModelCommand = Command(async () => { var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" }; @@ -195,10 +203,10 @@ public sealed class MainViewModel : BindableBase if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练"); DesktopPlatform.Reveal(directory); }); - OnnxCommand = Command(async () => { SaveLabel(); await Run(Request("onnx")); }); + OnnxCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("onnx")); }); SuggestCommand = Command(async () => { - SaveLabel(); + ValidateProjectTarget(); if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧"); await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index, endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke()); @@ -217,7 +225,7 @@ public sealed class MainViewModel : BindableBase } private DelegateCommand Command(Action action) { - var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => !IsBusy); + var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => IsIdle); Commands.Add(command); return command; } private DelegateCommand Command(Func action) @@ -226,7 +234,7 @@ public sealed class MainViewModel : BindableBase { try { await action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } - }, () => !IsBusy); + }, () => IsIdle); Commands.Add(command); return command; } // Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting. @@ -234,33 +242,47 @@ public sealed class MainViewModel : BindableBase valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = "yolo11n.pt", device = Device, outputDirectory = Path.Combine(RequireProject().RecipeDirectory, "runs") }; private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目"); - private void SaveLabel() + private void ValidateProjectTarget() { var project = RequireProject(); - ValidatePartSelection(); + ValidatePart(Label); + if (project.Name != Label) throw new InvalidOperationException("标注项目的目标零件已被修改,请重新打开正确的项目;目标零件不能在标注或训练时切换"); 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(); + project.Save(); } - private async void Import() + private async Task ImportAsync() { + if (!IsIdle) return; + IsImporting = true; try { - var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" }; - try { video.InitialDirectory = Path.Combine(RecipeDirectoryFor(RecipeName), "recordings"); } - catch (Exception e) { Append("录像目录配置读取失败:" + e.Message); } - if (await video.ShowDialogAsync() != true) return; var recipeDirectory = RecipeDirectoryFor(RecipeName); - ValidatePartSelection(); + RefreshPartNames(); + if (PartNames.Count == 0) throw new InvalidOperationException("请先在配方编辑的“零件列表”中添加并保存目标零件,再导入视频"); + if (SelectImportPartAsync is null) throw new InvalidOperationException("请在标注页面导入视频并选择目标零件"); + var target = await SelectImportPartAsync(PartNames.ToArray()); + if (_stopping || string.IsNullOrEmpty(target)) { Status = "已取消导入,原标注项目保持不变"; return; } + ValidatePart(target); + string? videoPath; + if (SelectImportVideoAsync is not null) videoPath = await SelectImportVideoAsync(); + else + { + var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*", InitialDirectory = Path.Combine(recipeDirectory, "recordings") }; + videoPath = await video.ShowDialogAsync() == true ? video.FileName : null; + } + if (_stopping || string.IsNullOrWhiteSpace(videoPath)) { Status = "已取消导入,原标注项目保持不变"; return; } + ValidatePart(target); 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)) + if (await Run(new { action = "extract", video = videoPath, output, name = target, recipeName = RecipeName, recipeDirectory, stride = ExtractStride, maxFrames = MaxFrames }, reload: false)) Load(Path.Combine(output, "project.json")); } catch (Exception e) { Status = e.Message; Append(e.Message); } + finally { IsImporting = false; } } public void Load(string path, int index = 0) { @@ -399,8 +421,10 @@ public sealed class MainViewModel : BindableBase public void Cancel() => _cancellation?.Cancel(); public async Task StopAsync() { + _stopping = true; RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); Cancel(); if (_completion != null) await _completion.Task; + if (_importTask != null) await _importTask; } private static string FormatMetrics(JsonElement metrics) => string.Join(Environment.NewLine, metrics.EnumerateObject().Where(m => m.Value.ValueKind == JsonValueKind.Number) @@ -446,9 +470,9 @@ public sealed class MainViewModel : BindableBase foreach (var item in settings.RootElement.EnumerateObject()) { 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); + if (property?.SetMethod?.IsPublic == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString()); + else if (property?.SetMethod?.IsPublic == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32()); + if (property?.SetMethod?.IsPublic == true) RaisePropertyChanged(property.Name); } } catch (Exception) { Status = "设置文件不可读,已使用默认配置"; } diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml index d715dd3..9576287 100644 --- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml +++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml @@ -18,7 +18,7 @@ -