收敛旧配方兼容与历史资料迁移

This commit is contained in:
Codex 2026-11-25 10:14:39 +08:00
parent e27aba66a2
commit 207f7b4334
29 changed files with 331 additions and 635 deletions

View File

@ -2,7 +2,7 @@
Windows / Linux 共用一套 Avalonia 桌面程序:相机采集、双手关键点检测、区域触发和 djev 步骤确认。本分支已移除 YOLO 推理及模型、零件标注和训练设置界面。
当前代码和构建不依赖原 WPF 归档。旧标注、训练记录和模型文件不自动删除,但不会被当前运行管线加载。
当前代码和构建不依赖原 WPF 归档。旧标注、训练记录和模型文件保留在原目录。整目录导入配方时原样复制这些文件;从旧散放配置初始化时迁移标准视频。
## 运行

View File

@ -9,16 +9,16 @@ namespace SopHelper.Presentation;
internal static class DesktopPlatform
{
private static readonly Lazy<SopHelper.Engine.Training.RecipeWorkspace> RecipeStorage = new(() =>
private static readonly Lazy<SopHelper.Engine.Recipes.RecipeWorkspace> RecipeStorage = new(() =>
{
var storage = new SopHelper.Engine.Training.RecipeWorkspace(WorkspaceRoot);
var storage = new SopHelper.Engine.Recipes.RecipeWorkspace(WorkspaceRoot);
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")) &&
LegacySourceRoot is { } legacyRoot)
storage.ImportFrom(legacyRoot);
storage.Initialize(Path.Combine(AppContext.BaseDirectory, "configs", "sop"));
return storage;
});
public static SopHelper.Engine.Training.RecipeWorkspace Recipes => RecipeStorage.Value;
public static SopHelper.Engine.Recipes.RecipeWorkspace Recipes => RecipeStorage.Value;
public static string WorkspaceRoot
{
get

View File

@ -15,7 +15,7 @@ internal static class Program
try
{
if(importIndex+1>=args.Length)throw new ArgumentException("--import-recipes 后需提供原数据根目录");
var storage=new SopHelper.Engine.Training.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
var storage=new SopHelper.Engine.Recipes.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
storage.ImportFrom(args[importIndex+1]);
storage.Initialize(Path.Combine(AppContext.BaseDirectory,"configs","sop"));
Console.WriteLine($"配方导入完成:{storage.RecipesDirectory}");return 0;
@ -39,8 +39,8 @@ internal static class Program
try
{
if (exportIndex + 2 >= args.Length) throw new ArgumentException("--export-recipe-package 后需提供配方名和输出文件");
var storage = new SopHelper.Engine.Training.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
var result = SopHelper.Engine.Training.RecipePackage.Export(storage, args[exportIndex + 1], args[exportIndex + 2]);
var storage = new SopHelper.Engine.Recipes.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
var result = SopHelper.Engine.Recipes.RecipePackage.Export(storage, args[exportIndex + 1], args[exportIndex + 2]);
foreach (var note in result.Warnings) Console.WriteLine($"提醒:{note}");
Console.WriteLine($"已导出配方包:{result.Path}({result.FileCount} 个文件)");
return 0;
@ -55,12 +55,12 @@ internal static class Program
// 一次可传多个包;同名配方自动追加 -2、-3 等后缀,命令行没有确认窗口,绝不覆盖现场配方。
var paths = args.Skip(packageIndex + 1).TakeWhile(arg => !arg.StartsWith("--")).ToArray();
if (paths.Length == 0) throw new ArgumentException("--import-recipe-package 后需提供配方包文件");
var storage = new SopHelper.Engine.Training.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
var storage = new SopHelper.Engine.Recipes.RecipeWorkspace(Presentation.DesktopPlatform.WorkspaceRoot);
foreach (var path in paths)
{
var info = SopHelper.Engine.Training.RecipePackage.Inspect(path);
var target = SopHelper.Engine.Training.RecipePackage.SuggestName(storage, info.RecipeName);
var result = SopHelper.Engine.Training.RecipePackage.Import(storage, path, target, false);
var info = SopHelper.Engine.Recipes.RecipePackage.Inspect(path);
var target = SopHelper.Engine.Recipes.RecipePackage.SuggestName(storage, info.RecipeName);
var result = SopHelper.Engine.Recipes.RecipePackage.Import(storage, path, target, false);
foreach (var warning in result.Warnings) Console.WriteLine($"提醒:{warning}");
Console.WriteLine($"已导入配方:{result.Name}");
}

View File

@ -2,7 +2,7 @@
using System.IO;
using OpenCvSharp;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.Presentation;
namespace SopHelper.SopVideo;

View File

@ -9,7 +9,7 @@ using SopHelper.Presentation.Imaging;
using SopHelper.Presentation.Threading;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using Prism.Commands;
using Prism.Mvvm;

View File

@ -52,7 +52,6 @@ public sealed class SopVideoFlowTest : IDisposable
var snapshot = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config));
(SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).Apply(snapshot);
snapshot.Sop.Settings.AutoResetOnComplete = false;
snapshot.Sop.Model = null;
_stride = Math.Max(1, snapshot.Sop.Settings.FrameStride);
_engine.VisionDecisionClient = visionClient ?? new ConfiguredVisionDecisionClient(VisionHttp);
_engine.LogArrived += entry => LogObserved?.Invoke(entry);

View File

@ -27,29 +27,7 @@ public interface IRemovable
}
/// <summary>
/// 字符串列表项(YAML 的 classes / must_keep / required_objects)。
/// 不能直接绑 string——string 不实现 INPC,TwoWay 写不回集合项。
/// </summary>
public class TextItem : EditorNode, IRemovable
{
private string _text = "";
/// <summary>文本</summary>
public string Text
{
get { return _text; }
set { SetProperty(ref _text, value); }
}
/// <inheritdoc />
public ICommand? RemoveCommand { get; set; }
/// <inheritdoc />
public override string ToString() => Text;
}
/// <summary>
/// 可增删的行列表(类别名、必在物料、违规规则都用它)
/// 可增删的编辑行列表,用于违规规则。
/// </summary>
public class EditableList<T> : EditorNode where T : EditorNode, IRemovable, new()
{
@ -119,25 +97,10 @@ 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>
internal List<string>? LegacyParts { get; set; }
/// <summary>加区域</summary>
public DelegateCommand AddRegionCommand { get; }
@ -224,9 +187,6 @@ public class RecipeNode : EditorNode
/// <summary>步骤(sop.steps)</summary>
public ObservableCollection<StepNode> Steps { get; } = [];
/// <summary>检测模型配置始终启用。</summary>
public RecipeModelNode Model { get; } = new();
/// <summary>当前编辑的区域</summary>
public RegionNode? SelectedRegion
{
@ -406,8 +366,7 @@ public class RecipeNode : EditorNode
Description = config.Sop.Description,
};
foreach (var name in SopHelper.Engine.Training.PartCatalog.Read(config, null))
node.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = node.Parts.RemoveCommand });
node.LegacyParts = config.Sop.Parts?.ToList();
foreach (var (key, def) in config.Sop.Regions)
{
@ -444,8 +403,8 @@ public class RecipeNode : EditorNode
},
};
foreach (var item in step.MustKeep) stepNode.MustKeep.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.MustKeep.RemoveCommand });
foreach (var item in step.RequiredObjects) stepNode.RequiredObjects.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.RequiredObjects.RemoveCommand });
stepNode.LegacyMustKeep.AddRange(step.MustKeep);
stepNode.LegacyRequiredObjects.AddRange(step.RequiredObjects);
if (step.Detection is not null) stepNode.Detection = ConditionNode.From(step.Detection);
@ -455,11 +414,6 @@ public class RecipeNode : EditorNode
node.Steps.Add(stepNode);
}
if (config.Sop.Model is not null)
{
node.Model.CopyFrom(config.Sop.Model);
}
node.SelectedStep = node.Steps.FirstOrDefault();
node.SelectedRegion = node.Regions.FirstOrDefault();
@ -477,8 +431,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();
config.Sop.Parts = LegacyParts?.ToList();
foreach (var region in Regions.Where(r => !string.IsNullOrWhiteSpace(r.Key)))
{
@ -513,8 +466,8 @@ public class RecipeNode : EditorNode
},
};
def.MustKeep.AddRange(step.MustKeep.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
def.RequiredObjects.AddRange(step.RequiredObjects.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
def.MustKeep.AddRange(step.LegacyMustKeep);
def.RequiredObjects.AddRange(step.LegacyRequiredObjects);
if (step.Detection is not null && !string.IsNullOrWhiteSpace(step.Detection.Method))
def.Detection = step.Detection.ToCondition();
@ -525,48 +478,10 @@ public class RecipeNode : EditorNode
config.Sop.Steps.Add(def);
}
config.Sop.Model = null;
return config;
}
}
/// <summary>
/// sop.model
/// </summary>
public class RecipeModelNode : EditorNode
{
private string _path = "";
private int _inputSize = 640;
/// <summary>onnx 路径(相对程序目录)</summary>
public string Path
{
get { return _path; }
set { SetProperty(ref _path, value); }
}
/// <summary>类别名(顺序必须与训练时一致)</summary>
public EditableList<TextItem> Classes { get; } = new() { Title = "类别名(顺序须与训练一致)" };
/// <summary>输入尺寸</summary>
public int InputSize
{
get { return _inputSize; }
set { SetProperty(ref _inputSize, value); }
}
/// <summary>读入</summary>
public void CopyFrom(ModelDef from)
{
Path = from.Path;
InputSize = from.InputSize;
Classes.Items.Clear();
foreach (var name in from.Classes) Classes.Items.Add(new TextItem { Text = name, RemoveCommand = Classes.RemoveCommand });
}
}
/// <summary>
/// regions 里的一项(Key = 配方里引用的区域名,即 YAML 的字典键)
/// </summary>
@ -864,11 +779,9 @@ public class StepNode : EditorNode
set { SetProperty(ref _detection, value); }
}
/// <summary>本步期间必须常在的物体</summary>
public EditableList<TextItem> MustKeep { get; } = new() { Title = "本步期间必须在的物体(被拿走即违规)" };
/// <summary>本步完成时必须存在的物体</summary>
public EditableList<TextItem> RequiredObjects { get; } = new() { Title = "本步完成时必须存在的物体(漏放/缺料)" };
/// <summary>保留旧物料规则,使编辑和保存后仍可提示工艺迁移。</summary>
internal List<string> LegacyMustKeep { get; } = [];
internal List<string> LegacyRequiredObjects { get; } = [];
/// <summary>违规规则</summary>
public EditableList<ViolationRuleNode> ViolationRules { get; } = new() { Title = "违规规则" };
@ -924,7 +837,7 @@ public class ConditionNode : EditorNode
public bool UsesHandTrigger => UsesTriggerRegion || IsMoveTrigger;
public bool UsesStableGate => UsesTriggerRegion;
/// <summary>目标物体类别</summary>
/// <summary>旧物体触发的目标名称,仅用于配方往返。</summary>
public string TargetObject
{
get { return _targetObject; }

View File

@ -1,15 +1,5 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" x:Name="RecipeEditorRoot" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters" xmlns:video="clr-namespace:SopHelper.SopVideo" xmlns:sop="clr-namespace:SopHelper.VVMs.SopPage">
<UserControl.DataTemplates>
<DataTemplate DataType="{x:Type ed:TextItem}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<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>
<DataTemplate DataType="{x:Type ed:ViolationRuleNode}">
<StackPanel Spacing="6" Margin="0,0,0,8">

View File

@ -12,7 +12,7 @@ using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
namespace SopHelper.VVMs.RecipeEditor;
@ -340,7 +340,6 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var config = Recipe.ToConfig();
config.Sop.Model = null;
var saved = SopConfigLoader.Save(config, path);
_path = path;
@ -395,7 +394,6 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
Warnings.Clear();
var config = Recipe.ToConfig();
config.Sop.Model = null;
SopConfigLoader.Validate(config);
foreach (var warning in config.Warnings) Warnings.Add(warning);

View File

@ -25,9 +25,7 @@ public partial class RecipeEditorViewModel
Recipe.AddRegion(region.Key).CopyFrom(merged.Sop.Regions[region.Key]);
Recipe.Steps.Clear();
foreach (var step in prepared.Steps) Recipe.Steps.Add(step);
foreach (var part in prepared.Parts.Items)
if (!Recipe.Parts.Items.Any(p => p.Text.Equals(part.Text, StringComparison.OrdinalIgnoreCase)))
Recipe.Parts.Items.Add(new TextItem { Text = part.Text, RemoveCommand = Recipe.Parts.RemoveCommand });
Recipe.LegacyParts = prepared.LegacyParts;
Recipe.SelectedStep = Recipe.Steps.ElementAtOrDefault(firstImported);
RefreshWarnings();
StepTransferStatus = $"已{(append ? "追加" : "替换导入")} {incoming.Sop.Steps.Count} 个步骤,当前共 {Recipe.Steps.Count} 步;点击“保存”后写入配方。";

View File

@ -22,7 +22,7 @@ public sealed class DeleteRecipeDialog : Window
Children =
{
new TextBlock { Text = $"确定删除配方“{name}”?", FontSize = 16, FontWeight = FontWeight.Bold, TextWrapping = TextWrapping.Wrap },
new TextBlock { Text = "此配方的配置、录像、标注数据和训练模型会一并从配方列表移除,移入本地“已删除配方”目录,必要时可以找回。", TextWrapping = TextWrapping.Wrap },
new TextBlock { Text = "此配方及其目录内的文件会移入本地“已删除配方”目录,必要时可以找回。", TextWrapping = TextWrapping.Wrap },
new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Spacing = 8, Children = { cancel, delete } }
}
};

