视频标注支持同帧多零件和按零件独立自动传播
This commit is contained in:
parent
95efb21e85
commit
7cb38481bb
@ -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<BitmapSource?> SourceProperty=AvaloniaProperty.Register<AnnotationCanvas,BitmapSource?>(nameof(Source));
|
||||
public static readonly StyledProperty<double[]?> BoxProperty=AvaloniaProperty.Register<AnnotationCanvas,double[]?>(nameof(Box));
|
||||
public static readonly StyledProperty<string> TargetNameProperty=AvaloniaProperty.Register<AnnotationCanvas,string>(nameof(TargetName), "");
|
||||
public static readonly StyledProperty<IReadOnlyList<ObjectAnnotation>?> AnnotationsProperty=AvaloniaProperty.Register<AnnotationCanvas,IReadOnlyList<ObjectAnnotation>?>(nameof(Annotations));
|
||||
public IReadOnlyList<ObjectAnnotation>? 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<AnnotationCanvas>(SourceProperty,BoxProperty,TargetNameProperty);}
|
||||
static AnnotationCanvas(){AffectsRender<AnnotationCanvas>(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);
|
||||
|
||||
@ -1,32 +0,0 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
|
||||
/// <summary>每次导入显式选择目标,确认前不修改当前标注项目。</summary>
|
||||
public sealed class ImportPartDialog : Window
|
||||
{
|
||||
public ImportPartDialog(IReadOnlyList<string> 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 } }
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -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<ObjectAnnotation> 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<string> PartNames { get; } = [];
|
||||
private string _label = "";
|
||||
public string Label { get => _label; private set => SetProperty(ref _label, value); }
|
||||
public Func<IReadOnlyList<string>, Task<string?>>? 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<Task<string?>>? SelectImportVideoAsync { get; set; }
|
||||
public void RefreshPartNames()
|
||||
{
|
||||
PartNames.Clear();
|
||||
var selected = Label;
|
||||
IReadOnlyList<string> 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();
|
||||
}
|
||||
}
|
||||
|
||||
@ -56,15 +56,16 @@
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding FrameInfo}" Margin="0,0,0,10" TextWrapping="Wrap" />
|
||||
<Border Grid.Row="1" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" ClipToBounds="True" Classes="panel">
|
||||
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" TargetName="{Binding Label}" IsEnabled="{Binding IsIdle}" />
|
||||
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" Annotations="{Binding CurrentAnnotations}" TargetName="{Binding Label}" IsEnabled="{Binding IsIdle}" />
|
||||
</Border>
|
||||
<WrapPanel Grid.Row="2" Margin="0,12,0,0">
|
||||
<Button Content="适应窗口" Click="ResetImageViewClicked" />
|
||||
<Button Content="← 上一帧" Command="{Binding PreviousCommand}" />
|
||||
<Button Content="下一帧 →" Command="{Binding NextCommand}" />
|
||||
<Button Content="确认当前框" Command="{Binding ApproveCommand}" />
|
||||
<Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip.Tip="确认本项目中所有带目标框的待复核帧,并立即保存" />
|
||||
<Button Content="无目标" Command="{Binding AbsentCommand}" />
|
||||
<Button Content="确认整帧" Command="{Binding ApproveCommand}" ToolTip.Tip="确认这一帧所有可见零件均已标全,允许导出训练" />
|
||||
<Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip.Tip="请先检查所有待复核帧的可见零件是否标全;此操作会将它们全部确认为完整训练样本" />
|
||||
<Button Content="当前零件不在" Command="{Binding AbsentCommand}" />
|
||||
<Button Content="整帧无零件" Command="{Binding EmptyFrameCommand}" />
|
||||
<Button Content="排除此帧" Command="{Binding ExcludeCommand}" />
|
||||
</WrapPanel>
|
||||
<TextBlock Grid.Row="3" Text="滚轮缩放,右键拖动图像,左键画框或修正并自动保存。← → 切帧,Enter 确认并进入下一帧。" Classes="Hint" TextWrapping="Wrap" />
|
||||
@ -75,20 +76,22 @@
|
||||
<StackPanel>
|
||||
<TextBlock Text="所属配方" />
|
||||
<TextBlock Text="{Binding RecipeName}" FontWeight="Bold" />
|
||||
<TextBlock Text="每个视频标注一个零件;零件名称在本窗口的“零件列表”中维护,修改后请先保存配方。" Classes="Hint" />
|
||||
<TextBlock Text="目标零件(导入时锁定)" Margin="0,12,0,0" />
|
||||
<TextBlock x:Name="TrainingTargetPart" Text="{Binding Label}" FontWeight="Bold" />
|
||||
<TextBlock Text="导入视频时选择目标零件;当前项目的标注和训练不能切换目标。" Classes="Hint" />
|
||||
<TextBlock Text="一个视频可标注多种零件;零件名称在“零件列表”中维护,修改后请先保存配方。" Classes="Hint" />
|
||||
<TextBlock Text="当前标注零件" Margin="0,12,0,0" />
|
||||
<ComboBox x:Name="TrainingTargetPart" ItemsSource="{Binding PartNames}" SelectedItem="{Binding Label, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
||||
<TextBlock Text="切换零件后画框,每种零件每帧保存一个框;其他零件的框会保留,允许重叠和包含。" Classes="Hint" />
|
||||
<TextBlock Text="本帧已标零件" FontWeight="Bold" Margin="0,8,0,4" />
|
||||
<TextBlock Text="{Binding AnnotationSummary}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="抽帧间隔(原视频帧数)" />
|
||||
<TextBox Text="{Binding ExtractStride, Mode=TwoWay}" />
|
||||
<TextBlock Text="最多导入帧数" />
|
||||
<TextBox Text="{Binding MaxFrames, Mode=TwoWay}" />
|
||||
<TextBlock Text="默认最多600帧;长视频会自动增大间隔覆盖全片。快速旋转建议分成短片导入。" Classes="Hint" />
|
||||
<TextBlock Text="02 画框并自动传播" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,10,0,8" />
|
||||
<Button Content="开始自动标注" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}" />
|
||||
<TextBlock Text="先在清晰帧画一个框。旋转幅度大时,可在多个角度补框后再运行。传播保留已复核帧。" Classes="Hint" />
|
||||
<Button Content="自动标注当前零件" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}" />
|
||||
<TextBlock Text="先为当前零件补充清晰关键帧,再自动传播;仅更新当前零件,保留其他零件以及当前零件已手工确认的框。多个零件分别运行,遮挡或装配处请补框复核。" Classes="Hint" />
|
||||
<TextBlock Text="03 人工复核" FontWeight="Bold" Foreground="{StaticResource Accent}" />
|
||||
<TextBlock Text="逐帧确认目标框;框偏了直接重画。无目标用于负样本,排除帧不参与训练。只导出已复核数据。" Classes="Hint" />
|
||||
<TextBlock Text="所有可见零件均标全后点“确认整帧”;仅画框或自动传播不会将整帧加入训练。当前零件不在只清除该零件,整帧无零件用于负样本,排除帧不参与训练。" Classes="Hint" />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
|
||||
@ -13,7 +13,6 @@ 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<CameraInfo?> _selectedCameraProvider;
|
||||
@ -26,7 +25,6 @@ public partial class TrainingPage : UserControl
|
||||
_canOpenCamera=canOpenCamera??(()=>true);
|
||||
Canvas.BoxDrawn+=model.DrawBox;
|
||||
model.ReadApiKey=()=>ApiKey.Text??"";
|
||||
model.SelectImportPartAsync=SelectImportPartAsync;
|
||||
model.SelectImportVideoAsync=SelectImportVideoAsync;
|
||||
AttachedToVisualTree+=(_,_)=>
|
||||
{
|
||||
@ -46,7 +44,7 @@ public partial class TrainingPage : UserControl
|
||||
if(model.IsBusy || TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement() is TextBox)return;
|
||||
if(e.Key==Key.Left){model.PreviousCommand.Execute();e.Handled=true;}
|
||||
else if(e.Key==Key.Right){model.NextCommand.Execute();e.Handled=true;}
|
||||
else if(e.Key==Key.Enter && model.SelectedFrame?.Box!=null)
|
||||
else if(e.Key==Key.Enter && model.CurrentAnnotations.Count>0)
|
||||
{model.ApproveCommand.Execute();model.NextCommand.Execute();e.Handled=true;}
|
||||
},RoutingStrategies.Tunnel);
|
||||
}
|
||||
@ -63,24 +61,17 @@ public partial class TrainingPage : UserControl
|
||||
}
|
||||
public async Task ShutdownAsync()
|
||||
{
|
||||
_closing=true;_importPartDialog?.Close(null);
|
||||
_closing=true;
|
||||
await _model.StopAsync();
|
||||
if(_cameraWindow is { } cameraWindow){await cameraWindow.Model.ShutdownAsync();cameraWindow.Close();}
|
||||
}
|
||||
private async Task<string?> SelectImportPartAsync(IReadOnlyList<string> parts)
|
||||
{
|
||||
if(_closing || TopLevel.GetTopLevel(this) is not Window owner)return null;
|
||||
var dialog=new ImportPartDialog(parts);_importPartDialog=dialog;
|
||||
try{return await dialog.ShowDialog<string?>(owner);}
|
||||
finally{_importPartDialog=null;}
|
||||
}
|
||||
private async Task<string?> 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,
|
||||
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]
|
||||
});
|
||||
|
||||
@ -47,7 +47,14 @@ public static class PartCatalog
|
||||
foreach (var path in paths)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (doc.RootElement.TryGetProperty("name", out var name) && name.GetString() is { Length: > 0 } value)
|
||||
if (doc.RootElement.TryGetProperty("annotationVersion", out var version) && version.GetInt32() >= 2)
|
||||
{
|
||||
foreach (var frame in doc.RootElement.GetProperty("frames").EnumerateArray())
|
||||
if (frame.TryGetProperty("objects", out var objects))
|
||||
foreach (var item in objects.EnumerateArray())
|
||||
if (item.TryGetProperty("label", out var label) && label.GetString() is { Length: > 0 } part) yield return part;
|
||||
}
|
||||
else if (doc.RootElement.TryGetProperty("name", out var name) && name.GetString() is { Length: > 0 } value)
|
||||
yield return value;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,19 +3,29 @@ using System.Text.Json.Serialization;
|
||||
|
||||
namespace SopHelper.Engine.Training;
|
||||
|
||||
public sealed class ObjectAnnotation
|
||||
{
|
||||
public string Label { get; set; } = "";
|
||||
public double[]? Box { get; set; }
|
||||
public string Status { get; set; } = "unlabeled";
|
||||
public bool Prompt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class FrameAnnotation
|
||||
{
|
||||
public int Index { get; set; }
|
||||
public int SourceIndex { get; set; }
|
||||
public string Image { get; set; } = "";
|
||||
public double[]? Box { get; set; }
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public double[]? Box { get; set; }
|
||||
public string Status { get; set; } = "unlabeled";
|
||||
public bool Prompt { get; set; }
|
||||
[JsonIgnore] public string Display => $"{Index + 1:0000} · {Status switch { "reviewed" => "已复核", "auto" => "待复核", "absent" => "无目标", "excluded" => "已排除", _ => "未标注" }}{(Prompt ? " · 关键帧" : "")}";
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool Prompt { get; set; }
|
||||
public List<ObjectAnnotation> Objects { get; set; } = [];
|
||||
[JsonIgnore] public string Display => $"{Index + 1:0000} · {Status switch { "reviewed" => "整帧已复核", "auto" => "自动待复核", "absent" => "整帧无零件", "excluded" => "已排除", _ => "待整帧复核" }} · {Objects.Count(o => o.Box != null)} 框";
|
||||
}
|
||||
|
||||
public sealed class TrainingProject
|
||||
{
|
||||
public int AnnotationVersion { get; set; } = 1;
|
||||
public string Name { get; set; } = "零件";
|
||||
public string RecipeName { get; set; } = "";
|
||||
public string RecipeDirectory { get; set; } = "";
|
||||
@ -41,11 +51,18 @@ public sealed class TrainingProject
|
||||
throw new InvalidDataException("项目没有有效的视频帧");
|
||||
foreach (var frame in project.Frames)
|
||||
{
|
||||
if (project.AnnotationVersion < 2 && frame.Objects.Count == 0 && (frame.Box != null || frame.Status is "reviewed" or "absent"))
|
||||
frame.Objects.Add(new ObjectAnnotation { Label = project.Name, Box = frame.Box, Status = frame.Status, Prompt = frame.Prompt });
|
||||
frame.Box = null; frame.Prompt = false;
|
||||
var root = Path.GetFullPath(project.DirectoryPath) + Path.DirectorySeparatorChar;
|
||||
if (!Path.GetFullPath(Path.Combine(root, frame.Image)).StartsWith(root, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidDataException("帧路径超出项目目录");
|
||||
if (frame.Box is { } box) project.ValidateBox(box);
|
||||
if (frame.Objects.Any(o => string.IsNullOrWhiteSpace(o.Label)) || frame.Objects.Select(o => o.Label).Distinct().Count() != frame.Objects.Count)
|
||||
throw new InvalidDataException("同一帧的零件名称不能为空或重复");
|
||||
foreach (var item in frame.Objects)
|
||||
if (item.Box is { } box) project.ValidateBox(box);
|
||||
}
|
||||
project.AnnotationVersion = 2;
|
||||
return project;
|
||||
}
|
||||
public void ValidateBox(double[] box)
|
||||
|
||||
@ -240,12 +240,12 @@ internal static class Smoke
|
||||
Check(trainingView.GetVisualDescendants().OfType<AnnotationCanvas>().Single().TargetName==trainer.Label,"Annotation canvas uses the imported project's locked target name");
|
||||
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");
|
||||
outerTabs.SelectedIndex=0;outerTabs.SelectedIndex=6;await Task.Delay(80);
|
||||
Check(ReferenceEquals(trainer,trainingEditorVm.TrainingView!.Model)&&trainer.SelectedFrame?.Box is { Length:4 },"Switching editor tabs preserves annotation state");
|
||||
Check(ReferenceEquals(trainer,trainingEditorVm.TrainingView!.Model)&&trainer.CurrentBox is { Length:4 },"Switching editor tabs preserves annotation state");
|
||||
try{trainer.RecipeName="另一配方";throw new Exception("Locked recipe accepted a switch");}catch(InvalidOperationException){}
|
||||
Check(trainer.RecipeName==savedRecipe&&trainer.Project is not null,"Embedded training cannot switch away from the edited recipe");
|
||||
var foreign=new TrainingProject{FilePath=Path.Combine(temporary,"foreign.json"),Name="其他零件",RecipeName="另一配方",Width=100,Height=100,Frames=[new FrameAnnotation{Index=0,Image="frame.png"}]};foreign.Save();
|
||||
try{trainer.Load(foreign.FilePath);throw new Exception("Foreign recipe project was accepted");}catch(InvalidOperationException){}
|
||||
Check(trainer.SelectedFrame?.Box is {Length:4},"Opening another recipe's project is rejected without altering current annotations");
|
||||
Check(trainer.CurrentBox is {Length:4},"Opening another recipe's project is rejected without altering current annotations");
|
||||
await CheckTrainingLayout(trainingDialog,trainingView,trainer);
|
||||
Save(trainingDialog,"training-project");
|
||||
trainer.DoctorCommand.Execute();
|
||||
@ -269,11 +269,12 @@ internal static class Smoke
|
||||
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");
|
||||
var closingTrainer=editorVm.TrainingView!.Model;
|
||||
closingTrainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);
|
||||
closingTrainer.ImportCommand.Execute();await Task.Delay(40);
|
||||
Check(closingTrainer.IsImporting&&lifetime.Windows.OfType<ImportPartDialog>().Any(),"Import part picker is open before closing the editor");
|
||||
Check(!closingTrainer.IsImporting,"Cancelling video selection finishes import without a part picker");
|
||||
dialog.Close();
|
||||
for(var i=0;i<100&&dialog.IsVisible;i++)await Task.Delay(20);
|
||||
Check(!dialog.IsVisible&&!closingTrainer.IsImporting&&!lifetime.Windows.OfType<ImportPartDialog>().Any(),"Closing the editor cancels the part picker without starting import");
|
||||
Check(!dialog.IsVisible&&!closingTrainer.IsImporting,"Closing the editor after cancelled import releases resources");
|
||||
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();
|
||||
@ -334,66 +335,45 @@ internal static class Smoke
|
||||
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()
|
||||
var selectVideo=trainer.SelectImportVideoAsync;
|
||||
async Task Import()
|
||||
{
|
||||
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<ImportPartDialog> Picker()
|
||||
{
|
||||
trainer.ImportCommand.Execute();await Task.Delay(40);
|
||||
return lifetime.Windows.OfType<ImportPartDialog>().Single();
|
||||
}
|
||||
void Confirm(ImportPartDialog dialog,string name)
|
||||
{
|
||||
dialog.GetVisualDescendants().OfType<ComboBox>().Single().SelectedItem=name;
|
||||
var button=dialog.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="下一步:选择视频");
|
||||
Check(button.IsEnabled,"Choosing an existing part enables video selection");
|
||||
button.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
trainer.ImportCommand.Execute();
|
||||
for(var i=0;i<400&&(trainer.IsBusy||trainer.IsImporting);i++)await Task.Delay(20);
|
||||
Check(!trainer.IsBusy&&!trainer.IsImporting,"Video import finishes without a part picker");
|
||||
}
|
||||
try
|
||||
{
|
||||
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(null);};
|
||||
var picker=await Picker();
|
||||
var partPicker=picker.GetVisualDescendants().OfType<ComboBox>().Single();
|
||||
Check(partPicker.SelectedItem is null&&partPicker.Items.Cast<string>().SequenceEqual(config.Sop.Parts),"Import first requires explicit selection from the recipe part catalog");
|
||||
Check(!picker.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="下一步:选择视频").IsEnabled,"Import cannot advance without a target part");
|
||||
Save(picker,"import-target-part");picker.Close(null);await WaitImport();
|
||||
Check(videoCalls==0&&trainer.Project is null&&trainer.Label=="","Cancelling part selection never opens the video picker or changes the current project");
|
||||
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
||||
Check(videoCalls==1&&trainer.Project is null&&trainer.Label=="","Cancelling video selection does not assign a target");
|
||||
var videoPath=Path.Combine(trainer.Root,"import-target-test.avi");
|
||||
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);await Import();
|
||||
Check(trainer.Project is null,"Cancelling the video picker leaves the current project unchanged");
|
||||
var videoPath=Path.Combine(trainer.Root,"multi-part-test.avi");
|
||||
using(var writer=new VideoWriter(videoPath,FourCC.MJPG,10,new OpenCvSharp.Size(64,48)))
|
||||
{
|
||||
Check(writer.IsOpened(),"Import fixture video opens for writing");
|
||||
using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));for(var i=0;i<20;i++)writer.Write(frame);
|
||||
using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));for(var i=0;i<30;i++)writer.Write(frame);
|
||||
}
|
||||
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(videoPath);};
|
||||
picker=await Picker();Confirm(picker,"支架");await WaitImport();
|
||||
Check(trainer.Project is {Name:"支架"}&&trainer.Label=="支架"&&trainer.Frames.Count>0,"Real video extraction stores and locks the selected part");
|
||||
var first=trainer.Project!.FilePath;var before=File.ReadAllBytes(first);
|
||||
Check(view.FindControl<TextBlock>("TrainingTargetPart")!.Text=="支架"&&!view.GetVisualDescendants().OfType<ComboBox>().Any(c=>ReferenceEquals(c.ItemsSource,trainer.PartNames)),"Annotation page displays the locked target without a category selector");
|
||||
var calls=videoCalls;picker=await Picker();picker.Close(null);await WaitImport();
|
||||
Check(videoCalls==calls&&trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves the current project and target");
|
||||
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(null);};
|
||||
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
||||
Check(trainer.Label=="支架"&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a different target's video picker does not relabel current annotations");
|
||||
trainer.Project.Name="螺丝";trainer.ExportCommand.Execute();
|
||||
Check(trainer.Status.Contains("不能")&&SopHelper.Engine.Training.TrainingProject.Load(first).Name=="支架"&&!trainer.IsBusy,"Training/export reject target changes instead of rewriting project metadata");
|
||||
trainer.Load(first);Check(trainer.Label=="支架","Reopening a project restores its original locked target");
|
||||
trainer.SelectImportPartAsync=_=>Task.FromResult<string?>("未知零件");calls=videoCalls;
|
||||
trainer.ImportCommand.Execute();await WaitImport();
|
||||
Check(videoCalls==calls&&trainer.Status.Contains("零件列表")&&trainer.Label=="支架","Unknown import targets are rejected before opening the video picker");
|
||||
trainer.SelectImportPartAsync=selectPart;
|
||||
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(videoPath);
|
||||
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
||||
Check(trainer.Project is {Name:"螺丝"}&&trainer.Label=="螺丝"&&trainer.Project.FilePath!=first&&TrainingProject.Load(first).Name=="支架","Each newly imported video gets its own fixed target without altering older projects");
|
||||
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(videoPath);await Import();
|
||||
Check(trainer.Project is {AnnotationVersion:2}&&trainer.Frames.Count>0,"Video import creates an unassigned multi-part project");
|
||||
var selector=view.FindControl<ComboBox>("TrainingTargetPart")!;
|
||||
selector.SelectedItem="支架";trainer.DrawBox([1,1,60,44]);
|
||||
selector.SelectedItem="螺丝";trainer.DrawBox([10,10,25,25]);
|
||||
Check(trainer.SelectedFrame!.Objects.Count==2&&trainer.CurrentAnnotations.Count==2&&trainer.SelectedFrame.Status=="auto","A nested second part preserves the first box and requires whole-frame review");
|
||||
Check(view.GetVisualDescendants().OfType<AnnotationCanvas>().Single().Annotations!.Count==2,"Annotation canvas receives both part boxes at once");
|
||||
trainer.ApproveCommand.Execute();var first=trainer.Project!.FilePath;
|
||||
var saved=TrainingProject.Load(first);
|
||||
Check(saved.Frames[0].Status=="reviewed"&&saved.Frames[0].Objects.All(o=>o.Status=="reviewed"),"Whole-frame review saves both part labels");
|
||||
Save(owner,"multi-part-annotation");
|
||||
trainer.AbsentCommand.Execute();
|
||||
Check(trainer.SelectedFrame.Objects.Single(o=>o.Label=="支架").Box!=null&&trainer.CurrentBox==null,"Marking the selected part absent preserves other part boxes");
|
||||
trainer.Label="支架";trainer.DrawBox([2,2,58,43]);
|
||||
Check(trainer.SelectedFrame.Objects.Count==2&&trainer.SelectedFrame.Objects.Single(o=>o.Label=="螺丝").Status=="absent","Redrawing updates only the selected part");
|
||||
trainer.SelectedFrame=trainer.Frames[1];trainer.Label="螺丝";trainer.DrawBox([10,10,25,25]);trainer.Label="支架";
|
||||
trainer.Load(first,1);Check(trainer.SelectedFrame!.Objects.Single().Label=="螺丝","Reopening preserves per-frame part identities without relabeling");
|
||||
var before=File.ReadAllBytes(first);trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(null);await Import();
|
||||
Check(trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves every existing annotation");
|
||||
}
|
||||
finally {trainer.SelectImportVideoAsync=selectVideo;trainer.SelectImportPartAsync=selectPart;}
|
||||
finally{trainer.SelectImportVideoAsync=selectVideo;}
|
||||
}
|
||||
|
||||
private static async Task CheckTrainingLayout(Window window,TrainingPage view,SopHelper.Training.MainViewModel trainer)
|
||||
{
|
||||
var width=window.Width;var logs=trainer.Logs;var status=trainer.Status;
|
||||
|
||||
@ -82,22 +82,25 @@ internal static class Program
|
||||
window.Close(); vm.OnDialogClosed();
|
||||
|
||||
var projectDirectory = Path.Combine(directory, "parts", "video"); Directory.CreateDirectory(projectDirectory);
|
||||
var project = new TrainingProject { FilePath = Path.Combine(projectDirectory, "project.json"), Name = "支架", RecipeName = "装配", RecipeDirectory = directory, Width = 100, Height = 100, Frames = [new FrameAnnotation { Index = 0, Image = "frame.png" }] };
|
||||
var project = new TrainingProject { AnnotationVersion = 2, FilePath = Path.Combine(projectDirectory, "project.json"), Name = "装配视频", RecipeName = "装配", RecipeDirectory = directory, Width = 100, Height = 100, Frames = [new FrameAnnotation { Index = 0, Image = "frame.png", Objects = [new() {Label="支架", Box=[0,0,90,90]}, new() {Label="螺丝", Box=[20,20,30,30]}] }] };
|
||||
project.Save();
|
||||
Check(PartCatalog.ProjectNames(directory).Contains("支架") && PartCatalog.ProjectNames(directory).Contains("螺丝") && !PartCatalog.ProjectNames(directory).Contains("装配视频"), "Multi-part annotation references use object labels instead of the video title");
|
||||
var trainer = new MainViewModel(new WorkerClient()); trainer.RecipeName = "装配";
|
||||
Check(trainer.PartNames.SequenceEqual(saved.Sop.Parts!), "Training offers the same catalog");
|
||||
trainer.Load(project.FilePath);
|
||||
Check(trainer.Label == "支架", "Loading a project selects its existing catalog part");
|
||||
var training = new TrainingPage(trainer, null); var trainingWindow = new Window { Content = training, Width = 1180, Height = 820 }; trainingWindow.Show(); trainingWindow.UpdateLayout();
|
||||
var targetPart = training.FindControl<TextBlock>("TrainingTargetPart")!;
|
||||
Check(targetPart.Text == "支架" && training.FindControl<ComboBox>("TrainingPartPicker") is null, "Training target is displayed read-only after loading a project");
|
||||
var targetPart = training.FindControl<ComboBox>("TrainingTargetPart")!;
|
||||
Check(targetPart.SelectedItem?.ToString() == "支架", "Training offers a part selector after loading a project");
|
||||
targetPart.SelectedItem = "螺丝";
|
||||
Check(trainer.Label == "螺丝", "Annotation part can switch within a video");
|
||||
trainer.RefreshPartNames();
|
||||
Check(trainer.Label == "支架", "Catalog refresh cannot switch the locked target");
|
||||
Check(trainer.Label == "螺丝", "Catalog refresh preserves the selected annotation part");
|
||||
trainingWindow.Close();
|
||||
var other = new SopConfig(); other.Sop.Name = "另一配方"; other.Sop.Parts = ["外壳"];
|
||||
Directory.CreateDirectory(storage.DirectoryFor(other.Sop.Name)); SopConfigLoader.Save(other, storage.ConfigPath(other.Sop.Name));
|
||||
trainer.RecipeName = other.Sop.Name;
|
||||
Check(trainer.PartNames.SequenceEqual(new[] { "外壳" }) && trainer.Label == "" && trainer.Project is null, "Switching recipes clears the previous project and selection");
|
||||
Check(trainer.PartNames.SequenceEqual(new[] { "外壳" }) && trainer.Label == "外壳" && trainer.Project is null, "Switching recipes clears the previous project and selects an available part");
|
||||
var changed = SopConfigLoader.Load(storage.ConfigPath("装配")); changed.Sop.Parts!.Remove("支架"); changed.Sop.Steps.Clear();
|
||||
try { PartCatalog.Validate(changed, directory); throw new Exception("Annotation reference was ignored"); }
|
||||
catch (InvalidDataException error) { Check(error.Message.Contains("支架"), "Parts referenced only by annotation projects cannot be removed"); }
|
||||
|
||||
@ -10,7 +10,7 @@ try
|
||||
Frames = [new FrameAnnotation { Image = "frames/000000.jpg", Box = [10, 20, 100, 200], Status = "reviewed", Prompt = true }] };
|
||||
project.Save();
|
||||
var loaded = TrainingProject.Load(project.FilePath);
|
||||
if (loaded.Name != project.Name || !loaded.Frames[0].Prompt || loaded.Frames[0].Box![2] != 100) throw new Exception("Project round trip failed");
|
||||
if (loaded.Name != project.Name || !loaded.Frames[0].Objects[0].Prompt || loaded.Frames[0].Objects[0].Box![2] != 100 || loaded.AnnotationVersion != 2) throw new Exception("Legacy project migration failed");
|
||||
foreach (var invalid in new double[][] { [-1,0,10,10], [0,0,0,10], [0,0,641,10], [double.NaN,0,1,1] })
|
||||
{
|
||||
try { loaded.ValidateBox(invalid); throw new Exception("Invalid box accepted"); }
|
||||
|
||||
@ -58,18 +58,18 @@ with tempfile.TemporaryDirectory(prefix="sophelper-worker-") as directory:
|
||||
assert all((project / frame["image"]).is_file() for frame in data["frames"])
|
||||
print("PASS: actual video import, frame extraction, Unicode and space paths", flush=True)
|
||||
|
||||
data["frames"][0].update(box=[40, 60, 120, 140], status="reviewed", prompt=True)
|
||||
data["frames"][0].update(objects=[{"label":"测试零件", "box":[40,60,120,140], "status":"reviewed", "prompt":True}], status="reviewed")
|
||||
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
if options.sam2:
|
||||
run({"action": "propagate", "project": str(project_file), "device": "cpu"})
|
||||
run({"action": "propagate", "project": str(project_file), "label":"测试零件", "device": "cpu"})
|
||||
data = json.loads(project_file.read_text(encoding="utf-8"))
|
||||
assert data["frames"][0]["status"] == "reviewed" and data["frames"][0]["prompt"]
|
||||
assert data["frames"][0]["status"] == "reviewed" and data["frames"][0]["objects"][0]["prompt"]
|
||||
assert all(frame["status"] == "auto" for frame in data["frames"][1:])
|
||||
assert any(frame["box"] for frame in data["frames"][1:]), "SAM2 produced no tracked boxes"
|
||||
assert any(o.get("box") for frame in data["frames"][1:] for o in frame["objects"]), "SAM2 produced no tracked boxes"
|
||||
print("PASS: SAM2 model load and propagation preserve the reviewed seed", flush=True)
|
||||
|
||||
for index, frame in enumerate(data["frames"]):
|
||||
frame.update(box=[40 + index * 3, 60, 120 + index * 3, 140], status="reviewed")
|
||||
frame.update(objects=[{"label":"测试零件", "box":[40+index*3,60,120+index*3,140], "status":"reviewed", "prompt":index==0}], status="reviewed")
|
||||
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||
events = run({"action": "export", "project": str(project_file), "every": 1})
|
||||
output = Path(next(event["output"] for event in events if "output" in event))
|
||||
|
||||
@ -78,9 +78,74 @@ class DatasetTests(unittest.TestCase):
|
||||
with patch.dict(worker.os.environ, {"PARTTRAINER_API_KEY": "local-test-secret"}), patch.object(worker.urllib.request, "build_opener", return_value=opener):
|
||||
worker.suggest({"project": str(self.project), "index": 0, "endpoint": "http://localhost:9999/v1", "apiModel": "test-vision"})
|
||||
result = worker.read_json(self.project)["frames"][0]
|
||||
self.assertEqual(result["box"], [10,16,80,72])
|
||||
self.assertEqual(result["objects"][0]["box"], [10,16,80,72])
|
||||
self.assertEqual(result["status"], "auto")
|
||||
self.assertTrue(result["prompt"])
|
||||
self.assertTrue(result["objects"][0]["prompt"])
|
||||
|
||||
def multi_part(self):
|
||||
self.data["annotationVersion"] = 2
|
||||
for frame in self.data["frames"]:
|
||||
frame.pop("box", None)
|
||||
frame.pop("prompt", None)
|
||||
frame["objects"] = [
|
||||
{"label": "盒子", "box": [5, 5, 95, 75], "status": "reviewed", "prompt": False},
|
||||
{"label": "连接器", "box": [20, 20, 40, 40], "status": "reviewed", "prompt": False}]
|
||||
self.save()
|
||||
|
||||
def test_nested_parts_export_as_two_labels_in_same_image(self):
|
||||
self.multi_part()
|
||||
dataset = worker.export_dataset({"project": str(self.project), "every": 5}).parent
|
||||
manifest = worker.read_json(dataset / "manifest.json")
|
||||
self.assertEqual(manifest["classes"], ["盒子", "连接器"])
|
||||
labels = (dataset / "labels/train/0000_000000.txt").read_text().splitlines()
|
||||
self.assertEqual(len(labels), 2)
|
||||
self.assertEqual([row.split()[0] for row in labels], ["0", "1"])
|
||||
self.assertEqual([float(x) for x in labels[1].split()[1:]], [0.3, 0.375, 0.2, 0.25])
|
||||
|
||||
def test_unconfirmed_frames_not_exported_and_pending_objects_rejected(self):
|
||||
self.multi_part()
|
||||
self.data["frames"][0]["status"] = "auto"
|
||||
self.save()
|
||||
dataset = worker.export_dataset({"project": str(self.project), "every": 5}).parent
|
||||
self.assertFalse((dataset / "labels/train/0000_000000.txt").exists())
|
||||
self.data["frames"][5]["objects"][1]["status"] = "auto"
|
||||
self.save()
|
||||
with self.assertRaises(ValueError):
|
||||
worker.export_dataset({"project": str(self.project), "every": 5})
|
||||
|
||||
def test_selected_part_propagation_preserves_other_labels_and_manual_work(self):
|
||||
import copy
|
||||
import types
|
||||
import torch
|
||||
self.multi_part()
|
||||
for frame in self.data["frames"]:
|
||||
frame["objects"] = frame["objects"][:1]
|
||||
self.data["frames"][0]["objects"].append({"label": "连接器", "box": [20,20,40,40], "prompt": True, "status": "reviewed"})
|
||||
manual = {"label": "连接器", "box": [10,10,15,15], "prompt": True, "status": "reviewed"}
|
||||
self.data["frames"][2]["objects"].append(copy.deepcopy(manual))
|
||||
self.data["frames"][3]["objects"].append({"label": "连接器", "box": None, "prompt": False, "status": "absent"})
|
||||
self.data["frames"][4]["status"] = "excluded"
|
||||
original_boxes = copy.deepcopy([f["objects"][0] for f in self.data["frames"]])
|
||||
self.save()
|
||||
class Predictor:
|
||||
def init_state(inner, *args, **kwargs): return {}
|
||||
def add_new_points_or_box(inner, *args, **kwargs): pass
|
||||
def propagate_in_video(inner, *args, **kwargs):
|
||||
for index in range(60):
|
||||
mask = torch.full((1,1,80,100), -1.0)
|
||||
mask[:,:,22:42,24:44] = 1
|
||||
yield index, [1], mask
|
||||
module = types.ModuleType("sam2.build_sam")
|
||||
module.build_sam2_video_predictor = lambda *args, **kwargs: Predictor()
|
||||
with patch.dict(worker.sys.modules, {"sam2.build_sam": module}), patch.object(worker, "emit"):
|
||||
worker.propagate({"project": str(self.project), "label": "连接器", "device": "cpu", "checkpoint": "mock.pt"})
|
||||
result = worker.read_json(self.project)
|
||||
self.assertEqual([f["objects"][0] for f in result["frames"]], original_boxes)
|
||||
self.assertEqual(worker.object_for(result["frames"][1], "连接器")["box"], [24,22,44,42])
|
||||
self.assertEqual(worker.object_for(result["frames"][2], "连接器"), manual)
|
||||
self.assertEqual(worker.object_for(result["frames"][3], "连接器")["status"], "absent")
|
||||
self.assertIsNone(worker.object_for(result["frames"][4], "连接器"))
|
||||
self.assertEqual(result["frames"][1]["status"], "auto")
|
||||
self.assertNotIn("local-test-secret", self.project.read_text(encoding="utf-8"))
|
||||
|
||||
def test_import_stores_video_in_recipe(self):
|
||||
|
||||
100
tools/worker.py
100
tools/worker.py
@ -63,15 +63,38 @@ def load_project(path):
|
||||
data = read_json(path)
|
||||
if data["width"] <= 0 or data["height"] <= 0 or not data["frames"]:
|
||||
raise ValueError("项目没有有效的视频帧")
|
||||
legacy = int(data.get("annotationVersion", 1)) < 2
|
||||
for frame in data["frames"]:
|
||||
image = (path.parent / frame["image"]).resolve()
|
||||
if not image.is_relative_to(path.parent):
|
||||
raise ValueError("帧路径超出项目目录")
|
||||
if frame.get("box") is not None:
|
||||
validate_box(frame["box"], data["width"], data["height"])
|
||||
if legacy and not frame.get("objects"):
|
||||
frame["objects"] = [{"label": data["name"], "box": frame.get("box"), "status": frame.get("status", "unlabeled"), "prompt": frame.get("prompt", False)}]
|
||||
frame.pop("box", None)
|
||||
frame.pop("prompt", None)
|
||||
objects = frame.setdefault("objects", [])
|
||||
names = [o.get("label") for o in objects]
|
||||
if any(not isinstance(n, str) or not n.strip() for n in names) or len(set(names)) != len(names):
|
||||
raise ValueError("同一帧的零件名称不能为空或重复")
|
||||
for item in objects:
|
||||
if item.get("box") is not None:
|
||||
validate_box(item["box"], data["width"], data["height"])
|
||||
data["annotationVersion"] = 2
|
||||
return path, data
|
||||
|
||||
|
||||
def project_labels(data):
|
||||
return list(dict.fromkeys(o["label"] for f in data["frames"] for o in f.get("objects", [])))
|
||||
|
||||
|
||||
def object_for(frame, label, create=False):
|
||||
item = next((o for o in frame.get("objects", []) if o["label"] == label), None)
|
||||
if item is None and create:
|
||||
item = {"label": label, "box": None, "status": "unlabeled", "prompt": False}
|
||||
frame.setdefault("objects", []).append(item)
|
||||
return item
|
||||
|
||||
|
||||
def doctor(request):
|
||||
modules = {m: importlib.util.find_spec(m) is not None for m in ("cv2", "numpy", "torch", "ultralytics", "sam2", "onnx")}
|
||||
emit("Python " + sys.version.split()[0], modules=modules)
|
||||
@ -131,7 +154,7 @@ def extract(request):
|
||||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
# Bound RAM/disk use and preserve coverage across the entire source video.
|
||||
stride = max(stride, math.ceil(total / limit)) if total > 0 else stride
|
||||
data = {"name": request.get("name", "零件"), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
|
||||
data = {"annotationVersion": 2, "name": request.get("name", video.stem), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
|
||||
"width": 0, "height": 0, "stride": stride, "frames": [],
|
||||
"recipeName": request.get("recipeName", ""), "recipeDirectory": request.get("recipeDirectory", "")}
|
||||
index = 0
|
||||
@ -152,7 +175,7 @@ def extract(request):
|
||||
raise RuntimeError("帧编码失败")
|
||||
buffer.tofile(str(staging / name))
|
||||
data["frames"].append({"index": number, "sourceIndex": index, "image": name,
|
||||
"box": None, "status": "unlabeled", "prompt": False})
|
||||
"objects": [], "status": "unlabeled"})
|
||||
if number % 25 == 0:
|
||||
emit(f"已抽取 {number + 1} 帧", progress=min(0.99, index / max(total, 1)))
|
||||
index += 1
|
||||
@ -175,7 +198,11 @@ def propagate(request):
|
||||
import torch
|
||||
from sam2.build_sam import build_sam2_video_predictor
|
||||
path, data = load_project(request["project"])
|
||||
prompts = [f for f in data["frames"] if f.get("prompt") and f.get("box") and f["status"] == "reviewed"]
|
||||
label = request.get("label") or (project_labels(data)[0] if len(project_labels(data)) == 1 else "")
|
||||
if not label:
|
||||
raise ValueError("请先选择要自动标注的零件")
|
||||
prompts = [(f, object_for(f, label)) for f in data["frames"] if f.get("status") not in ("excluded", "absent")]
|
||||
prompts = [(f, o) for f, o in prompts if o and o.get("prompt") and o.get("box") and o["status"] == "reviewed"]
|
||||
if not prompts:
|
||||
raise ValueError("请至少手动画一个关键帧标注框")
|
||||
device = request.get("device", "auto")
|
||||
@ -194,28 +221,31 @@ def propagate(request):
|
||||
context = torch.autocast("cuda", dtype=torch.bfloat16) if device.startswith("cuda") and torch.cuda.is_bf16_supported() else nullcontext()
|
||||
with torch.inference_mode(), context:
|
||||
state = predictor.init_state(str(path.parent / "frames"), offload_video_to_cpu=True, offload_state_to_cpu=True)
|
||||
for frame in prompts:
|
||||
predictor.add_new_points_or_box(state, frame_idx=frame["index"], obj_id=1, box=np.array(frame["box"], dtype=np.float32))
|
||||
start = min(f["index"] for f in prompts)
|
||||
for frame, item in prompts:
|
||||
predictor.add_new_points_or_box(state, frame_idx=frame["index"], obj_id=1, box=np.array(item["box"], dtype=np.float32))
|
||||
start = min(f["index"] for f, _ in prompts)
|
||||
# Run both directions so a seed drawn in the middle covers earlier frames too.
|
||||
directions = [False, True] if start > 0 else [False]
|
||||
count = 0
|
||||
for reverse in directions:
|
||||
for index, ids, logits in predictor.propagate_in_video(state, start_frame_idx=start, reverse=reverse):
|
||||
frame = data["frames"][index]
|
||||
if frame["status"] in ("reviewed", "absent", "excluded"):
|
||||
item = object_for(frame, label)
|
||||
if frame["status"] in ("absent", "excluded") or (item and item["status"] in ("reviewed", "absent")):
|
||||
continue
|
||||
mask = (logits[0, 0] > 0).cpu().numpy()
|
||||
ys, xs = np.where(mask)
|
||||
frame["box"] = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None
|
||||
item = object_for(frame, label, create=True)
|
||||
item["box"] = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None
|
||||
frame["status"] = "auto" # Empty predictions still require review, never become negative labels automatically.
|
||||
frame["prompt"] = False
|
||||
item["status"] = "auto"
|
||||
item["prompt"] = False
|
||||
count += 1
|
||||
if count % 20 == 0:
|
||||
save_json(path, data)
|
||||
emit(f"传播帧 {index + 1}/{len(data['frames'])}" + (" · 未找到目标" if not len(xs) else ""), progress=count / len(data["frames"]))
|
||||
save_json(path, data)
|
||||
emit("SAM2 传播完成,请复核自动标注", progress=1)
|
||||
emit(f"{label} 的 SAM2 传播完成,其他零件标注已保留;请复核整帧", progress=1)
|
||||
|
||||
|
||||
def default_checkpoint():
|
||||
@ -254,7 +284,7 @@ def recipe_context(request):
|
||||
path, data = load_project(request["project"])
|
||||
directory = data.get("recipeDirectory", "")
|
||||
if not directory:
|
||||
return path.parent, [(path, data)], [data["name"]]
|
||||
return path.parent, [(path, data)], project_labels(data)
|
||||
root = Path(directory).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
registry = root / "recipe-training.json"
|
||||
@ -281,19 +311,21 @@ def recipe_context(request):
|
||||
continue
|
||||
projects.append(load_project(item))
|
||||
for source, project in projects:
|
||||
if catalog is not None and project["name"] not in catalog:
|
||||
raise ValueError(f"零件“{project['name']}”不在配方零件列表中,请先在配方编辑中维护")
|
||||
names = project_labels(project)
|
||||
if catalog is not None and any(name not in catalog for name in names):
|
||||
raise ValueError(f"零件“{'、'.join(n for n in names if n not in catalog)}”不在配方零件列表中,请先在配方编辑中维护")
|
||||
previous = labels.get(str(source))
|
||||
# A corrected name keeps its class ID when it is the sole video for that part.
|
||||
if catalog is None and previous and previous != project["name"] and previous in state["classes"] and project["name"] not in state["classes"]:
|
||||
others = [p["name"] for other, p in projects if other != source]
|
||||
if catalog is None and len(names) == 1 and isinstance(previous, str) and previous != names[0] and previous in state["classes"] and names[0] not in state["classes"]:
|
||||
others = [n for other, p in projects if other != source for n in project_labels(p)]
|
||||
if previous not in others:
|
||||
state["classes"][state["classes"].index(previous)] = project["name"]
|
||||
labels[str(source)] = project["name"]
|
||||
state["classes"][state["classes"].index(previous)] = names[0]
|
||||
labels[str(source)] = names[0] if len(names) == 1 else names
|
||||
if Path(project.get("recipeDirectory", "")).resolve() != root:
|
||||
raise ValueError(f"零件项目的配方归属不一致:{source}")
|
||||
if project["name"] not in state["classes"]:
|
||||
state["classes"].append(project["name"])
|
||||
for name in names:
|
||||
if name not in state["classes"]:
|
||||
state["classes"].append(name)
|
||||
if missing:
|
||||
archived = state.setdefault("missingProjects", [])
|
||||
for item in missing:
|
||||
@ -321,12 +353,12 @@ def export_dataset(request):
|
||||
for path, data in projects:
|
||||
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
|
||||
reason = None
|
||||
if any(f["status"] == "reviewed" and not f.get("box") for f in selected):
|
||||
reason = "已复核的正样本缺少标注框"
|
||||
if any(f["status"] == "reviewed" and (not any(o.get("box") for o in f["objects"]) or any(o.get("status") not in ("reviewed", "absent") or (o.get("status") == "reviewed" and not o.get("box")) for o in f["objects"])) for f in selected):
|
||||
reason = "整帧复核不完整:存在未确认的零件或缺少标注框"
|
||||
boundary = int(len(data["frames"]) * (1 - ratio))
|
||||
training = [f for f in selected if f["index"] < boundary - every and f["index"] % every == 0]
|
||||
validation = [f for f in selected if f["index"] >= boundary and f["index"] % every == 0]
|
||||
if len(training) < 2 or not validation or not any(f.get("box") for f in training) or not any(f.get("box") for f in validation):
|
||||
if len(training) < 2 or not validation or not any(o.get("box") for f in training for o in f["objects"]) or not any(o.get("box") for f in validation for o in f["objects"]):
|
||||
reason = reason or "复核样本不足,训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。请补充复核或减小训练抽样间隔"
|
||||
if any(not (path.parent / f["image"]).is_file() for f in training + validation):
|
||||
reason = reason or "训练样本的图像文件不存在"
|
||||
@ -348,7 +380,7 @@ def export_dataset(request):
|
||||
output.mkdir(parents=True)
|
||||
manifest = []
|
||||
for number, (path, data, training, validation) in enumerate(samples):
|
||||
class_id = classes.index(data["name"])
|
||||
class_ids = [classes.index(name) for name in project_labels(data)]
|
||||
for split, frames in (("train", training), ("val", validation)):
|
||||
(output / "images" / split).mkdir(parents=True, exist_ok=True)
|
||||
(output / "labels" / split).mkdir(parents=True, exist_ok=True)
|
||||
@ -356,12 +388,14 @@ def export_dataset(request):
|
||||
stem = f"{number:04d}_{frame['index']:06d}"
|
||||
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
|
||||
label = ""
|
||||
if frame.get("box") is not None and frame["status"] != "absent":
|
||||
x1, y1, x2, y2 = validate_box(frame["box"], data["width"], data["height"])
|
||||
label = str(class_id) + " " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
|
||||
for item in frame["objects"]:
|
||||
if item.get("box") is None or frame["status"] == "absent":
|
||||
continue
|
||||
x1, y1, x2, y2 = validate_box(item["box"], data["width"], data["height"])
|
||||
label += str(classes.index(item["label"])) + " " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
|
||||
(x2-x1)/data["width"], (y2-y1)/data["height"])) + "\n"
|
||||
(output / "labels" / split / (stem + ".txt")).write_text(label, encoding="utf-8")
|
||||
manifest.append({"project": str(path), "classId": class_id, "train": [f["index"] for f in training], "val": [f["index"] for f in validation]})
|
||||
manifest.append({"project": str(path), "classIds": class_ids, "classId": class_ids[0] if len(class_ids) == 1 else None, "train": [f["index"] for f in training], "val": [f["index"] for f in validation]})
|
||||
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n"
|
||||
yaml += "".join(f" {i}: {json.dumps(name, ensure_ascii=False)}\n" for i, name in enumerate(classes))
|
||||
(output / "data.yaml").write_text(yaml, encoding="utf-8")
|
||||
@ -471,6 +505,9 @@ def export_onnx(request):
|
||||
def suggest(request):
|
||||
path, data = load_project(request["project"])
|
||||
frame = data["frames"][int(request["index"])]
|
||||
label = request.get("label") or (project_labels(data)[0] if len(project_labels(data)) == 1 else "")
|
||||
if not label:
|
||||
raise ValueError("请先选择建议框对应的零件")
|
||||
key = os.environ.get("PARTTRAINER_API_KEY", "")
|
||||
if not key:
|
||||
raise ValueError("请填写视觉 API Key(只保存在当前进程内)")
|
||||
@ -489,7 +526,7 @@ def suggest(request):
|
||||
ok, buffer = cv2.imencode(".jpg", image)
|
||||
if not ok:
|
||||
raise ValueError("图像编码失败")
|
||||
prompt = f"Locate the single main object described as: {data['name']}. {request.get('description', '')} Return ONLY JSON: {{\"box\":[x1,y1,x2,y2]}} with coordinates normalized to 0..1. If absent, return {{\"box\":null}}."
|
||||
prompt = f"Locate the single main object described as: {label}. {request.get('description', '')} Return ONLY JSON: {{\"box\":[x1,y1,x2,y2]}} with coordinates normalized to 0..1. If absent, return {{\"box\":null}}."
|
||||
payload = {"model": request["apiModel"], "messages": [{"role": "user", "content": [
|
||||
{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(buffer).decode()}}]}], "max_tokens": 300}
|
||||
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
|
||||
@ -506,7 +543,8 @@ def suggest(request):
|
||||
validate_box(box, 1, 1)
|
||||
box = [box[0]*data["width"], box[1]*data["height"], box[2]*data["width"], box[3]*data["height"]]
|
||||
# This becomes a conditioning frame only after the user approves it.
|
||||
frame.update(box=box, status="auto", prompt=box is not None)
|
||||
object_for(frame, label, create=True).update(box=box, status="auto", prompt=box is not None)
|
||||
frame["status"] = "auto"
|
||||
save_json(path, data)
|
||||
emit("视觉模型已给出建议,请检查并确认当前帧", progress=1)
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user