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 @@
-
+
@@ -76,8 +76,9 @@
-
-
+
+
+
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs b/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
index 6bd6bdf..c9850b2 100644
--- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
+++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
@@ -2,6 +2,7 @@ using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Threading;
+using Avalonia.Platform.Storage;
using SopHelper.Engine.Camera;
using SopHelper.VVMs.SopPage;
@@ -12,6 +13,7 @@ public partial class TrainingPage : UserControl
private readonly MainViewModel _model;
private readonly SopPageViewModel? _sop;
private CameraWindow? _cameraWindow;
+ private ImportPartDialog? _importPartDialog;
private Window? _host;
private bool _closing,_closedSafely;
private readonly Func _selectedCameraProvider;
@@ -24,6 +26,8 @@ public partial class TrainingPage : UserControl
_canOpenCamera=canOpenCamera??(()=>true);
Canvas.BoxDrawn+=model.DrawBox;
model.ReadApiKey=()=>ApiKey.Text??"";
+ model.SelectImportPartAsync=SelectImportPartAsync;
+ model.SelectImportVideoAsync=SelectImportVideoAsync;
AttachedToVisualTree+=(_,_)=>
{
if (!embedded && !model.IsBusy && sop != null)
@@ -48,6 +52,7 @@ public partial class TrainingPage : UserControl
}
private async void OpenCameraClicked(object? sender,RoutedEventArgs e)
{
+ if(_closing || !_model.IsIdle)return;
if(!_canOpenCamera() || _sop is { CanSelectCamera:false } || _sop is { IsConnected:true })
{_model.Status="请先停止其他相机预览或 SOP 采集,再打开零件录像";return;}
if(TopLevel.GetTopLevel(this) is not Window owner)return;
@@ -58,9 +63,30 @@ public partial class TrainingPage : UserControl
}
public async Task ShutdownAsync()
{
+ _closing=true;_importPartDialog?.Close(null);
await _model.StopAsync();
if(_cameraWindow is { } cameraWindow){await cameraWindow.Model.ShutdownAsync();cameraWindow.Close();}
}
+ private async Task SelectImportPartAsync(IReadOnlyList parts)
+ {
+ if(_closing || TopLevel.GetTopLevel(this) is not Window owner)return null;
+ var dialog=new ImportPartDialog(parts);_importPartDialog=dialog;
+ try{return await dialog.ShowDialog(owner);}
+ finally{_importPartDialog=null;}
+ }
+ private async Task SelectImportVideoAsync()
+ {
+ if(_closing || TopLevel.GetTopLevel(this) is not Window owner)return null;
+ var directory=_model.VideoImportDirectory??System.IO.Path.Combine(_model.RecipeFolder,"recordings");
+ var files=await owner.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
+ {
+ Title="选择目标零件的视频",AllowMultiple=false,
+ SuggestedStartLocation=System.IO.Directory.Exists(directory)?await owner.StorageProvider.TryGetFolderFromPathAsync(directory):null,
+ FileTypeFilter=[new FilePickerFileType("视频"){Patterns=["*.mp4","*.avi","*.mov","*.mkv","*.wmv"]},FilePickerFileTypes.All]
+ });
+ if(files.Count==0)return null;
+ return files[0].TryGetLocalPath()??throw new System.IO.IOException("请选择本地视频文件");
+ }
private async void HostClosing(object? sender,WindowClosingEventArgs e)
{
if(_closedSafely)return;e.Cancel=true;if(_closing)return;_closing=true;_host!.IsEnabled=false;
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 4c3dfa9..4d3143d 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -142,6 +142,7 @@ internal static class Smoke
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");
+ await CheckTrainingImport(lifetime,trainingDialog,trainingView,trainer);
var savedRecipe=trainer.RecipeName;
restoredTrainer.RecipeName=savedRecipe;
Check(restoredTrainer.ImageSize==960,"Reopening the same recipe restores its saved training parameters");
@@ -236,7 +237,13 @@ internal static class Smoke
Check(editorVm.Recipe.Steps.Count>0,"Original recipe ViewModel loads steps");
Check(editorVm.Recipe.Steps[0].Detection?.Method=="hand_in_region","Recipe bindings preserve selected condition method");
Check(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())==recipeBefore,"Opening all recipe tabs does not alter any recipe fields");
- dialog.Close();editorVm.OnDialogClosed();
+ var closingTrainer=editorVm.TrainingView!.Model;
+ closingTrainer.ImportCommand.Execute();await Task.Delay(40);
+ Check(closingTrainer.IsImporting&&lifetime.Windows.OfType().Any(),"Import part picker is open before closing the editor");
+ dialog.Close();
+ for(var i=0;i<100&&dialog.IsVisible;i++)await Task.Delay(20);
+ Check(!dialog.IsVisible&&!closingTrainer.IsImporting&&!lifetime.Windows.OfType().Any(),"Closing the editor cancels the part picker without starting import");
+ editorVm.OnDialogClosed();
var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
@@ -288,6 +295,71 @@ internal static class Smoke
catch(Exception ex){Console.Error.WriteLine(ex);}
finally{lifetime.Shutdown(_exit);}
}
+ private static async Task CheckTrainingImport(IClassicDesktopStyleApplicationLifetime lifetime,Window owner,TrainingPage view,SopHelper.Training.MainViewModel trainer)
+ {
+ var store=new RecipeWorkspace(trainer.Root);var configPath=store.ConfigPath(trainer.RecipeName);
+ var config=SopHelper.Engine.Sop.SopConfigLoader.Load(configPath);config.Sop.Parts=["支架","螺丝","测试零件"];
+ SopHelper.Engine.Sop.SopConfigLoader.Save(config,configPath);trainer.RefreshPartNames();
+ var selectVideo=trainer.SelectImportVideoAsync;var selectPart=trainer.SelectImportPartAsync;
+ var videoCalls=0;
+ async Task WaitImport()
+ {
+ for(var i=0;i<400&&(trainer.IsImporting||trainer.IsBusy);i++)await Task.Delay(25);
+ Check(!trainer.IsImporting&&!trainer.IsBusy,"Video import operation finishes");
+ }
+ async Task Picker()
+ {
+ trainer.ImportCommand.Execute();await Task.Delay(40);
+ return lifetime.Windows.OfType().Single();
+ }
+ void Confirm(ImportPartDialog dialog,string name)
+ {
+ dialog.GetVisualDescendants().OfType().Single().SelectedItem=name;
+ var button=dialog.GetVisualDescendants().OfType