View File

@ -17,7 +17,7 @@ using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
namespace SopHelper.VVMs.SopPage;
@ -95,7 +95,7 @@ public class SopPageViewModel : ViewModelBase
/// <param name="PackagePath">用户选择的配方包文件路径。</param>
/// <param name="Info">包摘要,含配方名、文件数、体积与提醒。</param>
/// <param name="SuggestedName">改名导入时将使用的可用配方名。</param>
public sealed record ImportConflict(string PackagePath, SopHelper.Engine.Training.RecipePackage.PackageInfo Info, string SuggestedName);
public sealed record ImportConflict(string PackagePath, SopHelper.Engine.Recipes.RecipePackage.PackageInfo Info, string SuggestedName);
/// <summary>同名配方导入的用户选择。</summary>
public enum ImportConflictChoice { Cancel, Overwrite, SaveAsNew }
@ -634,7 +634,7 @@ public class SopPageViewModel : ViewModelBase
}
var names = DesktopPlatform.Recipes.Names().Select(name => name + ".yaml").ToList();
foreach (var name in names)
SopHelper.Engine.Training.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(name)));
SopHelper.Engine.Recipes.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(name)));
_refreshingRecipes = true;
try
{
@ -1062,7 +1062,6 @@ public class SopPageViewModel : ViewModelBase
_runtimeOptions.Apply(config);
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec)); RaisePropertyChanged(nameof(DjevTimeoutMs));
config.Sop.Model = null;
_engine.Load(config);
var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
@ -1157,7 +1156,7 @@ public class SopPageViewModel : ViewModelBase
StepElapsedText = FormatDuration(statistics.StepElapsed);
AverageDurationText = FormatDuration(statistics.AverageDuration);
StandardDurationText = FormatDuration(!string.IsNullOrWhiteSpace(recipe) && Recipes.Contains(recipe)
? SopHelper.Engine.Training.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(name)) : TimeSpan.Zero);
? SopHelper.Engine.Recipes.SopStandardVideoDuration.Get(DesktopPlatform.Recipes.DirectoryFor(name)) : TimeSpan.Zero);
foreach (var stepCard in StepCards)
{
UpdateStepCounts(stepCard, _engine.Statistics);

View File

@ -6,7 +6,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Training;
namespace SopHelper.Engine.Recipes;
/// <summary>
/// 配方包(<c>.bwsrecipe</c>,zip 容器)的导出、检查与导入。

View File

@ -0,0 +1,206 @@
// 配方工作区:统一配置与关联数据的目录、导入迁移、路径修正及可回退的删除归档。
using System.Text.Json;
using System.Text.Json.Nodes;
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Recipes;
/// <summary>配方设置及其全部数据的统一存储入口。</summary>
public sealed class RecipeWorkspace(string root)
{
public string Root { get; } = Path.GetFullPath(root);
public string RecipesDirectory => Path.Combine(Root, "recipes");
public string DeletedRecipesDirectory => Path.Combine(Root, "workspace", "deleted-recipes");
private bool WasDeleted(string name) => Directory.Exists(Path.Combine(DeletedRecipesDirectory, name));
/// <summary>移出活动配方并保留整目录备份;归档目录也阻止下次启动重新导入旧配方。</summary>
public string Delete(string name)
{
var source = Path.GetFullPath(DirectoryFor(name));
var container = Path.GetFullPath(Path.Combine(DeletedRecipesDirectory, name));
var destination = Path.Combine(container, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N"));
if (!IsWithin(source, RecipesDirectory) || !IsWithin(destination, DeletedRecipesDirectory))
throw new IOException("配方删除路径超出工作区");
if (!File.Exists(ConfigPath(name))) throw new FileNotFoundException("配方不存在,无法删除", ConfigPath(name));
CheckDirectoryLinks(source); CheckDirectoryLinks(container);
var existed = Directory.Exists(container);
Directory.CreateDirectory(container);
try { Directory.Move(source, destination); }
catch
{
if (!existed && !Directory.EnumerateFileSystemEntries(container).Any()) Directory.Delete(container);
throw;
}
return destination;
}
/// <summary>检查工作区内的路径祖先是否包含重解析点,避免归档操作越过实际目录边界。</summary>
private void CheckDirectoryLinks(string path)
{
for (var directory = new DirectoryInfo(path); directory is not null && IsWithin(directory.FullName, Root); directory = directory.Parent)
if (directory.Exists && (directory.Attributes & FileAttributes.ReparsePoint) != 0)
throw new IOException("配方目录或备份目录包含链接,无法直接删除");
}
/// <summary>先校验配方名称,再生成工作区内的配方目录路径。</summary>
public string DirectoryFor(string name)
{
if (GetNameError(name) is { } error) throw new ArgumentException(error, nameof(name));
return Path.Combine(RecipesDirectory, name);
}
/// <summary>校验跨平台文件名限制、系统保留名及 UTF-8 文件名长度;合法时返回 null。</summary>
public static string? GetNameError(string name)
{
if (string.IsNullOrWhiteSpace(name)) return "配方名不能为空";
if (name.Any(c => c < 32 || "<>:\"/\\|?*".Contains(c)))
return "配方名不能包含 < > : \" / \\ | ? * 或控制字符";
if (name.EndsWith('.') || name.EndsWith(' ')) return "配方名不能以空格或句点结尾";
var stem = name.Split('.')[0].TrimEnd(' ').ToUpperInvariant();
if (stem is "CON" or "PRN" or "AUX" or "NUL" ||
(stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) && "123456789¹²³".Contains(stem[3])))
return "配方名不能使用系统保留名称(如 CON、NUL、COM1、LPT1)";
if (System.Text.Encoding.UTF8.GetByteCount(name + ".yaml") > 255)
return "配方名过长,请缩短名称";
return null;
}
public string ConfigPath(string name) => Path.Combine(DirectoryFor(name), name + ".yaml");
public IEnumerable<string> Names() => Directory.Exists(RecipesDirectory)
? Directory.GetDirectories(RecipesDirectory).Select(Path.GetFileName).OfType<string>()
.Where(n => File.Exists(ConfigPath(n))).OrderBy(n => n)
: [];
public static bool IsWithin(string path, string directory) =>
Path.GetFullPath(path).StartsWith(Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>一次性复制旧数据并修正路径。保留旧文件供回退,后续只使用新目录。</summary>
public void ImportFrom(string previousRoot)
{
var previous = new RecipeWorkspace(previousRoot);
foreach (var name in previous.Names())
{
var source = previous.DirectoryFor(name);
var destination = DirectoryFor(name);
if (File.Exists(ConfigPath(name)) || WasDeleted(name)) continue;
var staging = destination + ".migrating";
CopyTree(source, staging);
// 旧关联文件按原样复制,迁移只解析当前使用的配方配置。
var stagedConfig = Path.Combine(staging, name + ".yaml");
var config = SopConfigLoader.Load(stagedConfig);
config.Sop.Name = name;
RemapCompletionDirectories(config, source, destination);
SopConfigLoader.Save(config, stagedConfig);
// 配方文件最后发布,已有活动配方优先。
if (Directory.Exists(destination))
{
File.Move(stagedConfig, stagedConfig + ".ready", true);
CopyTree(staging, destination);
File.Move(ConfigPath(name) + ".ready", ConfigPath(name));
if (!IsWithin(staging, RecipesDirectory)) throw new IOException("迁移临时目录超出配方目录");
Directory.Delete(staging, true);
}
else Directory.Move(staging, destination);
}
}
/// <summary>从旧的散放目录复制并修正路径。</summary>
/// <remarks>初始化现有配方存储并接入旧目录,保持已存在的活动配方及删除记录的优先级。</remarks>
public void Initialize(params string[] legacyConfigDirectories)
{
Directory.CreateDirectory(RecipesDirectory);
var configs = legacyConfigDirectories.Where(Directory.Exists).Distinct()
.SelectMany(d => Directory.GetFiles(d, "*.yaml"))
.GroupBy(Path.GetFileNameWithoutExtension);
foreach (var group in configs)
{
var name = group.Key!;
var destination = DirectoryFor(name);
var configPath = ConfigPath(name);
if (File.Exists(configPath))
{
NormalizeName(configPath, name);
continue;
}
if (WasDeleted(name)) continue;
Directory.CreateDirectory(destination);
var source = group.OrderByDescending(File.GetLastWriteTimeUtc).First();
var oldStandardVideo = Path.Combine(Root, "workspace", "training", name, "sop_stand");
if (Directory.Exists(oldStandardVideo))
CopyTree(oldStandardVideo, Path.Combine(destination, "sop_stand"));
var config = SopConfigLoader.Load(source);
config.Sop.Name = name;
// 配方文件最后落位;中断重试时会复用已复制的标准视频。
SopConfigLoader.Save(config, configPath + ".migrating");
File.Move(configPath + ".migrating", configPath);
}
foreach (var name in Names()) NormalizeName(ConfigPath(name), name);
RefreshLocation();
}
private void RefreshLocation()
{
var marker = Path.Combine(RecipesDirectory, ".location.json");
var previous = File.Exists(marker) ? JsonNode.Parse(File.ReadAllText(marker))?["recipesDirectory"]?.GetValue<string>() : null;
if (!string.IsNullOrWhiteSpace(previous) && !Path.GetFullPath(previous).Equals(RecipesDirectory, StringComparison.OrdinalIgnoreCase))
{
foreach (var name in Names())
{
var path = ConfigPath(name);
var config = SopConfigLoader.Load(path);
var oldDirectory = Path.Combine(previous, name);
if (!RemapCompletionDirectories(config, oldDirectory, DirectoryFor(name))) continue;
SopConfigLoader.Save(config, path + ".tmp");
File.Move(path + ".tmp", path, true);
}
}
WriteJson(marker,new JsonObject { ["recipesDirectory"] = RecipesDirectory });
}
private static void NormalizeName(string path, string name)
{
var config = SopConfigLoader.Load(path);
if (config.Sop.Name == name) return;
config.Sop.Name = name;
SopConfigLoader.Save(config, path + ".tmp");
File.Move(path + ".tmp", path, true);
}
private static void CopyTree(string source, string destination)
{
if (IsWithin(destination, source)) throw new IOException("导入目录不能包含配方目标目录:" + source);
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source))
{
var target = Path.Combine(destination, Path.GetFileName(file));
if (!File.Exists(target)) File.Copy(file, target);
}
foreach (var child in Directory.GetDirectories(source))
CopyTree(child, Path.Combine(destination, Path.GetFileName(child)));
}
/// <summary>仅迁移旧配方目录内的绝对完成图路径,保留相对路径和工位自定义位置。</summary>
private static bool RemapCompletionDirectories(SopConfig config, string source, string destination)
{
var changed = false;
foreach (var step in config.Sop.Steps)
{
var path = step.CompletionImageDirectory;
if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path)) continue;
if (Path.GetFullPath(path).Equals(source, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
step.CompletionImageDirectory = destination;
else if (IsWithin(path, source))
step.CompletionImageDirectory = Path.Combine(destination, Path.GetRelativePath(source, path));
else continue;
changed = true;
}
return changed;
}
private static void WriteJson(string file, JsonNode? node)
{
var temporary = file + ".tmp";
File.WriteAllText(temporary, node?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, file, true);
}
}

