集中维护配方零件列表并将引用字段改为选择
This commit is contained in:
parent
b5405d2f79
commit
6cdf51ee15
11
README.md
11
README.md
@ -44,11 +44,14 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
|
||||
## 操作流程
|
||||
|
||||
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
|
||||
2. 配方编辑器保留步骤、区域、全局设置、检测模型四个标签页;区域坐标使用原图像素。
|
||||
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型五个标签页;区域坐标使用原图像素。
|
||||
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
|
||||
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
|
||||
- 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。
|
||||
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
|
||||
- 在标注页选择所属配方,每个视频录入一个零件;录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。
|
||||
- 在标注页选择所属配方及已有零件类别,每个视频录入一个零件;录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。
|
||||
- 点击“训练并更新配方模型”,自动累计导出该配方所有已加入视频的复核数据,并使用上一版配方模型开始新训练;首次使用 `yolo11n.pt`。无需手选权重。
|
||||
- 同名零件的多个视频共用类别,新增零件自动分配类别编号。每个视频均需完成足够的训练段和末尾验证段复核。
|
||||
- 同名零件的多个视频共用类别,训练导出按零件列表顺序分配类别编号,并拒绝列表以外的项目类别。每个视频均需完成足够的训练段和末尾验证段复核。
|
||||
- 训练成功后自动将 `配方名.pt` 和 `配方名.onnx` 发布到同配方的 `models/训练版本/`;训练曲线和日志保存在 `runs`,数据集保存在 `datasets`。`latest-model.json` 指向最新完整版本,重新应用配方即可加载。
|
||||
- “保存参数”写入所选配方的 `training-settings.json`,切换配方时恢复各自参数。打开外部标注项目会将其复制到所属配方目录。
|
||||
4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。
|
||||
@ -78,6 +81,8 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
|
||||
|
||||
```powershell
|
||||
dotnet run --project tests/Avalonia.Smoke -c Release
|
||||
dotnet run --project tests/PartCatalog.Smoke -c Release
|
||||
python/python.exe tests/Training.Smoke/test_recipe_training.py
|
||||
dotnet run --project tests/OpenCv.Smoke -c Release
|
||||
dotnet run --project tests/HandednessSmoke -c Release
|
||||
dotnet run --project tests/Training.Smoke -c Release -- python/python.exe
|
||||
|
||||
@ -7,6 +7,7 @@ using SopHelper.Presentation.Threading;
|
||||
using SopHelper.Presentation;
|
||||
using SopHelper.Presentation.Imaging;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Engine.Sop;
|
||||
using Prism.Commands;
|
||||
using Prism.Mvvm;
|
||||
|
||||
@ -88,6 +89,7 @@ public sealed class MainViewModel : BindableBase
|
||||
Status="已切换配方,请导入视频或打开该配方的标注项目";
|
||||
}
|
||||
LoadTrainingResult();
|
||||
RefreshPartNames();
|
||||
RaisePropertyChanged(nameof(RecipeFolder));
|
||||
}
|
||||
}
|
||||
@ -98,7 +100,26 @@ public sealed class MainViewModel : BindableBase
|
||||
throw new ArgumentException("请先选择有效的配方");
|
||||
return DesktopPlatform.Recipes.DirectoryFor(name);
|
||||
}
|
||||
public string Label { get; set; } = "零件";
|
||||
public ObservableCollection<string> PartNames { get; } = [];
|
||||
private string _label = "";
|
||||
public string Label { get => _label; set => SetProperty(ref _label, value); }
|
||||
public void RefreshPartNames()
|
||||
{
|
||||
var selected = Label;
|
||||
PartNames.Clear();
|
||||
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);
|
||||
}
|
||||
Label = PartNames.Contains(selected) ? selected : "";
|
||||
}
|
||||
private void ValidatePartSelection()
|
||||
{
|
||||
RefreshPartNames();
|
||||
if (!PartNames.Contains(Label)) throw new InvalidOperationException("请先在配方编辑的“零件列表”中添加零件,再选择零件类别");
|
||||
}
|
||||
public int ExtractStride { get; set; } = 1;
|
||||
public int MaxFrames { get; set; } = 600;
|
||||
public string Checkpoint { get; set; } = "";
|
||||
@ -209,7 +230,7 @@ public sealed class MainViewModel : BindableBase
|
||||
private void SaveLabel()
|
||||
{
|
||||
var project = RequireProject();
|
||||
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
|
||||
ValidatePartSelection();
|
||||
if (string.IsNullOrWhiteSpace(project.RecipeDirectory))
|
||||
{
|
||||
project.RecipeDirectory = RecipeDirectoryFor(RecipeName);
|
||||
@ -227,7 +248,7 @@ public sealed class MainViewModel : BindableBase
|
||||
catch (Exception e) { Append("录像目录配置读取失败:" + e.Message); }
|
||||
if (await video.ShowDialogAsync() != true) return;
|
||||
var recipeDirectory = RecipeDirectoryFor(RecipeName);
|
||||
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
|
||||
ValidatePartSelection();
|
||||
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))
|
||||
Load(Path.Combine(output, "project.json"));
|
||||
@ -246,6 +267,7 @@ public sealed class MainViewModel : BindableBase
|
||||
RecipeName = _project.RecipeName;
|
||||
}
|
||||
Label = _project.Name; RaisePropertyChanged(nameof(Label));
|
||||
RefreshPartNames();
|
||||
_selected = null; Frames.Clear();
|
||||
foreach (var frame in _project.Frames) Frames.Add(frame);
|
||||
SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)];
|
||||
|
||||
@ -74,10 +74,10 @@
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
<TextBlock Text="所属配方" />
|
||||
<ComboBox ItemsSource="{Binding Recipes}" SelectedItem="{Binding RecipeName, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
<TextBlock Text="每个视频录入一个零件;新零件会加入当前配方。配方可在运行设置中创建。" Classes="Hint" />
|
||||
<ComboBox ItemsSource="{Binding Recipes}" SelectedItem="{Binding RecipeName, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" HorizontalAlignment="Stretch" />
|
||||
<TextBlock Text="每个视频标注一个零件;请先在运行设置的“配方编辑 → 零件列表”中维护零件。" Classes="Hint" />
|
||||
<TextBlock Text="零件类别名称" Margin="0,12,0,0" />
|
||||
<TextBox Text="{Binding Label, Mode=TwoWay}" />
|
||||
<ComboBox x:Name="TrainingPartPicker" ItemsSource="{Binding PartNames}" SelectedItem="{Binding Label, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" HorizontalAlignment="Stretch" />
|
||||
<TextBlock Text="抽帧间隔(原视频帧数)" />
|
||||
<TextBox Text="{Binding ExtractStride, Mode=TwoWay}" />
|
||||
<TextBlock Text="最多导入帧数" />
|
||||
|
||||
@ -28,6 +28,7 @@ public partial class TrainingPage : UserControl
|
||||
foreach (var recipe in sop.Recipes.Select(System.IO.Path.GetFileNameWithoutExtension).OfType<string>())
|
||||
if (!model.Recipes.Contains(recipe)) model.Recipes.Add(recipe);
|
||||
if (string.IsNullOrWhiteSpace(model.RecipeName)) model.RecipeName = System.IO.Path.GetFileNameWithoutExtension(sop.SelectedRecipe) ?? "";
|
||||
model.RefreshPartNames();
|
||||
}
|
||||
if(_host!=null || TopLevel.GetTopLevel(this) is not Window host)return;
|
||||
_host=host;host.Closing+=HostClosing;
|
||||
|
||||
@ -120,6 +120,24 @@ public class RecipeNode : EditorNode
|
||||
RemoveStepCommand = new DelegateCommand<StepNode>(node => { RemoveStep(node); Changed?.Invoke(); }, node => node is not null);
|
||||
MoveStepUpCommand = new DelegateCommand<StepNode>(node => { MoveStepUp(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id < node.Id));
|
||||
MoveStepDownCommand = new DelegateCommand<StepNode>(node => { MoveStepDown(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id > node.Id));
|
||||
Parts.Items.CollectionChanged += (_, e) =>
|
||||
{
|
||||
if (e.OldItems is not null) foreach (TextItem item in e.OldItems) item.PropertyChanged -= PartChanged;
|
||||
if (e.NewItems is not null) foreach (TextItem item in e.NewItems) item.PropertyChanged += PartChanged;
|
||||
RefreshPartNames();
|
||||
};
|
||||
}
|
||||
|
||||
public EditableList<TextItem> Parts { get; } = new() { Title = "零件列表" };
|
||||
public ObservableCollection<string> PartNames { get; } = [""];
|
||||
private void PartChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) => RefreshPartNames();
|
||||
private void RefreshPartNames()
|
||||
{
|
||||
// 替换选项时 SelectionConverter 保留当前引用,删除已引用名称由保存校验拦截。
|
||||
PartNames.Clear();
|
||||
PartNames.Add("");
|
||||
foreach (var name in Parts.Items.Select(p => p.Text).Where(n => !string.IsNullOrWhiteSpace(n)).Distinct()) PartNames.Add(name);
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>加区域</summary>
|
||||
@ -385,6 +403,8 @@ public class RecipeNode : EditorNode
|
||||
};
|
||||
|
||||
node.Settings.CopyFrom(config.Sop.Settings);
|
||||
foreach (var name in SopHelper.Engine.Training.PartCatalog.Read(config, null))
|
||||
node.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = node.Parts.RemoveCommand });
|
||||
|
||||
foreach (var (key, def) in config.Sop.Regions)
|
||||
{
|
||||
@ -437,6 +457,7 @@ public class RecipeNode : EditorNode
|
||||
config.Sop.Name = Name;
|
||||
config.Sop.Version = Version;
|
||||
config.Sop.Description = Description;
|
||||
config.Sop.Parts = Parts.Items.Select(p => p.Text).ToList();
|
||||
|
||||
Settings.CopyTo(config.Sop.Settings);
|
||||
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<ComboBox ItemsSource="{Binding DataContext.Recipe.PartNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Text, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
||||
<Button Grid.Column="1" Margin="6,0,0,0" Classes="Mini" Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
@ -168,7 +168,7 @@
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<TextBlock Grid.Column="2" Text="目标类别" Margin="16,0,8,0" Classes="Field" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Detection.TargetObject, Mode=TwoWay}" />
|
||||
<ComboBox x:Name="TargetPartPicker" Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.PartNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.TargetObject, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
||||
</Grid>
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
@ -384,6 +384,25 @@
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</TabItem>
|
||||
<TabItem Header="零件列表">
|
||||
<ScrollViewer Margin="10">
|
||||
<StackPanel DataContext="{Binding Recipe.Parts}">
|
||||
<TextBlock Text="在此统一维护本配方的零件名称,标注和步骤中只选择已有零件。" Margin="0,0,0,8" TextWrapping="Wrap" />
|
||||
<TextBlock Text="已被步骤或标注项目引用的名称不能删除或改名;修改列表不会改变已训练模型的类别。" Margin="0,0,0,8" TextWrapping="Wrap" />
|
||||
<Button Content="添加零件" Command="{Binding AddCommand}" HorizontalAlignment="Left" Margin="0,0,0,8" />
|
||||
<ItemsControl ItemsSource="{Binding Items}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid ColumnDefinitions="*,Auto" Classes="Row">
|
||||
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Button Grid.Column="1" Content="删" Margin="6,0,0,0" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" Classes="Mini" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</TabItem>
|
||||
<TabItem Header="检测模型">
|
||||
<StackPanel x:Name="ModelSettings" Margin="10" DataContext="{Binding Recipe}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
@ -411,10 +430,12 @@
|
||||
</Grid>
|
||||
<StackPanel DataContext="{Binding Classes}">
|
||||
<TextBlock FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" Classes="Title" />
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,6">
|
||||
<Button Content="加类别" Command="{Binding AddCommand}" Classes="Mini" />
|
||||
</StackPanel>
|
||||
<ItemsControl ItemsSource="{Binding Items}" />
|
||||
<TextBlock Text="类别由模型确定,仅供查看。零件名称请在“零件列表”中维护。" TextWrapping="Wrap" Margin="0,0,0,6" />
|
||||
<ItemsControl ItemsSource="{Binding Items}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate><TextBlock Text="{Binding Text}" /></DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
@ -122,6 +122,10 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
|
||||
|
||||
Recipe = RecipeNode.From(config, fileName, _isNew);
|
||||
var partNames = PartCatalog.Read(config, string.IsNullOrEmpty(_path) ? null : Path.GetDirectoryName(_path));
|
||||
Recipe.Parts.Items.Clear();
|
||||
foreach (var name in partNames)
|
||||
Recipe.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = Recipe.Parts.RemoveCommand });
|
||||
Recipe.Changed += RefreshWarnings;
|
||||
|
||||
RefreshWarnings();
|
||||
@ -268,6 +272,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
var config = Recipe.ToConfig();
|
||||
PartCatalog.Validate(config, Path.GetDirectoryName(path));
|
||||
if (config.Sop.Model is { Path.Length: > 0 } model)
|
||||
{
|
||||
var source = Path.GetFullPath(model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
|
||||
@ -327,6 +332,8 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
Warnings.Clear();
|
||||
|
||||
var config = Recipe.ToConfig();
|
||||
try { PartCatalog.Validate(config, string.IsNullOrEmpty(_path) ? null : Path.GetDirectoryName(_path)); }
|
||||
catch (InvalidDataException error) { Warnings.Add(error.Message); }
|
||||
SopConfigLoader.Validate(config);
|
||||
|
||||
foreach (var warning in config.Warnings) Warnings.Add(warning);
|
||||
|
||||
@ -29,6 +29,10 @@ public class SopBody
|
||||
/// <summary>说明</summary>
|
||||
public string Description { get; set; } = "";
|
||||
|
||||
/// <summary>本配方统一维护的零件名称;null 表示旧配方尚未迁移。</summary>
|
||||
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
|
||||
public List<string>? Parts { get; set; }
|
||||
|
||||
/// <summary>全局设置</summary>
|
||||
public SopSettings Settings { get; set; } = new();
|
||||
|
||||
|
||||
67
src/SopHelper.CrossPlatform.Engine/Training/PartCatalog.cs
Normal file
67
src/SopHelper.CrossPlatform.Engine/Training/PartCatalog.cs
Normal file
@ -0,0 +1,67 @@
|
||||
using System.Text.Json;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Engine.Training;
|
||||
|
||||
/// <summary>零件列表由配方维护。模型类别与训练注册表只作为旧配方的迁移来源。</summary>
|
||||
public static class PartCatalog
|
||||
{
|
||||
public static IEnumerable<string> References(SopConfig config) => config.Sop.Steps.SelectMany(step =>
|
||||
step.MustKeep.Concat(step.RequiredObjects).Append(step.Detection?.TargetObject ?? ""))
|
||||
.Where(name => !string.IsNullOrWhiteSpace(name));
|
||||
|
||||
public static IReadOnlyList<string> Read(SopConfig config, string? directory)
|
||||
{
|
||||
if (config.Sop.Parts is { } parts) return parts.ToArray();
|
||||
var names = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(directory) && Directory.Exists(directory))
|
||||
{
|
||||
foreach (var filename in new[] { "latest-model.json", "recipe-training.json" })
|
||||
{
|
||||
var path = Path.Combine(directory, filename);
|
||||
if (!File.Exists(path)) continue;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
if (doc.RootElement.TryGetProperty("classes", out var classes))
|
||||
names.AddRange(classes.EnumerateArray().Select(c => c.GetString() ?? ""));
|
||||
}
|
||||
names.AddRange(ProjectNames(directory));
|
||||
}
|
||||
names.AddRange(config.Sop.Model?.Classes ?? []);
|
||||
names.AddRange(References(config));
|
||||
return names.Where(n => !string.IsNullOrWhiteSpace(n)).Distinct(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
public static IEnumerable<string> ProjectNames(string directory)
|
||||
{
|
||||
var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var partsDirectory = Path.Combine(directory, "parts");
|
||||
if (Directory.Exists(partsDirectory))
|
||||
paths.UnionWith(Directory.GetFiles(partsDirectory, "project.json", SearchOption.AllDirectories));
|
||||
var registry = Path.Combine(directory, "recipe-training.json");
|
||||
if (File.Exists(registry))
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(registry));
|
||||
if (doc.RootElement.TryGetProperty("projects", out var projects))
|
||||
paths.UnionWith(projects.EnumerateArray().Select(p => p.GetString()).OfType<string>().Where(File.Exists));
|
||||
}
|
||||
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)
|
||||
yield return value;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Validate(SopConfig config, string? directory)
|
||||
{
|
||||
var parts = config.Sop.Parts ?? throw new InvalidDataException("请先维护零件列表");
|
||||
if (parts.Any(n => string.IsNullOrWhiteSpace(n) || n != n.Trim()))
|
||||
throw new InvalidDataException("零件名称不能为空,首尾不能有空格");
|
||||
if (parts.Distinct(StringComparer.Ordinal).Count() != parts.Count)
|
||||
throw new InvalidDataException("零件名称不能重复");
|
||||
var missing = References(config).Concat(string.IsNullOrWhiteSpace(directory) ? [] : ProjectNames(directory))
|
||||
.Distinct(StringComparer.Ordinal).Where(n => !parts.Contains(n, StringComparer.Ordinal)).ToArray();
|
||||
if (missing.Length > 0)
|
||||
throw new InvalidDataException("以下零件仍被步骤或标注项目引用,不能删除或改名:" + string.Join("、", missing));
|
||||
}
|
||||
}
|
||||
@ -215,7 +215,7 @@ internal static class Smoke
|
||||
var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
|
||||
var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);
|
||||
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();
|
||||
Check(tabs.ItemCount==4,"All four original recipe tabs retained");
|
||||
Check(tabs.ItemCount==5,"Recipe tabs include the central parts catalog");
|
||||
for(var i=0;i<tabs.ItemCount;i++){tabs.SelectedIndex=i;await Task.Delay(80);Save(dialog,"recipe-"+i);}
|
||||
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");
|
||||
|
||||
7
tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj
Normal file
7
tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj
Normal file
@ -0,0 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" />
|
||||
<PackageReference Include="Avalonia.Headless" Version="12.1.5" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
115
tests/PartCatalog.Smoke/Program.cs
Normal file
115
tests/PartCatalog.Smoke/Program.cs
Normal file
@ -0,0 +1,115 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Markup.Xaml.Styling;
|
||||
using Avalonia.Themes.Fluent;
|
||||
using Avalonia.VisualTree;
|
||||
using Prism.Dialogs;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
using System.Text.Json;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "part-catalog-smoke-" + Guid.NewGuid().ToString("N"));
|
||||
var previous = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
|
||||
try
|
||||
{
|
||||
AppBuilder.Configure<Application>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).SetupWithoutStarting();
|
||||
Application.Current!.Styles.Add(new FluentTheme());
|
||||
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
|
||||
Run(new RecipeWorkspace(root));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previous);
|
||||
// Test-owned temporary root, never application data.
|
||||
if (Path.GetFileName(root).StartsWith("part-catalog-smoke-") && Directory.Exists(root)) Directory.Delete(root, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Run(RecipeWorkspace storage)
|
||||
{
|
||||
var directory = storage.DirectoryFor("装配");
|
||||
Directory.CreateDirectory(directory);
|
||||
var config = new SopConfig(); config.Sop.Name = "装配";
|
||||
config.Sop.Model = new ModelDef { Classes = ["螺丝", "支架"] };
|
||||
config.Sop.Steps = [new StepDef { Id = 1, Name = "检查", Detection = new StepCondition { Method = ConditionMethod.ObjectPresent, TargetObject = "螺丝" }, MustKeep = ["支架"], RequiredObjects = ["螺丝"] }];
|
||||
File.WriteAllText(Path.Combine(directory, "latest-model.json"), JsonSerializer.Serialize(new { classes = new[] { "支架", "螺丝" } }));
|
||||
Check(PartCatalog.Read(config, directory).SequenceEqual(new[] { "支架", "螺丝" }), "Legacy migration preserves trained class order and names");
|
||||
SopConfigLoader.Save(config, storage.ConfigPath("装配"));
|
||||
var vm = Open(storage, "装配");
|
||||
Check(vm.Recipe.PartNames.SequenceEqual(new[] { "", "支架", "螺丝" }), "Editor migrates the legacy catalog with an optional empty selection");
|
||||
var window = new Window { Width = 1180, Height = 820 };
|
||||
var editor = new RecipeEditor { DataContext = vm }; window.Content = editor; window.Show(); window.UpdateLayout();
|
||||
var pickers = editor.GetVisualDescendants().OfType<ComboBox>().Where(c => ReferenceEquals(c.ItemsSource, vm.Recipe.PartNames)).ToArray();
|
||||
Check(pickers.Length == 3, "Target, must-keep and required-object fields use catalog pickers");
|
||||
var target = editor.FindControl<ComboBox>("TargetPartPicker")!;
|
||||
target.SelectedItem = "支架";
|
||||
Check(vm.Recipe.SelectedStep!.Detection!.TargetObject == "支架", "Target selection writes back");
|
||||
vm.Recipe.Parts.AddCommand.Execute(); var added = vm.Recipe.Parts.Items.Last(); added.Text = "垫片";
|
||||
window.UpdateLayout();
|
||||
Check(target.Items.Contains("垫片") && vm.Recipe.SelectedStep.Detection.TargetObject == "支架", "Catalog edits refresh choices without erasing references");
|
||||
target.SelectedItem = "";
|
||||
Check(vm.Recipe.SelectedStep.Detection.TargetObject == "", "Explicit empty selection clears an optional target");
|
||||
target.SelectedItem = "螺丝";
|
||||
vm.SaveCommand.Execute();
|
||||
var saved = SopConfigLoader.Load(storage.ConfigPath("装配"));
|
||||
Check(saved.Sop.Parts!.SequenceEqual(new[] { "支架", "螺丝", "垫片" }), "Central catalog persists with the recipe");
|
||||
Check(saved.Sop.Model!.Classes.SequenceEqual(new[] { "螺丝", "支架" }), "Editing the catalog never renumbers model output labels");
|
||||
var before = File.ReadAllBytes(storage.ConfigPath("装配"));
|
||||
vm.Recipe.Parts.Items[0].Text = ""; vm.SaveCommand.Execute();
|
||||
Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Empty catalog names cannot be saved");
|
||||
vm.Recipe.Parts.Items[0].Text = "螺丝"; vm.SaveCommand.Execute();
|
||||
Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Duplicate catalog names cannot be saved");
|
||||
vm.Recipe.Parts.Items[0].Text = "支架";
|
||||
vm.Recipe.Parts.RemoveCommand.Execute(vm.Recipe.Parts.Items[0]); vm.SaveCommand.Execute();
|
||||
Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Referenced parts cannot be deleted");
|
||||
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single();
|
||||
tabs.SelectedIndex = 4; window.UpdateLayout();
|
||||
var modelClasses = editor.GetVisualDescendants().OfType<ItemsControl>().Single(c => ReferenceEquals(c.ItemsSource, vm.Recipe.Model.Classes.Items));
|
||||
Check(!modelClasses.GetVisualDescendants().OfType<TextBox>().Any() && !modelClasses.GetVisualDescendants().OfType<ComboBox>().Any(), "Model label mapping is read-only");
|
||||
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" }] };
|
||||
project.Save();
|
||||
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 trainingPicker = training.FindControl<ComboBox>("TrainingPartPicker")!;
|
||||
trainingPicker.SelectedItem = "螺丝";
|
||||
Check(trainer.Label == "螺丝", "Training category is selected through a ComboBox");
|
||||
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");
|
||||
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"); }
|
||||
var reopened = Open(storage, "装配");
|
||||
Check(reopened.Recipe.Parts.Items.Select(i => i.Text).SequenceEqual(saved.Sop.Parts!), "Reopening restores the saved catalog");
|
||||
reopened.OnDialogClosed();
|
||||
}
|
||||
|
||||
private static RecipeEditorViewModel Open(RecipeWorkspace storage, string name)
|
||||
{
|
||||
var vm = new RecipeEditorViewModel();
|
||||
vm.OnDialogOpened(new DialogParameters { { "directory", storage.RecipesDirectory }, { "path", storage.ConfigPath(name) }, { "config", SopConfigLoader.Load(storage.ConfigPath(name)) }, { "new", false } });
|
||||
return vm;
|
||||
}
|
||||
private static void Check(bool value, string message)
|
||||
{
|
||||
if (!value) throw new Exception(message);
|
||||
Console.WriteLine("PASS: " + message);
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,38 @@ spec.loader.exec_module(worker)
|
||||
|
||||
|
||||
class RecipeTrainingTests(unittest.TestCase):
|
||||
def test_managed_catalog_is_authoritative(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
current = root / "parts" / "current" / "project.json"
|
||||
current.parent.mkdir(parents=True)
|
||||
(current.parent / "frame.jpg").write_bytes(b"test-image")
|
||||
data = {"name": "螺丝", "recipeName": root.name, "recipeDirectory": str(root),
|
||||
"width": 100, "height": 100, "frames": [
|
||||
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
|
||||
for i in range(30)]}
|
||||
worker.save_json(current, data)
|
||||
config = root / (root.name + ".yaml")
|
||||
config.write_text('sop:\n parts: [支架, 螺丝]\n', encoding="utf-8")
|
||||
worker.save_json(root / "recipe-training.json", {"projects": [str(current)], "classes": ["螺丝", "旧名称"]})
|
||||
_, _, classes = worker.recipe_context({"project": str(current)})
|
||||
self.assertEqual(classes, ["支架", "螺丝"])
|
||||
dataset = worker.export_dataset({"project": str(current), "every": 1}).parent
|
||||
self.assertEqual(worker.read_json(dataset / "manifest.json")["classes"], ["支架", "螺丝"])
|
||||
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"1"})
|
||||
before = (root / "recipe-training.json").read_bytes()
|
||||
worker.save_json(current, {**data, "name": "随意输入"})
|
||||
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
|
||||
worker.recipe_context({"project": str(current)})
|
||||
self.assertEqual((root / "recipe-training.json").read_bytes(), before)
|
||||
worker.save_json(current, data)
|
||||
config.write_text('sop:\n parts: [螺丝, 螺丝]\n', encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "零件列表无效"):
|
||||
worker.recipe_context({"project": str(current)})
|
||||
config.write_text('sop:\n parts: []\n', encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
|
||||
worker.recipe_context({"project": str(current)})
|
||||
|
||||
def test_missing_project_removed_and_restored(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
|
||||
@ -259,6 +259,16 @@ def recipe_context(request):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
registry = root / "recipe-training.json"
|
||||
state = read_json(registry) if registry.exists() else {"projects": [], "classes": []}
|
||||
config_path = root / (data.get("recipeName", root.name) + ".yaml")
|
||||
catalog = None
|
||||
if config_path.exists():
|
||||
import yaml
|
||||
catalog = (yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}).get("sop", {}).get("parts")
|
||||
if catalog is not None:
|
||||
if (not isinstance(catalog, list) or any(not isinstance(n, str) or not n.strip() or n != n.strip() for n in catalog)
|
||||
or len(catalog) != len(set(catalog))):
|
||||
raise ValueError("配方零件列表无效,请在配方编辑中维护")
|
||||
state["classes"] = list(catalog)
|
||||
current = str(path)
|
||||
if current not in state["projects"]:
|
||||
state["projects"].append(current)
|
||||
@ -271,9 +281,11 @@ 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']}”不在配方零件列表中,请先在配方编辑中维护")
|
||||
previous = labels.get(str(source))
|
||||
# A corrected name keeps its class ID when it is the sole video for that part.
|
||||
if previous and previous != project["name"] and previous in state["classes"] and project["name"] not in state["classes"]:
|
||||
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 previous not in others:
|
||||
state["classes"][state["classes"].index(previous)] = project["name"]
|
||||
|
||||
Loading…
Reference in New Issue
Block a user