From 7cb38481bb94fba6691a52e772a8a66372bf7be7 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Tue, 10 Nov 2026 22:40:56 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=86=E9=A2=91=E6=A0=87=E6=B3=A8=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=90=8C=E5=B8=A7=E5=A4=9A=E9=9B=B6=E4=BB=B6=E5=92=8C?= =?UTF-8?q?=E6=8C=89=E9=9B=B6=E4=BB=B6=E7=8B=AC=E7=AB=8B=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E4=BC=A0=E6=92=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Training/AnnotationCanvas.cs | 19 +++- .../Training/ImportPartDialog.cs | 32 ------ .../Training/MainViewModel.cs | 107 +++++++++++++----- .../Training/TrainingPage.axaml | 25 ++-- .../Training/TrainingPage.axaml.cs | 15 +-- .../Training/PartCatalog.cs | 9 +- .../Training/Project.cs | 25 +++- tests/Avalonia.Smoke/Program.cs | 88 ++++++-------- tests/PartCatalog.Smoke/Program.cs | 13 ++- tests/Training.Smoke/Program.cs | 2 +- tests/Training.WorkerSmoke/check.py | 10 +- tests/test_worker.py | 69 ++++++++++- tools/worker.py | 100 +++++++++++----- 13 files changed, 323 insertions(+), 191 deletions(-) delete mode 100644 src/SopHelper.Avalonia/Training/ImportPartDialog.cs diff --git a/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs b/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs index 21a92d3..6e6c6ac 100644 --- a/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs +++ b/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs @@ -4,6 +4,7 @@ using Avalonia.Input; using Avalonia.Media; using System.Globalization; using SopHelper.Presentation.Imaging; +using SopHelper.Engine.Training; namespace SopHelper.Training; public sealed class AnnotationCanvas : Control @@ -11,6 +12,8 @@ public sealed class AnnotationCanvas : Control public static readonly StyledProperty SourceProperty=AvaloniaProperty.Register(nameof(Source)); public static readonly StyledProperty BoxProperty=AvaloniaProperty.Register(nameof(Box)); public static readonly StyledProperty TargetNameProperty=AvaloniaProperty.Register(nameof(TargetName), ""); + public static readonly StyledProperty?> AnnotationsProperty=AvaloniaProperty.Register?>(nameof(Annotations)); + public IReadOnlyList? Annotations {get=>GetValue(AnnotationsProperty);set=>SetValue(AnnotationsProperty,value);} public BitmapSource? Source {get=>GetValue(SourceProperty);set=>SetValue(SourceProperty,value);} public double[]? Box {get=>GetValue(BoxProperty);set=>SetValue(BoxProperty,value);} public string TargetName {get=>GetValue(TargetNameProperty);set=>SetValue(TargetNameProperty,value);} @@ -19,7 +22,7 @@ public sealed class AnnotationCanvas : Control private double _zoom=1; private Vector _offset; private Point? _panStart; - static AnnotationCanvas(){AffectsRender(SourceProperty,BoxProperty,TargetNameProperty);} + static AnnotationCanvas(){AffectsRender(SourceProperty,BoxProperty,TargetNameProperty,AnnotationsProperty);} public AnnotationCanvas(){ClipToBounds=true;Cursor=new Cursor(StandardCursorType.Cross);Focusable=true;} private Rect ImageRect { @@ -56,6 +59,13 @@ public sealed class AnnotationCanvas : Control { dc.DrawRectangle(Brushes.Transparent,null,new Rect(Bounds.Size));var image=ImageRect;if(Source is null||image.Width<=0)return; dc.DrawImage(Source,image);var pen=new Pen(new SolidColorBrush(Color.FromRgb(0,220,220)),2); + foreach(var item in Annotations??[]) + { + if(item.Label==TargetName||item.Box is not {Length:4} other)continue; + var scale=image.Width/Source.PixelWidth; + var rect=new Rect(image.X+other[0]*scale,image.Y+other[1]*scale,(other[2]-other[0])*scale,(other[3]-other[1])*scale); + dc.DrawRectangle(null,new Pen(Brushes.Orange,2),rect);DrawTargetName(dc,rect,Brushes.Orange,item.Label); + } if(Box is { Length:4 } b) { var scale=image.Width/Source.PixelWidth; @@ -70,12 +80,13 @@ public sealed class AnnotationCanvas : Control DrawTargetName(dc,rect,Brushes.Yellow); } } - private void DrawTargetName(DrawingContext dc,Rect box,IBrush foreground) + private void DrawTargetName(DrawingContext dc,Rect box,IBrush foreground,string? label=null) { - if(string.IsNullOrWhiteSpace(TargetName)||Bounds.Width<=8||Bounds.Height<=8|| + label??=TargetName; + if(string.IsNullOrWhiteSpace(label)||Bounds.Width<=8||Bounds.Height<=8|| box.Right<0||box.Left>Bounds.Width||box.Bottom<0||box.Top>Bounds.Height)return; const double padding=4; - var text=new FormattedText(TargetName,CultureInfo.CurrentCulture,FlowDirection.LeftToRight, + var text=new FormattedText(label,CultureInfo.CurrentCulture,FlowDirection.LeftToRight, new Typeface("Microsoft YaHei, Noto Sans CJK SC"),14,foreground) {MaxTextWidth=Math.Max(1,Bounds.Width-2*padding),MaxLineCount=1,Trimming=TextTrimming.CharacterEllipsis}; var size=new Size(text.Width+2*padding,text.Height+2*padding); diff --git a/src/SopHelper.Avalonia/Training/ImportPartDialog.cs b/src/SopHelper.Avalonia/Training/ImportPartDialog.cs deleted file mode 100644 index bc2a0f8..0000000 --- a/src/SopHelper.Avalonia/Training/ImportPartDialog.cs +++ /dev/null @@ -1,32 +0,0 @@ -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 04626e2..69a7564 100644 --- a/src/SopHelper.Avalonia/Training/MainViewModel.cs +++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs @@ -61,7 +61,10 @@ public sealed class MainViewModel : BindableBase public string FrameInfo => _selected == null || _project == null ? "拖动画框以标记零件" : $"第 {_selected.Index + 1} 帧 · 原视频帧 {_selected.SourceIndex} · {(_project.Fps > 0 ? (_selected.SourceIndex / _project.Fps).ToString("F2") + " 秒" : "时间未知")} · {_selected.Display}"; public string ProjectPath => _project?.FilePath ?? "项目会自动保存到你选择的文件夹"; public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); } - public double[]? CurrentBox => _selected?.Box; + private ObjectAnnotation? CurrentObject => _selected?.Objects.FirstOrDefault(o => o.Label == Label); + public double[]? CurrentBox => CurrentObject?.Box; + public IReadOnlyList CurrentAnnotations => _selected?.Objects.Where(o => o.Box != null).ToArray() ?? []; + public string AnnotationSummary => string.Join("\n", CurrentAnnotations.Select(o => $"{o.Label} · {(o.Status == "reviewed" ? "已确认" : "待复核")}")); public FrameAnnotation? SelectedFrame { get => _selected; @@ -80,6 +83,7 @@ public sealed class MainViewModel : BindableBase } catch (Exception e) { Status = "图像读取失败:" + e.Message; Preview = null; } RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); + RaisePropertyChanged(nameof(CurrentAnnotations)); RaisePropertyChanged(nameof(AnnotationSummary)); } } // Configuration is saved locally, except the API key which is passed only through the worker environment. @@ -120,23 +124,41 @@ public sealed class MainViewModel : BindableBase } public ObservableCollection PartNames { get; } = []; private string _label = ""; - public string Label { get => _label; private set => SetProperty(ref _label, value); } - public Func, Task>? SelectImportPartAsync { get; set; } + public string Label + { + get => _label; + set + { + if (IsBusy || IsImporting || value is null || (!string.IsNullOrEmpty(value) && !PartNames.Contains(value))) return; + if (!SetProperty(ref _label, value)) return; + RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(CurrentAnnotations)); + } + } public Func>? SelectImportVideoAsync { get; set; } public void RefreshPartNames() { - PartNames.Clear(); + var selected = Label; + IReadOnlyList names = []; if (!string.IsNullOrWhiteSpace(RecipeName)) { var path = DesktopPlatform.Recipes.ConfigPath(RecipeName); if (File.Exists(path)) - foreach (var name in PartCatalog.Read(SopConfigLoader.Load(path), RecipeDirectoryFor(RecipeName))) PartNames.Add(name); + names = PartCatalog.Read(SopConfigLoader.Load(path), RecipeDirectoryFor(RecipeName)); } + for (var index = PartNames.Count - 1; index >= 0; index--) + if (!names.Contains(PartNames[index])) PartNames.RemoveAt(index); + for (var index = 0; index < names.Count; index++) + { + var existing = PartNames.IndexOf(names[index]); + if (existing < 0) PartNames.Insert(index, names[index]); + else if (existing != index) PartNames.Move(existing, index); + } + Label = PartNames.Contains(selected) ? selected : PartNames.FirstOrDefault() ?? ""; } private void ValidatePart(string name) { RefreshPartNames(); - if (!PartNames.Contains(name)) throw new InvalidOperationException("目标零件不在当前配方的零件列表中,请先维护并保存零件列表,再重新导入视频"); + if (!PartNames.Contains(name)) throw new InvalidOperationException("请先维护并保存当前配方的零件列表,再选择要标注的零件"); } public int ExtractStride { get; set; } = 1; public int MaxFrames { get; set; } = 600; @@ -165,6 +187,7 @@ public sealed class MainViewModel : BindableBase public DelegateCommand ApproveCommand { get; } public DelegateCommand ApproveAllCommand { get; } public DelegateCommand AbsentCommand { get; } + public DelegateCommand EmptyFrameCommand { get; } public DelegateCommand ExcludeCommand { get; } public DelegateCommand PreviousCommand { get; } public DelegateCommand NextCommand { get; } @@ -192,7 +215,7 @@ 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 () => { ValidateProjectTarget(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); }); + PropagateCommand = Command(async () => { ValidateProjectTarget(); ValidatePart(Label); await Run(new { action = "propagate", project = RequireProject().FilePath, label = Label, checkpoint = Checkpoint, config = SamConfig, device = Device }); }); ExportCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("export")); }); TrainCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("train")); }); OpenTrainingResultsCommand = Command(() => @@ -205,13 +228,20 @@ public sealed class MainViewModel : BindableBase SuggestCommand = Command(async () => { ValidateProjectTarget(); + ValidatePart(Label); 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()); + label = Label, endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke()); }); ApproveCommand = Command(() => Update("reviewed")); ApproveAllCommand = Command(ApproveAll); AbsentCommand = Command(() => Update("absent")); + EmptyFrameCommand = Command(() => + { + if (SelectedFrame == null) return; + if (SelectedFrame.Objects.Any(o => o.Box != null)) throw new InvalidOperationException("该帧仍有零件框,请先逐个标记“当前零件不在”,再确认整帧无零件"); + SelectedFrame.Status = "absent"; RequireProject().Save(); Refresh(); + }); ExcludeCommand = Command(() => Update("excluded")); PreviousCommand = Command(() => Move(-1)); NextCommand = Command(() => Move(1)); @@ -243,8 +273,9 @@ public sealed class MainViewModel : BindableBase private void ValidateProjectTarget() { var project = RequireProject(); - ValidatePart(Label); - if (project.Name != Label) throw new InvalidOperationException("标注项目的目标零件已被修改,请重新打开正确的项目;目标零件不能在标注或训练时切换"); + RefreshPartNames(); + var missing = project.Frames.SelectMany(f => f.Objects).Select(o => o.Label).Distinct().Where(n => !PartNames.Contains(n)).ToArray(); + if (missing.Length > 0) throw new InvalidOperationException("标注中引用了零件列表外的名称:" + string.Join("、", missing)); if (string.IsNullOrWhiteSpace(project.RecipeDirectory)) { project.RecipeDirectory = RecipeDirectoryFor(RecipeName); @@ -261,11 +292,6 @@ public sealed class MainViewModel : BindableBase { var recipeDirectory = RecipeDirectoryFor(RecipeName); 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 @@ -274,13 +300,12 @@ public sealed class MainViewModel : BindableBase 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 = videoPath, output, name = target, recipeName = RecipeName, recipeDirectory, stride = ExtractStride, maxFrames = MaxFrames }, reload: false)) + if (await Run(new { action = "extract", video = videoPath, output, name = Path.GetFileNameWithoutExtension(videoPath), 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; } + finally { IsImporting = false; RefreshPartNames(); } } public void Load(string path, int index = 0) { @@ -295,8 +320,9 @@ public sealed class MainViewModel : BindableBase if (!Recipes.Contains(_project.RecipeName)) Recipes.Add(_project.RecipeName); RecipeName = _project.RecipeName; } - Label = _project.Name; RaisePropertyChanged(nameof(Label)); RefreshPartNames(); + var preferred = _project.Frames.SelectMany(f => f.Objects).FirstOrDefault()?.Label; + if (string.IsNullOrEmpty(Label) && preferred != null && PartNames.Contains(preferred)) Label = preferred; _selected = null; Frames.Clear(); foreach (var frame in _project.Frames) Frames.Add(frame); SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)]; @@ -309,34 +335,49 @@ public sealed class MainViewModel : BindableBase if (IsBusy || SelectedFrame == null || _project == null) return; try { - _project.ValidateBox(box); SelectedFrame.Box = box; SelectedFrame.Prompt = true; - SelectedFrame.Status = "reviewed"; _project.Save(); Refresh(); - Status = "关键帧已保存;可再选其他角度画框,或开始自动标注"; + ValidatePart(Label); _project.ValidateBox(box); + var item = GetOrCreateObject(); item.Box = box; item.Prompt = true; item.Status = "reviewed"; + SelectedFrame.Status = "auto"; _project.Save(); Refresh(); + Status = "当前零件关键帧已保存;可切换零件继续画框,全部标好后确认整帧,或传播当前零件"; } catch (Exception e) { Status = e.Message; } } private void Update(string status) { if (SelectedFrame == null) return; - if (status == "reviewed" && SelectedFrame.Box == null) throw new InvalidOperationException("该帧没有目标框,请画框或标记无目标"); - SelectedFrame.Status = status; - if (status != "reviewed") { SelectedFrame.Box = null; SelectedFrame.Prompt = false; } + if (status == "reviewed") + { + if (!SelectedFrame.Objects.Any(o => o.Box != null)) throw new InvalidOperationException("该帧没有零件框,请画框或确认整帧无零件"); + if (SelectedFrame.Objects.Any(o => o.Box == null && o.Status != "absent")) throw new InvalidOperationException("该帧仍有未确认的空框,请为对应零件补框,或标记“当前零件不在”"); + foreach (var item in SelectedFrame.Objects.Where(o => o.Box != null)) { RequireProject().ValidateBox(item.Box!); item.Status = "reviewed"; } + SelectedFrame.Status = "reviewed"; + } + else if (status == "absent") + { + ValidatePart(Label); var item = GetOrCreateObject(); item.Box = null; item.Prompt = false; item.Status = "absent"; + SelectedFrame.Status = "auto"; + } + else SelectedFrame.Status = status; RequireProject().Save(); Refresh(); Status = "当前帧已保存"; } private void ApproveAll() { var project = RequireProject(); - var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Box != null).ToList(); + var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Objects.Any(o => o.Box != null)).ToList(); + if (pending.Any(f => f.Objects.Any(o => o.Box == null && o.Status != "absent"))) + throw new InvalidOperationException("待复核帧中仍有自动标注未找到的零件,请补框或标记“当前零件不在”后再复核"); // Validate the whole batch before changing any annotation status. - foreach (var frame in pending) project.ValidateBox(frame.Box!); + foreach (var item in pending.SelectMany(f => f.Objects).Where(o => o.Box != null)) project.ValidateBox(item.Box!); if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; } var selectedIndex = SelectedFrame?.Index ?? 0; - foreach (var frame in pending) frame.Status = "reviewed"; + var previous = pending.SelectMany(f => f.Objects).Select(o => (Item: o, o.Status)).ToArray(); + foreach (var frame in pending) { frame.Status = "reviewed"; foreach (var item in frame.Objects.Where(o => o.Box != null)) item.Status = "reviewed"; } try { project.Save(); } catch { foreach (var frame in pending) frame.Status = "auto"; + foreach (var item in previous) item.Item.Status = item.Status; throw; } Load(project.FilePath, selectedIndex); @@ -349,6 +390,13 @@ public sealed class MainViewModel : BindableBase var index = Frames.IndexOf(frame); Frames[index] = frame; SelectedFrame = frame; RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); RaisePropertyChanged(nameof(Summary)); + RaisePropertyChanged(nameof(CurrentAnnotations)); RaisePropertyChanged(nameof(AnnotationSummary)); + } + private ObjectAnnotation GetOrCreateObject() + { + var item = CurrentObject; + if (item != null) return item; + item = new ObjectAnnotation { Label = Label }; SelectedFrame!.Objects.Add(item); return item; } private void Move(int delta) { @@ -391,7 +439,7 @@ public sealed class MainViewModel : BindableBase IsBusy = true; Progress = 0; Status = "任务运行中…"; _cancellation = new CancellationTokenSource(); _completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0; + var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0; var label = Label; var elapsed = Stopwatch.StartNew(); var outcome = "失败"; try @@ -438,6 +486,7 @@ public sealed class MainViewModel : BindableBase try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); } } _cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false; + RefreshPartNames(); if (PartNames.Contains(label)) Label = label; _completion.TrySetResult(); } } diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml index 8021a69..0e20f6f 100644 --- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml +++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml @@ -56,15 +56,16 @@ - +