固定使用当前配方训练模型并移除手动模型路径选择
This commit is contained in:
parent
7e357bbc40
commit
e7de29f889
@ -47,7 +47,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
|
||||
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频、零件标注与训练七个标签页;区域坐标使用原图像素。
|
||||
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
|
||||
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
|
||||
- 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。
|
||||
- 检测模型固定使用当前配方最新发布的训练模型,路径、输入尺寸和类别表全部只读,不提供手动选择。模型未训练、文件缺失或训练记录异常时提示训练或重新导出,不回退到其他模型。维护零件列表不会更改已训练模型的类别映射。
|
||||
- “SOP流程视频”页录制当前配方的完整标准操作,固定保存到 `recipes/配方名/sop_stand/sop.avi`,与零件训练录像分开存放。新配方先保存,再开启预览并开始录像。普通录像与SOP录像统一使用运行设置中选中的相机,录制界面只显示相机名称,不再选择或刷新设备。
|
||||
- 支持暂停、继续和停止保存;暂停时间不计入视频,累计有效录像最长 5 分钟,到时自动保存并弹窗。关闭编辑窗口也会停止并保存录像。
|
||||
- 同页可播放已保存视频,支持暂停、继续、停止及播完重播,拖动进度条可前后跳转,并保持原来的播放或暂停状态。播放不需要连接相机;开始播放时关闭相机预览,重新开启预览或关闭窗口时释放播放器。
|
||||
@ -63,11 +63,11 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
|
||||
4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。
|
||||
|
||||
模型文件:`palm_detection_full_Nx3x192x192_post.onnx`、`hand_landmark_sparse_Nx3x224x224.onnx`;
|
||||
目标检测模型由配方选择。测试用 `yolo11n.onnx` 和训练依赖沿用其上游许可。
|
||||
目标检测模型由当前配方的训练结果自动管理。测试用 `yolo11n.onnx` 和训练依赖沿用其上游许可。
|
||||
|
||||
## 配方存储与迁移
|
||||
|
||||
实际配方统一保存在 `recipes/<配方名>/<配方名>.yaml`。新建配方自动创建同名目录;编辑器选择的外部 ONNX 会复制到该配方的 `models`,运行快照保存在 `snaps`。
|
||||
实际配方统一保存在 `recipes/<配方名>/<配方名>.yaml`。新建配方自动创建同名目录;训练生成的 ONNX 保存在该配方的 `models`,由 `latest-model.json` 指向最新版本,运行快照保存在 `snaps`。
|
||||
|
||||
配方名同时作为文件名和目录名,编辑器只提供一个名称输入框,保存后名称固定。禁止 `< > : " / \ | ? *`、控制字符、末尾空格或句点及 `CON`、`NUL`、`COM1` 等系统保留名称;不合法时显示原因并禁止保存。已有配方以当前文件名为统一名称。
|
||||
|
||||
|
||||
@ -143,7 +143,7 @@ public sealed class MainViewModel : BindableBase
|
||||
public int Epochs { get; set; } = 50;
|
||||
public int Batch { get; set; } = 4;
|
||||
public int ImageSize { get; set; } = 640;
|
||||
public string Model { get; set; } = "yolo11n.pt";
|
||||
public string Model => "yolo11n.pt";
|
||||
public string Endpoint { get; set; } = "https://api.example.com/v1";
|
||||
public string ApiModel { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
@ -155,7 +155,6 @@ public sealed class MainViewModel : BindableBase
|
||||
public DelegateCommand PropagateCommand { get; }
|
||||
public DelegateCommand ExportCommand { get; }
|
||||
public DelegateCommand TrainCommand { get; }
|
||||
public DelegateCommand PickTrainingModelCommand { get; }
|
||||
public DelegateCommand OpenTrainingResultsCommand { get; }
|
||||
public DelegateCommand OnnxCommand { get; }
|
||||
public DelegateCommand SuggestCommand { get; }
|
||||
@ -192,11 +191,6 @@ public sealed class MainViewModel : BindableBase
|
||||
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" };
|
||||
if (await dialog.ShowDialogAsync() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
|
||||
});
|
||||
OpenTrainingResultsCommand = Command(() =>
|
||||
{
|
||||
var directory = TrainingRunDirectory;
|
||||
@ -461,7 +455,7 @@ public sealed class MainViewModel : BindableBase
|
||||
// 新配方使用默认参数,避免沿用刚刚查看的其他配方。
|
||||
ExtractStride=1; MaxFrames=600; ExportEvery=5; Epochs=50; Batch=4; ImageSize=640;
|
||||
Checkpoint=""; SamConfig="configs/sam2.1/sam2.1_hiera_t.yaml"; Device="auto";
|
||||
Model="yolo11n.pt"; Endpoint="https://api.example.com/v1"; ApiModel=""; Description="";
|
||||
Endpoint="https://api.example.com/v1"; ApiModel=""; Description="";
|
||||
foreach (var property in GetType().GetProperties().Where(p => p.CanWrite)) RaisePropertyChanged(property.Name);
|
||||
if (!File.Exists(path)) return;
|
||||
try
|
||||
|
||||
@ -405,6 +405,7 @@
|
||||
</TabItem>
|
||||
<TabItem Header="检测模型">
|
||||
<StackPanel x:Name="ModelSettings" Margin="10" DataContext="{Binding Recipe}">
|
||||
<TextBlock Text="{Binding DataContext.ModelStatus, RelativeSource={RelativeSource AncestorType=UserControl}}" TextWrapping="Wrap" Margin="0,0,0,10" />
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding Settings.ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="海康相机曝光时间,10000 为 10 毫秒;留空保留相机设置。保存配方后保留,区域取图和 SOP 启动前应用。" />
|
||||
@ -414,11 +415,9 @@
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="模型路径" Classes="Field" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Path, Mode=TwoWay}" />
|
||||
<Button Grid.Column="2" Content="选择模型…" Margin="8,0,0,0" Command="{Binding DataContext.BrowseModelCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" Classes="Mini" />
|
||||
<TextBlock Text="配方模型" Classes="Field" />
|
||||
<TextBlock x:Name="RecipeModelPath" Grid.Column="1" Text="{Binding Path}" TextWrapping="Wrap" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<Grid Classes="Row">
|
||||
<Grid.ColumnDefinitions>
|
||||
@ -426,7 +425,7 @@
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="输入尺寸" Classes="Field" />
|
||||
<TextBox Grid.Column="1" Text="{Binding InputSize, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding InputSize}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<StackPanel DataContext="{Binding Classes}">
|
||||
<TextBlock FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" Classes="Title" />
|
||||
|
||||
@ -28,6 +28,9 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private readonly HashSet<EditorNode> _observedStepNodes = [];
|
||||
private string _saveStatus = "";
|
||||
private bool _closingDialog;
|
||||
private ModelDef? _managedModel;
|
||||
private string _modelStatus = "请先保存配方,再训练配方模型";
|
||||
public string ModelStatus { get => _modelStatus; private set => SetProperty(ref _modelStatus, value); }
|
||||
|
||||
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
|
||||
public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? "";
|
||||
@ -56,14 +59,12 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
if (!SetProperty(ref _isCapturing, value)) return;
|
||||
CaptureImageCommand.RaiseCanExecuteChanged();
|
||||
OpenImageCommand.RaiseCanExecuteChanged();
|
||||
BrowseModelCommand.RaiseCanExecuteChanged();
|
||||
SaveCommand.RaiseCanExecuteChanged();
|
||||
CloseCommand.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
public DelegateCommand CaptureImageCommand { get; }
|
||||
public DelegateCommand OpenImageCommand { get; }
|
||||
public DelegateCommand BrowseModelCommand { get; }
|
||||
|
||||
/// <summary>当前编辑的配方目录(configs/sop)</summary>
|
||||
private string _directory = "";
|
||||
@ -112,7 +113,6 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
|
||||
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
|
||||
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
|
||||
BrowseModelCommand = new DelegateCommand(BrowseModel, () => !IsCapturing);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@ -154,6 +154,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
/// <inheritdoc />
|
||||
public void OnDialogClosed()
|
||||
{
|
||||
if (TrainingView is not null) TrainingView.Model.PropertyChanged -= TrainingModelChanged;
|
||||
_ = ShutdownAsync();
|
||||
Recipe.Changed -= RefreshWarnings;
|
||||
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
|
||||
@ -171,6 +172,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
_trainingWorker = new WorkerClient();
|
||||
var training = new SopHelper.Training.MainViewModel(_trainingWorker);
|
||||
training.BindRecipe(Path.GetFileNameWithoutExtension(_path));
|
||||
training.PropertyChanged += TrainingModelChanged;
|
||||
TrainingView = new SopHelper.Training.TrainingPage(training, null, embedded: true,
|
||||
selectedCameraProvider: _selectedCameraProvider,
|
||||
canOpenCamera: () => _canUseCamera() && !IsCapturing && SopRecording?.IsPreviewing != true);
|
||||
@ -218,35 +220,19 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
catch (Exception ex) { PreviewStatus = "打开图片失败:" + ex.Message; }
|
||||
}
|
||||
|
||||
private async void BrowseModel()
|
||||
private void TrainingModelChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (Recipe.Model is null) return;
|
||||
var dialog = new OpenFileDialog
|
||||
{
|
||||
Title = "选择 ONNX 检测模型",
|
||||
Filter = "ONNX 模型 (*.onnx)|*.onnx",
|
||||
DefaultExt = ".onnx",
|
||||
CheckFileExists = true,
|
||||
Multiselect = false,
|
||||
InitialDirectory = AppContext.BaseDirectory,
|
||||
};
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(Recipe.Model.Path))
|
||||
{
|
||||
var currentPath = Path.GetFullPath(Recipe.Model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
|
||||
var directory = Path.GetDirectoryName(currentPath);
|
||||
if (Directory.Exists(directory)) dialog.InitialDirectory = directory;
|
||||
if (File.Exists(currentPath)) dialog.FileName = Path.GetFileName(currentPath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
// 手填路径无效时,仍可从程序目录重新选择。
|
||||
}
|
||||
if (await dialog.ShowDialogAsync() != true) return;
|
||||
Recipe.Model.Path = dialog.FileName;
|
||||
RefreshWarnings();
|
||||
if (e.PropertyName == nameof(SopHelper.Training.MainViewModel.LatestOnnx) ||
|
||||
(e.PropertyName == nameof(SopHelper.Training.MainViewModel.IsBusy) && TrainingView?.Model.IsBusy == false)) RefreshWarnings();
|
||||
}
|
||||
private void RefreshManagedModel()
|
||||
{
|
||||
_managedModel = null;
|
||||
var status = "请先保存配方,再训练配方模型";
|
||||
if (!string.IsNullOrEmpty(_path))
|
||||
_managedModel = RecipeModelResolver.Load(Path.GetDirectoryName(_path)!, Path.GetFileNameWithoutExtension(_path), out status);
|
||||
ModelStatus = status;
|
||||
Recipe.Model.CopyFrom(_managedModel ?? new ModelDef());
|
||||
}
|
||||
|
||||
private async Task CaptureImageAsync()
|
||||
@ -321,25 +307,21 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
|
||||
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
RefreshManagedModel();
|
||||
var config = Recipe.ToConfig();
|
||||
PartCatalog.Validate(config, Path.GetDirectoryName(path));
|
||||
if (config.Sop.Model is { Path.Length: > 0 } model)
|
||||
config.Sop.Model = _managedModel is null ? null : new ModelDef
|
||||
{
|
||||
var source = Path.GetFullPath(model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
|
||||
var workspace = new RecipeWorkspace(Path.GetDirectoryName(_directory)!);
|
||||
if (File.Exists(source))
|
||||
{
|
||||
var imported = workspace.ImportFile(fileName, source, "models");
|
||||
model.Path = Path.GetRelativePath(Path.GetDirectoryName(path)!, imported);
|
||||
}
|
||||
}
|
||||
Path = Path.GetRelativePath(Path.GetDirectoryName(path)!, _managedModel.Path),
|
||||
InputSize = _managedModel.InputSize, Classes = _managedModel.Classes.ToList()
|
||||
};
|
||||
PartCatalog.Validate(config, Path.GetDirectoryName(path));
|
||||
var saved = SopConfigLoader.Save(config, path);
|
||||
if (Recipe.Model is not null && config.Sop.Model is not null) Recipe.Model.Path = config.Sop.Model.Path;
|
||||
|
||||
_path = path;
|
||||
_isNew = false;
|
||||
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
|
||||
InitializeRecipeTools();
|
||||
RefreshManagedModel();
|
||||
TrainingView?.Model.RefreshPartNames();
|
||||
RaisePropertyChanged(nameof(FileNameText));
|
||||
RaisePropertyChanged(nameof(Title));
|
||||
@ -383,7 +365,9 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
}
|
||||
Warnings.Clear();
|
||||
|
||||
RefreshManagedModel();
|
||||
var config = Recipe.ToConfig();
|
||||
config.Sop.Model = _managedModel;
|
||||
try { PartCatalog.Validate(config, string.IsNullOrEmpty(_path) ? null : Path.GetDirectoryName(_path)); }
|
||||
catch (InvalidDataException error) { Warnings.Add(error.Message); }
|
||||
SopConfigLoader.Validate(config);
|
||||
|
||||
@ -635,10 +635,10 @@ public class SopPageViewModel : ViewModelBase
|
||||
LoadTrainedRecipeModel(config);
|
||||
_engine.Load(config);
|
||||
|
||||
// 优先使用本配方训练发布的 ONNX,否则使用配方配置中的模型。
|
||||
// 仅使用本配方训练发布的 ONNX。
|
||||
var options = new PipelineOptions
|
||||
{
|
||||
YoloModelPath = ResolveRecipeModel(config.Sop.Model?.Path, Path.GetDirectoryName(path)!),
|
||||
YoloModelPath = config.Sop.Model?.Path,
|
||||
YoloClasses = config.Sop.Model?.Classes ?? [],
|
||||
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
|
||||
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
|
||||
@ -677,35 +677,11 @@ public class SopPageViewModel : ViewModelBase
|
||||
private void LoadTrainedRecipeModel(SopConfig config)
|
||||
{
|
||||
var recipeName = Path.GetFileNameWithoutExtension(SelectedRecipe);
|
||||
var manifest = Path.Combine(DesktopPlatform.Recipes.DirectoryFor(recipeName!), "latest-model.json");
|
||||
if (!File.Exists(manifest)) return;
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(manifest));
|
||||
var model = document.RootElement;
|
||||
var modelPath = model.TryGetProperty("onnx", out var onnx) ? onnx.GetString() : null;
|
||||
if (string.IsNullOrWhiteSpace(modelPath))
|
||||
{
|
||||
// 旧版本手动导出会生成与 PT 同名的 ONNX,但未记录路径。
|
||||
if (!model.TryGetProperty("weights", out var weights)) return;
|
||||
modelPath = Path.ChangeExtension(weights.GetString(), ".onnx");
|
||||
if (!File.Exists(modelPath)) return;
|
||||
}
|
||||
if (model.GetProperty("recipeName").GetString() != recipeName)
|
||||
throw new InvalidDataException("模型与当前配方不匹配");
|
||||
if (string.IsNullOrWhiteSpace(modelPath) || !Path.IsPathRooted(modelPath) || !File.Exists(modelPath))
|
||||
throw new FileNotFoundException("配方 ONNX 文件不存在", modelPath);
|
||||
var classes = model.GetProperty("classes").Deserialize<List<string>>() ?? [];
|
||||
var size = model.GetProperty("imageSize").GetInt32();
|
||||
if (classes.Count == 0 || size < 32 || size > 2048 || size % 32 != 0)
|
||||
throw new InvalidDataException("配方模型类别或输入尺寸无效");
|
||||
config.Sop.Model = new ModelDef { Path = modelPath, Classes = classes, InputSize = size };
|
||||
Log("info", $"已加载配方训练模型:{modelPath}");
|
||||
}
|
||||
catch (Exception error) when (error is IOException or InvalidDataException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException)
|
||||
{
|
||||
Log("warn", "读取配方训练模型失败,使用配方配置:" + error.Message);
|
||||
}
|
||||
var directory = DesktopPlatform.Recipes.DirectoryFor(recipeName!);
|
||||
config.Sop.Model = SopHelper.Engine.Training.RecipeModelResolver.Load(directory, recipeName!, out var status);
|
||||
config.Warnings.Clear(); SopConfigLoader.Validate(config);
|
||||
Log(config.Sop.Model is null && File.Exists(Path.Combine(directory, "latest-model.json")) ? "warn" : "info",
|
||||
config.Sop.Model is { } model ? $"已加载配方训练模型:{model.Path}" : status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -720,13 +696,6 @@ public class SopPageViewModel : ViewModelBase
|
||||
return File.Exists(path) ? path : null;
|
||||
}
|
||||
|
||||
private static string? ResolveRecipeModel(string? model, string recipeDirectory)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(model)) return null;
|
||||
var local = Path.GetFullPath(model, recipeDirectory);
|
||||
return File.Exists(local) ? local : ResolveModel(model);
|
||||
}
|
||||
|
||||
private void OnResult(FrameResult result)
|
||||
{
|
||||
if (_destroyed || !IsRunning) return;
|
||||
|
||||
@ -127,7 +127,7 @@ public static partial class SopConfigLoader
|
||||
}
|
||||
|
||||
if (NeedsModel(condition.Method) && string.IsNullOrWhiteSpace(config.Sop.Model?.Path))
|
||||
config.Warnings.Add($"步骤 {step.Id} 的方法 '{condition.Method}' 需要模型,但尚未配置模型路径");
|
||||
config.Warnings.Add($"步骤 {step.Id} 的方法 '{condition.Method}' 需要模型,配方模型尚未就绪,请先训练或重新导出");
|
||||
|
||||
foreach (var rule in step.ViolationRules)
|
||||
{
|
||||
|
||||
@ -0,0 +1,42 @@
|
||||
using System.Text.Json;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Engine.Training;
|
||||
|
||||
/// <summary>只解析当前配方训练发布的模型,配置文件中的手填模型路径不参与选择。</summary>
|
||||
public static class RecipeModelResolver
|
||||
{
|
||||
public static ModelDef? Load(string directory, string recipeName, out string status)
|
||||
{
|
||||
status = "尚未训练配方模型,请到“零件标注与训练”完成训练";
|
||||
var manifest = Path.Combine(directory, "latest-model.json");
|
||||
if (!File.Exists(manifest)) return null;
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(manifest));
|
||||
var model = document.RootElement;
|
||||
if (model.GetProperty("recipeName").GetString() != recipeName)
|
||||
throw new InvalidDataException("模型与当前配方不匹配");
|
||||
var path = model.TryGetProperty("onnx", out var onnx) ? onnx.GetString() : null;
|
||||
if (string.IsNullOrWhiteSpace(path) && model.TryGetProperty("weights", out var weights))
|
||||
path = Path.ChangeExtension(weights.GetString(), ".onnx");
|
||||
if (string.IsNullOrWhiteSpace(path)) throw new InvalidDataException("训练记录没有配方 ONNX,请重新导出");
|
||||
path = Path.GetFullPath(path, directory);
|
||||
if (!RecipeWorkspace.IsWithin(path, directory) || !Path.GetExtension(path).Equals(".onnx", StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidDataException("模型必须位于当前配方目录中");
|
||||
if (!File.Exists(path)) throw new FileNotFoundException("配方 ONNX 不存在,请重新导出配方模型", path);
|
||||
var classes = model.GetProperty("classes").Deserialize<List<string>>() ?? [];
|
||||
var size = model.GetProperty("imageSize").GetInt32();
|
||||
if (classes.Count == 0 || classes.Any(string.IsNullOrWhiteSpace) || classes.Distinct().Count() != classes.Count ||
|
||||
size < 32 || size > 2048 || size % 32 != 0)
|
||||
throw new InvalidDataException("配方模型类别或输入尺寸无效,请重新训练或导出");
|
||||
status = "自动使用当前配方最新训练模型,无需选择路径";
|
||||
return new ModelDef { Path = path, Classes = classes, InputSize = size };
|
||||
}
|
||||
catch (Exception error) when (error is IOException or InvalidDataException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
status = "配方模型不可用:" + error.Message;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -173,15 +173,21 @@ internal static class Smoke
|
||||
var recipeWorkspace=storage.DirectoryFor(recipeId);
|
||||
Directory.CreateDirectory(recipeWorkspace);
|
||||
var modelFile=Path.Combine(recipeWorkspace,recipeId+".onnx");
|
||||
var externalModel=Path.Combine(trainer.Root,"external-model.onnx");
|
||||
var manifestFile=Path.Combine(recipeWorkspace,"latest-model.json");
|
||||
try
|
||||
{
|
||||
File.Copy(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"),recipeFile);
|
||||
// The model loader may reject this stub; this checks recipe routing and metadata independently.
|
||||
File.WriteAllBytes(modelFile,[]);
|
||||
var manualConfig=SopHelper.Engine.Sop.SopConfigLoader.Load(recipeFile);
|
||||
manualConfig.Sop.Model=new SopHelper.Engine.Sop.ModelDef{Path=modelFile,Classes=["manual"],InputSize=640};
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(manualConfig,recipeFile);
|
||||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"A manually configured model cannot replace a missing recipe training publication");
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||||
Check(engine.Config.Sop.Model is {InputSize:960} trained&&trained.Path==modelFile&&trained.Classes.SequenceEqual(new[]{"测试零件"}),"Applying a recipe selects its trained ONNX, class order and input size");
|
||||
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model?.Path!=modelFile,"Switching recipes does not reuse the previous recipe's ONNX");
|
||||
@ -190,12 +196,23 @@ internal static class Smoke
|
||||
Check(engine.Config.Sop.Model?.Path==modelFile,"Older training records discover an existing ONNX beside their checkpoint");
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName="another-recipe",onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Mismatched recipe metadata cannot replace the configured model");
|
||||
Check(engine.Config.Sop.Model is null,"Mismatched recipe metadata does not fall back to the configured model");
|
||||
File.WriteAllText(manifestFile,"{broken-json");
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Broken training publication does not fall back to a manually configured model");
|
||||
File.WriteAllBytes(externalModel,[]);
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=externalModel,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Model files outside the current recipe are rejected");
|
||||
File.Delete(modelFile);
|
||||
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
||||
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
||||
Check(engine.Config.Sop.Model is null,"Missing published model cannot fall back to other models");
|
||||
}
|
||||
finally
|
||||
{
|
||||
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||||
File.Delete(recipeFile);File.Delete(modelFile);File.Delete(manifestFile);Directory.Delete(recipeWorkspace);
|
||||
File.Delete(recipeFile);File.Delete(modelFile);File.Delete(manifestFile);File.Delete(externalModel);Directory.Delete(recipeWorkspace);
|
||||
}
|
||||
var trainingTabs=trainingView.GetVisualDescendants().OfType<TabControl>().Single();
|
||||
trainingTabs.SelectedIndex=1;await Task.Delay(80);
|
||||
|
||||
@ -41,7 +41,8 @@ internal static class Program
|
||||
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[] { "支架", "螺丝" } }));
|
||||
var modelPath = Path.Combine(directory, "装配.onnx"); File.WriteAllText(modelPath, "test-model");
|
||||
File.WriteAllText(Path.Combine(directory, "latest-model.json"), JsonSerializer.Serialize(new { recipeName = "装配", onnx = modelPath, weights = Path.ChangeExtension(modelPath, ".pt"), imageSize = 640, 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, "装配");
|
||||
@ -59,10 +60,12 @@ internal static class Program
|
||||
target.SelectedItem = "";
|
||||
Check(vm.Recipe.SelectedStep.Detection.TargetObject == "", "Explicit empty selection clears an optional target");
|
||||
target.SelectedItem = "螺丝";
|
||||
vm.Recipe.Model.Path = Path.Combine(storage.Root, "manual-model.onnx"); vm.Recipe.Model.InputSize = 999;
|
||||
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");
|
||||
Check(saved.Sop.Model!.Classes.SequenceEqual(new[] { "支架", "螺丝" }), "Saved model labels follow the recipe training publication order");
|
||||
Check(Path.GetFullPath(saved.Sop.Model.Path, directory) == modelPath && saved.Sop.Model.InputSize == 640, "Saving always uses the published recipe model instead of stale/manual settings");
|
||||
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");
|
||||
@ -73,6 +76,7 @@ internal static class Program
|
||||
Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Referenced parts cannot be deleted");
|
||||
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single();
|
||||
tabs.SelectedIndex = 4; window.UpdateLayout();
|
||||
Check(editor.FindControl<TextBlock>("RecipeModelPath")!.Text == modelPath && !editor.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "选择模型…"), "Recipe model path is automatic and read-only");
|
||||
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();
|
||||
@ -99,6 +103,10 @@ internal static class Program
|
||||
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");
|
||||
var nextModel = Path.Combine(directory, "models", "v2", "装配.onnx"); Directory.CreateDirectory(Path.GetDirectoryName(nextModel)!); File.WriteAllText(nextModel, "next-version");
|
||||
File.WriteAllText(Path.Combine(directory, "latest-model.json"), JsonSerializer.Serialize(new { recipeName = "装配", onnx = nextModel, weights = Path.ChangeExtension(nextModel, ".pt"), imageSize = 960, classes = new[] { "支架", "螺丝" } }));
|
||||
reopened.TrainingView!.Model.Load(project.FilePath);
|
||||
Check(reopened.Recipe.Model.Path == nextModel && reopened.Recipe.Model.InputSize == 960, "Editor refreshes automatically when training publishes a newer recipe model");
|
||||
reopened.OnDialogClosed();
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user