View File

@ -4,7 +4,7 @@ using System.Collections.Concurrent;
using System.Text.Json;
using OpenCvSharp;
namespace SopHelper.Engine.Training;
namespace SopHelper.Engine.Recipes;
/// <summary>Persistent standard-video duration, read at most once per recipe per process.</summary>
public static class SopStandardVideoDuration

View File

@ -31,7 +31,7 @@ public class SopBody
/// <summary>说明</summary>
public string Description { get; set; } = "";
/// <summary>本配方统一维护的零件名称;null 表示旧配方尚未迁移。</summary>
/// <summary>旧配方的零件名称,仅用于保存和步骤交换。</summary>
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
public List<string>? Parts { get; set; }
@ -50,9 +50,6 @@ public class SopBody
/// <summary>步骤列表(按书写顺序执行)</summary>
public List<StepDef> Steps { get; set; } = [];
/// <summary>默认模型(缺省=只做手部与计时;写了就跑 YOLO)</summary>
public ModelDef? Model { get; set; }
}
/// <summary>
@ -110,21 +107,6 @@ public class RegionDef
public string Color { get; set; } = "#4CAF50";
}
/// <summary>
/// 模型定义
/// </summary>
public class ModelDef
{
/// <summary>onnx 路径(相对程序目录)</summary>
public string Path { get; set; } = "";
/// <summary>类别名,顺序必须与训练时一致</summary>
public List<string> Classes { get; set; } = [];
/// <summary>输入尺寸</summary>
public int InputSize { get; set; } = 640;
}
/// <summary>
/// 步骤定义
/// </summary>

