导入训练视频前选择目标零件并锁定项目目标

This commit is contained in:
tfarcraw 2026-11-10 11:29:20 +08:00
parent 691e3c6e9b
commit d92214b6f4
7 changed files with 192 additions and 36 deletions

View File

@ -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` 指向最新完整版本,重新应用配方即可加载。

View File

@ -0,0 +1,32 @@
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 } }
}
};
}
}

View File

@ -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<FrameAnnotation> 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<string> 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<IReadOnlyList<string>, Task<string?>>? SelectImportPartAsync { get; set; }
public Func<Task<string?>>? 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<Task> 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 = "设置文件不可读,已使用默认配置"; }

View File

@ -18,7 +18,7 @@
<TextBlock Grid.Column="1" Text="{Binding RecipeName}" Foreground="{StaticResource Dim}" TextTrimming="CharacterEllipsis" MaxWidth="360" ToolTip.Tip="{Binding RecipeFolder}" />
</Grid>
<WrapPanel>
<Button Content="相机与录像" Click="OpenCameraClicked" />
<Button Content="相机与录像" Click="OpenCameraClicked" IsEnabled="{Binding IsIdle}" />
<Button Content="导入视频" Command="{Binding ImportCommand}" />
<Button Content="打开项目" Command="{Binding OpenCommand}" />
<Button Content="保存参数" Command="{Binding SaveParametersCommand}" ToolTip.Tip="保存标注、训练和设置参数,下次打开时自动恢复" />
@ -76,8 +76,9 @@
<TextBlock Text="所属配方" />
<TextBlock Text="{Binding RecipeName}" FontWeight="Bold" />
<TextBlock Text="每个视频标注一个零件;零件名称在本窗口的“零件列表”中维护,修改后请先保存配方。" Classes="Hint" />
<TextBlock Text="零件类别名称" Margin="0,12,0,0" />
<ComboBox x:Name="TrainingPartPicker" ItemsSource="{Binding PartNames}" SelectedItem="{Binding Label, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" HorizontalAlignment="Stretch" />
<TextBlock Text="目标零件(导入时锁定)" Margin="0,12,0,0" />
<TextBlock x:Name="TrainingTargetPart" Text="{Binding Label}" FontWeight="Bold" />
<TextBlock Text="导入视频时选择目标零件;当前项目的标注和训练不能切换目标。" Classes="Hint" />
<TextBlock Text="抽帧间隔(原视频帧数)" />
<TextBox Text="{Binding ExtractStride, Mode=TwoWay}" />
<TextBlock Text="最多导入帧数" />

View File

@ -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<CameraInfo?> _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<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,
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;

View File

@ -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<ImportPartDialog>().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<ImportPartDialog>().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<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));
}
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");
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);
}
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");
}
finally {trainer.SelectImportVideoAsync=selectVideo;trainer.SelectImportPartAsync=selectPart;}
}
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;

View File

@ -85,9 +85,10 @@ internal static class Program
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 trainingPicker = training.FindControl<ComboBox>("TrainingPartPicker")!;
trainingPicker.SelectedItem = "螺丝";
Check(trainer.Label == "螺丝", "Training category is selected through a ComboBox");
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");
trainer.RefreshPartNames();
Check(trainer.Label == "支架", "Catalog refresh cannot switch the locked target");
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));