View File

@ -39,6 +39,7 @@ public static partial class SopConfigLoader
.IgnoreUnmatchedProperties()
.Build();
// 旧 model 字段由 IgnoreUnmatchedProperties 跳过;旧触发方法保留给校验提示。
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
MigrateStepSettings(config);
@ -66,11 +67,6 @@ public static partial class SopConfigLoader
var yaml = serializer.Serialize(saved);
// 没配模型时别留一个空的 model: 节点——它会被读成"有 model 但 path 为空",
// 校验里那几条"需要模型"的提醒就哑了(本可空手告诉你的手已经空了)。
if (config.Sop.Model is null)
yaml = string.Join("\n", yaml.Split('\n').Where(l => l.TrimEnd() != " model:"));
return yaml.TrimEnd('\n') + "\n";
}
@ -108,7 +104,6 @@ public static partial class SopConfigLoader
/// </summary>
public static void Validate(SopConfig config)
{
config.Sop.Model = null; // 旧配方模型字段不再参与运行。
var supported = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
ConditionMethod.HandInRegion,

View File

@ -1,76 +0,0 @@
// 配方零件目录:汇总显式名称及步骤引用,并兼容旧训练项目或模型类别中的零件信息。
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("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;
}
}
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));
}
}

View File

@ -1,44 +0,0 @@
// 配方模型定位:只查找当前配方发布的训练模型,避免使用手填路径混入其他配方模型。
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;
}
}
}

View File

@ -1,338 +0,0 @@
// 配方工作区:统一配置与关联数据的目录、导入迁移、路径修正及可回退的删除归档。
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Training;
/// <summary>配方设置及其全部数据的统一存储入口。</summary>
public sealed class RecipeWorkspace(string root)
{
public string Root { get; } = Path.GetFullPath(root);
public string RecipesDirectory => Path.Combine(Root, "recipes");
public string DeletedRecipesDirectory => Path.Combine(Root, "workspace", "deleted-recipes");
private bool WasDeleted(string name) => Directory.Exists(Path.Combine(DeletedRecipesDirectory, name));
/// <summary>移出活动配方并保留整目录备份;归档目录也阻止下次启动重新导入旧配方。</summary>
public string Delete(string name)
{
var source = Path.GetFullPath(DirectoryFor(name));
var container = Path.GetFullPath(Path.Combine(DeletedRecipesDirectory, name));
var destination = Path.Combine(container, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N"));
if (!IsWithin(source, RecipesDirectory) || !IsWithin(destination, DeletedRecipesDirectory))
throw new IOException("配方删除路径超出工作区");
if (!File.Exists(ConfigPath(name))) throw new FileNotFoundException("配方不存在,无法删除", ConfigPath(name));
CheckDirectoryLinks(source); CheckDirectoryLinks(container);
var existed = Directory.Exists(container);
Directory.CreateDirectory(container);
try { Directory.Move(source, destination); }
catch
{
if (!existed && !Directory.EnumerateFileSystemEntries(container).Any()) Directory.Delete(container);
throw;
}
return destination;
}
/// <summary>检查工作区内的路径祖先是否包含重解析点,避免归档操作越过实际目录边界。</summary>
private void CheckDirectoryLinks(string path)
{
for (var directory = new DirectoryInfo(path); directory is not null && IsWithin(directory.FullName, Root); directory = directory.Parent)
if (directory.Exists && (directory.Attributes & FileAttributes.ReparsePoint) != 0)
throw new IOException("配方目录或备份目录包含链接,无法直接删除");
}
/// <summary>先校验配方名称,再生成工作区内的配方目录路径。</summary>
public string DirectoryFor(string name)
{
if (GetNameError(name) is { } error) throw new ArgumentException(error, nameof(name));
return Path.Combine(RecipesDirectory, name);
}
/// <summary>校验跨平台文件名限制、系统保留名及 UTF-8 文件名长度;合法时返回 null。</summary>
public static string? GetNameError(string name)
{
if (string.IsNullOrWhiteSpace(name)) return "配方名不能为空";
if (name.Any(c => c < 32 || "<>:\"/\\|?*".Contains(c)))
return "配方名不能包含 < > : \" / \\ | ? * 或控制字符";
if (name.EndsWith('.') || name.EndsWith(' ')) return "配方名不能以空格或句点结尾";
var stem = name.Split('.')[0].TrimEnd(' ').ToUpperInvariant();
if (stem is "CON" or "PRN" or "AUX" or "NUL" ||
(stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) && "123456789¹²³".Contains(stem[3])))
return "配方名不能使用系统保留名称(如 CON、NUL、COM1、LPT1)";
if (System.Text.Encoding.UTF8.GetByteCount(name + ".yaml") > 255)
return "配方名过长,请缩短名称";
return null;
}
public string ConfigPath(string name) => Path.Combine(DirectoryFor(name), name + ".yaml");
public IEnumerable<string> Names() => Directory.Exists(RecipesDirectory)
? Directory.GetDirectories(RecipesDirectory).Select(Path.GetFileName).OfType<string>()
.Where(n => File.Exists(ConfigPath(n))).OrderBy(n => n)
: [];
public static bool IsWithin(string path, string directory) =>
Path.GetFullPath(path).StartsWith(Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>配方内文件直接复用;外部同名异内容文件使用来源路径摘要区分,避免静默覆盖素材。</summary>
public string ImportFile(string name, string source, string subdirectory)
{
source = Path.GetFullPath(source);
var recipe = DirectoryFor(name);
if (IsWithin(source, recipe)) return source;
if (!File.Exists(source)) throw new FileNotFoundException("配方关联文件不存在", source);
var targetDirectory = Path.Combine(recipe, subdirectory);
Directory.CreateDirectory(targetDirectory);
var target = Path.Combine(targetDirectory, Path.GetFileName(source));
if (File.Exists(target) && !SameContent(source, target))
{
var suffix = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source)))[..10];
target = Path.Combine(targetDirectory, Path.GetFileNameWithoutExtension(source) + "-" + suffix + Path.GetExtension(source));
if (File.Exists(target) && !SameContent(source, target))
throw new IOException("配方中已有同名但内容不同的文件:" + target);
}
if (!File.Exists(target)) File.Copy(source, target);
return target;
}
private static bool SameContent(string first, string second)
{
if (new FileInfo(first).Length != new FileInfo(second).Length) return false;
using var a = File.OpenRead(first); using var b = File.OpenRead(second);
return SHA256.HashData(a).SequenceEqual(SHA256.HashData(b));
}
/// <summary>复制旧标注项目及关联文件到当前配方,并重写项目中的目录与视频引用。</summary>
public string ImportProject(string name, string projectPath)
{
var recipe = DirectoryFor(name);
projectPath = Path.GetFullPath(projectPath);
if (IsWithin(projectPath, recipe)) return projectPath;
var legacy = Path.Combine(Root, "workspace", "training", name);
if (IsWithin(projectPath, legacy))
{
var migrated = Path.Combine(recipe, Path.GetRelativePath(legacy, projectPath));
if (File.Exists(migrated)) return migrated;
}
var source = Path.GetDirectoryName(projectPath)!;
var key = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(projectPath)))[..12];
var destination = Path.Combine(recipe, "parts", "import-" + key);
var target = Path.Combine(destination, "project.json");
if (File.Exists(target)) return target;
CopyTree(source, destination);
var data = JsonNode.Parse(File.ReadAllText(target))!;
RewritePaths(data, new() { [source] = destination });
data["recipeName"] = name; data["recipeDirectory"] = recipe;
var video = data["video"]?.GetValue<string>();
if (!string.IsNullOrWhiteSpace(video) && File.Exists(video)) data["video"] = ImportFile(name, video, "recordings");
WriteJson(target, data);
return target;
}
/// <summary>一次性复制旧数据并修正路径。保留旧文件供回退,后续只使用新目录。</summary>
public void ImportFrom(string previousRoot)
{
var previous = new RecipeWorkspace(previousRoot);
foreach (var name in previous.Names())
{
var source = previous.DirectoryFor(name);
var destination = DirectoryFor(name);
if (File.Exists(ConfigPath(name)) || WasDeleted(name)) continue;
var staging = destination + ".migrating";
CopyTree(source, staging);
var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [source] = destination };
foreach (var file in Directory.GetFiles(staging, "*.json", SearchOption.AllDirectories))
{
var node = JsonNode.Parse(File.ReadAllText(file));
RewritePaths(node, mappings);
WriteJson(file, node);
}
foreach (var yaml in Directory.GetFiles(staging, "data.yaml", SearchOption.AllDirectories))
File.WriteAllText(yaml, File.ReadAllText(yaml).Replace(source.Replace('\\', '/'), destination.Replace('\\', '/')));
var stagedConfig = Path.Combine(staging, name + ".yaml");
var config = SopConfigLoader.Load(stagedConfig);
config.Sop.Name = name;
if (config.Sop.Model is { Path.Length: > 0 } model) model.Path = Remap(model.Path, mappings);
SopConfigLoader.Save(config, stagedConfig);
// Keep a complete recipe as the publication unit; existing runtime recipes are authoritative.
if (Directory.Exists(destination))
{
File.Move(stagedConfig, stagedConfig + ".ready", true);
CopyTree(staging, destination);
File.Move(ConfigPath(name) + ".ready", ConfigPath(name));
if (!IsWithin(staging, RecipesDirectory)) throw new IOException("迁移临时目录超出配方目录");
Directory.Delete(staging, true);
}
else Directory.Move(staging, destination);
}
}
/// <summary>从旧的散放目录复制并修正路径。</summary>
/// <remarks>初始化现有配方存储并接入旧目录,保持已存在的活动配方及删除记录的优先级。</remarks>
public void Initialize(params string[] legacyConfigDirectories)
{
Directory.CreateDirectory(RecipesDirectory);
var configs = legacyConfigDirectories.Where(Directory.Exists).Distinct()
.SelectMany(d => Directory.GetFiles(d, "*.yaml"))
.GroupBy(Path.GetFileNameWithoutExtension);
foreach (var group in configs)
{
var name = group.Key!;
var destination = DirectoryFor(name);
var configPath = ConfigPath(name);
if (File.Exists(configPath))
{
NormalizeName(configPath, name);
continue;
}
if (WasDeleted(name)) continue;
Directory.CreateDirectory(destination);
var source = group.OrderByDescending(File.GetLastWriteTimeUtc).First();
var oldTraining = Path.Combine(Root, "workspace", "training", name);
var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [oldTraining] = destination };
if (Directory.Exists(oldTraining)) CopyTree(oldTraining, destination);
var registry = Path.Combine(destination, "recipe-training.json");
if (File.Exists(registry))
{
var projects = JsonNode.Parse(File.ReadAllText(registry))?["projects"]?.AsArray();
foreach (var project in projects ?? [])
{
var original = project?.GetValue<string>();
if (string.IsNullOrWhiteSpace(original) || !File.Exists(original) || IsWithin(original, oldTraining)) continue;
var imported = ImportProject(name, original);
mappings[Path.GetDirectoryName(original)!] = Path.GetDirectoryName(imported)!;
}
}
var settings = Path.Combine(Root, "workspace", "settings.json");
if (File.Exists(settings) && !File.Exists(Path.Combine(destination, "training-settings.json")))
File.Copy(settings, Path.Combine(destination, "training-settings.json"));
// 自定义训练输出目录也迁入配方,避免最新模型仍指向外部目录。
var latestPath = Path.Combine(destination, "latest-model.json");
if (File.Exists(latestPath))
{
var latest = JsonNode.Parse(File.ReadAllText(latestPath))!;
var run = latest["runDirectory"]?.GetValue<string>();
if (!string.IsNullOrEmpty(run) && Directory.Exists(run) && !IsWithin(run, oldTraining) && !IsWithin(run, destination))
{
var target = Path.Combine(destination, "runs", Path.GetFileName(run));
CopyTree(run, target); mappings[run] = target;
}
}
var config = SopConfigLoader.Load(source);
config.Sop.Name = name;
if (config.Sop.Model is { Path.Length: > 0 } model)
{
var original = model.Path;
var candidates = new[] { original, Path.Combine(Path.GetDirectoryName(source)!, "..", "..", original), Path.Combine(Root, original) };
var existing = candidates.Where(Path.IsPathRooted).FirstOrDefault(File.Exists);
if (existing is not null)
model.Path = Path.GetRelativePath(destination, ImportFile(name, existing, "models"));
}
// Copy each referenced video; frame/image paths stay relative to their annotation project.
foreach (var project in Directory.GetFiles(destination, "project.json", SearchOption.AllDirectories))
{
var data = JsonNode.Parse(File.ReadAllText(project))!;
var video = data["video"]?.GetValue<string>();
if (!string.IsNullOrWhiteSpace(video) && File.Exists(video))
mappings[video] = ImportFile(name, video, "recordings");
}
foreach (var file in Directory.GetFiles(destination, "*.json", SearchOption.AllDirectories))
{
var node = JsonNode.Parse(File.ReadAllText(file));
RewritePaths(node, mappings);
if (Path.GetFileName(file) == "project.json" && node is JsonObject project)
{ project["recipeName"] = name; project["recipeDirectory"] = destination; }
WriteJson(file, node);
}
foreach (var yaml in Directory.GetFiles(destination, "data.yaml", SearchOption.AllDirectories))
{
var text = File.ReadAllText(yaml);
foreach (var mapping in mappings)
text = text.Replace(mapping.Key.Replace('\\', '/'), mapping.Value.Replace('\\', '/'));
File.WriteAllText(yaml, text);
}
// The config is the commit marker: interrupted migration is safe to retry.
SopConfigLoader.Save(config, configPath + ".migrating");
File.Move(configPath + ".migrating", configPath);
}
foreach (var name in Names()) NormalizeName(ConfigPath(name), name);
RefreshLocation();
}
private void RefreshLocation()
{
var marker = Path.Combine(RecipesDirectory, ".location.json");
var previous = File.Exists(marker) ? JsonNode.Parse(File.ReadAllText(marker))?["recipesDirectory"]?.GetValue<string>() : null;
if (!string.IsNullOrWhiteSpace(previous) && !Path.GetFullPath(previous).Equals(RecipesDirectory, StringComparison.OrdinalIgnoreCase))
{
var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [previous] = RecipesDirectory };
foreach (var name in Names())
{
var directory = DirectoryFor(name);
foreach (var json in Directory.GetFiles(directory, "*.json", SearchOption.AllDirectories))
{
var node = JsonNode.Parse(File.ReadAllText(json));RewritePaths(node,mappings);WriteJson(json,node);
}
foreach (var yaml in Directory.GetFiles(directory, "data.yaml", SearchOption.AllDirectories))
File.WriteAllText(yaml,File.ReadAllText(yaml).Replace(previous.Replace('\\','/'),RecipesDirectory.Replace('\\','/')));
var config=SopConfigLoader.Load(ConfigPath(name));
if(config.Sop.Model is { Path.Length: > 0 } model) model.Path=Remap(model.Path,mappings);
SopConfigLoader.Save(config,ConfigPath(name)+".tmp");File.Move(ConfigPath(name)+".tmp",ConfigPath(name),true);
}
}
WriteJson(marker,new JsonObject { ["recipesDirectory"] = RecipesDirectory });
}
private static void NormalizeName(string path, string name)
{
var config = SopConfigLoader.Load(path);
if (config.Sop.Name == name) return;
config.Sop.Name = name;
SopConfigLoader.Save(config, path + ".tmp");
File.Move(path + ".tmp", path, true);
}
private static void CopyTree(string source, string destination)
{
if (IsWithin(destination, source)) throw new IOException("导入目录不能包含配方目标目录:" + source);
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source))
{
var target = Path.Combine(destination, Path.GetFileName(file));
if (!File.Exists(target)) File.Copy(file, target);
}
foreach (var child in Directory.GetDirectories(source))
CopyTree(child, Path.Combine(destination, Path.GetFileName(child)));
}
private static string Remap(string value, Dictionary<string, string> mappings)
{
foreach (var (source, target) in mappings.OrderByDescending(p => p.Key.Length))
if (value.Equals(source, StringComparison.OrdinalIgnoreCase)) return target;
else if (value.StartsWith(source.TrimEnd('\\', '/') + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return target + value[source.Length..];
return value;
}
private static void RewritePaths(JsonNode? node, Dictionary<string, string> mappings)
{
if (node is JsonObject obj)
foreach (var (key, value) in obj.ToArray())
{
if (value is JsonValue v && v.TryGetValue<string>(out var text)) obj[key] = Remap(text, mappings);
else RewritePaths(value, mappings);
var mapped = Remap(key, mappings);
if (mapped != key) { var child = obj[key]; obj.Remove(key); obj[mapped] = child; }
}
else if (node is JsonArray array)
for (var i = 0; i < array.Count; i++)
if (array[i] is JsonValue v && v.TryGetValue<string>(out var text)) array[i] = Remap(text, mappings);
else RewritePaths(array[i], mappings);
}
private static void WriteJson(string file, JsonNode? node)
{
var temporary = file + ".tmp";
File.WriteAllText(temporary, node?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, file, true);
}
}

View File

@ -9,7 +9,7 @@ using Prism.Ioc;
using Prism.Dialogs;
using SopHelper;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.Models;
using SopHelper.SopVideo;
using SopHelper.VVMs.SopPage;
@ -485,9 +485,9 @@ internal static class Smoke
var config = new SopHelper.Engine.Sop.SopConfig(); config.Sop.Name = name;
config.Sop.Steps = [new SopHelper.Engine.Sop.StepDef { Id = 1, Name = "导入检查", Description = "步骤说明", Detection = new SopHelper.Engine.Sop.StepCondition { Method = SopHelper.Engine.Sop.ConditionMethod.TimeElapsed } }];
SopHelper.Engine.Sop.SopConfigLoader.Save(config, store.ConfigPath(name));
var package = SopHelper.Engine.Training.RecipePackage.Export(store, name, Path.Combine(store.Root, name)).Path;
var package = SopHelper.Engine.Recipes.RecipePackage.Export(store, name, Path.Combine(store.Root, name)).Path;
var directories = Directory.GetDirectories(store.RecipesDirectory).Length;
var info = SopHelper.Engine.Training.RecipePackage.Inspect(package);
var info = SopHelper.Engine.Recipes.RecipePackage.Inspect(package);
var prompt = new SopPageViewModel.ImportConflict(package, info, name + "-2");
var confirm = sop.ConfirmImportConflictAsync ?? throw new Exception("运行设置未接上同名配方确认");
void Click(string label) => lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.ImportRecipeConflictDialog>().Single()
@ -1288,7 +1288,6 @@ internal static class Smoke
finally{settingsWindow.Close();}
sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
Check(engine.Config.Sop.Model is null,"Pure hand/AI recipe skips YOLO loading");
var fake=new UiVisionDecision();engine.VisionDecisionClient=fake;
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
async Task Emit(Scalar color)

View File

@ -5,7 +5,7 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
internal static class Program
{
@ -36,12 +36,60 @@ internal static class Program
private static void Run()
{
LegacyWorkspace();
RoundTrip();
OverwriteAndRename();
RejectedPackages();
MissingStandardVideo();
}
/// <summary>旧训练文件即使已损坏,也不应阻塞配方和标准视频迁移。</summary>
private static void LegacyWorkspace()
{
const string name = "旧配方";
var source = new RecipeWorkspace(Path.Combine(Root, "legacy"));
var target = new RecipeWorkspace(Path.Combine(Root, "migrated"));
var standard = Path.Combine(source.Root, "workspace", "training", name, "sop_stand");
var history = Path.Combine(Path.GetDirectoryName(standard)!, "parts", "project.json");
var configs = Path.Combine(source.Root, "configs");
Directory.CreateDirectory(standard);
Directory.CreateDirectory(Path.GetDirectoryName(history)!);
Directory.CreateDirectory(configs);
File.WriteAllText(history, "旧标注文件内容,即使不是有效 JSON 也保留");
File.WriteAllBytes(Path.Combine(standard, "sop.avi"), [1, 2, 3]);
File.WriteAllText(Path.Combine(configs, name + ".yaml"), """
sop:
name: 旧配方
model: { path: old.onnx }
parts: [支架]
steps:
- id: 1
description: 放好支架
must_keep: [支架]
detection: { method: object_present, target_object: 支架 }
""");
source.Initialize(configs);
var config = SopConfigLoader.Load(source.ConfigPath(name));
Check(config.Warnings.Any(w => w.Contains("已移除或不支持")) && config.Sop.Steps[0].MustKeep.SequenceEqual(new[] { "支架" }),
"旧物体条件继续提示迁移并保留物料描述");
Check(!File.ReadAllText(source.ConfigPath(name)).Contains("model:") &&
File.Exists(Path.Combine(source.DirectoryFor(name), "sop_stand", "sop.avi")) &&
!Directory.Exists(Path.Combine(source.DirectoryFor(name), "parts")) && File.Exists(history),
"散放旧配方只迁移标准视频,历史标注文件保留在原处");
var oldCompletion = Path.Combine(source.DirectoryFor(name), "done");
config.Sop.Steps[0].CompletionImageDirectory = oldCompletion;
SopConfigLoader.Save(config, source.ConfigPath(name));
var archivedRecord = Path.Combine(source.DirectoryFor(name), "recipe-training.json");
File.WriteAllText(archivedRecord, "历史文件按字节复制");
target.ImportFrom(source.Root);
target.Initialize();
var imported = SopConfigLoader.Load(target.ConfigPath(name));
Check(imported.Sop.Steps[0].CompletionImageDirectory == Path.Combine(target.DirectoryFor(name), "done") &&
File.ReadAllBytes(Path.Combine(target.DirectoryFor(name), "recipe-training.json")).SequenceEqual(File.ReadAllBytes(archivedRecord)),
"整目录导入时迁移完成图路径,历史文件按原样保留");
}
/// <summary>导出→检查→导入的往返:内容一致、路径改写、不残留暂存目录。</summary>
private static void RoundTrip()
{

View File

@ -10,7 +10,7 @@ using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.SopVideo;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.VVMs.RecipeEditor;
using Prism.Dialogs;
using Avalonia.Controls.Primitives;

View File

@ -8,7 +8,7 @@ using Avalonia.VisualTree;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.VVMs.RecipeEditor;
using Window = Avalonia.Controls.Window;

View File

@ -5,7 +5,7 @@ using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.SopVideo;
using SopHelper.VVMs.RecipeEditor;
using Window = Avalonia.Controls.Window;

View File

@ -9,7 +9,7 @@ using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.SopVideo;
using SopHelper.VVMs.RecipeEditor;
using SopHelper.VVMs.SopPage;
@ -34,6 +34,7 @@ internal static class Program
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
if (args.Contains("--optimization-only")) { OptimizeStepsChecks.Run(); return; }
CheckLegacyRecipeRoundTrip();
// 单独验证标准视频链路,便于定位回放与流程回测问题。
if (args.Contains("--standard-video-only"))
{
@ -60,6 +61,32 @@ internal static class Program
}
}
/// <summary>编辑往返保留旧规则内容,让使用者能看到迁移提示并手动改写工艺。</summary>
private static void CheckLegacyRecipeRoundTrip()
{
var config = SopConfigLoader.Parse("""
sop:
name: 旧工艺
model: { path: old.onnx }
parts: [支架, 螺丝]
steps:
- id: 1
description: 放置支架
must_keep: [支架]
required_objects: [螺丝]
detection: { method: object_present, target_object: 支架 }
""");
var node = RecipeNode.From(config, config.Sop.Name, false);
var yaml = SopConfigLoader.ToYaml(node.ToConfig());
var restored = SopConfigLoader.Parse(yaml);
var step = restored.Sop.Steps.Single();
Check(!yaml.Contains("model:") && restored.Sop.Parts!.SequenceEqual(new[] { "支架", "螺丝" })
&& step.MustKeep.SequenceEqual(new[] { "支架" }) && step.RequiredObjects.SequenceEqual(new[] { "螺丝" })
&& step.Detection is { Method: "object_present", TargetObject: "支架" }
&& restored.Warnings.Any(w => w.Contains("已移除或不支持")),
"旧配方经编辑器往返保留零件与物体条件,并继续提示迁移");
}
private static void CheckSequenceEditor()
{
Check(new StepNode().AiCheckWindowMs == 10000,

View File

@ -4,7 +4,7 @@ using Avalonia.Threading;
using Avalonia.VisualTree;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.VVMs.RecipeEditor;
internal static class RecipeCloseChecks

View File

@ -2,7 +2,7 @@ using Avalonia.Threading;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.Engine.Recipes;
using SopHelper.VVMs.RecipeEditor;
internal static class StandardVideoImportChecks

View File

@ -18,11 +18,11 @@ sop:
description: 把盒子放好
detection: { method: object_present, target_object: 盒子 }
""");
Check(retired.Sop.Model is null && retired.Warnings.Any(w=>w.Contains("已移除或不支持")), "旧模型绑定必须忽略,旧物体规则提示改用手部规则");
Check(!SopConfigLoader.ToYaml(retired).Contains("model:") && retired.Warnings.Any(w=>w.Contains("已移除或不支持")), "旧模型绑定必须忽略,旧物体规则提示改用手部规则");
var sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "hand-ai.yaml"));
Check(sample.Warnings.Count == 0 && sample.Sop.Model is null && sample.Sop.Steps.All(s => s.AiConfirmation is not null), "示例配方必须有效且不依赖 YOLO");
Check(sample.Warnings.Count == 0 && sample.Sop.Steps.All(s => s.AiConfirmation is not null), "示例配方必须有效且不依赖 YOLO");
var d3Sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "d3-workflow.yaml"));
Check(d3Sample.Warnings.Count == 0 && d3Sample.Sop.Model is null && d3Sample.Sop.Steps.All(s => s.AiConfirmation?.ImageRegion == "work"), "D3 示例必须有效、使用区域取图且不依赖 YOLO");
Check(d3Sample.Warnings.Count == 0 && d3Sample.Sop.Steps.All(s => s.AiConfirmation?.ImageRegion == "work"), "D3 示例必须有效、使用区域取图且不依赖 YOLO");
var config = SopConfigLoader.Parse("""
sop:
name: 手部 AI 测试