aisop/tests/PartCatalog.Smoke/Program.cs

128 lines
10 KiB
C#

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 = ["螺丝"] }];
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, "装配");
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.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[] { "支架", "螺丝" }), "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");
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();
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();
var projectDirectory = Path.Combine(directory, "parts", "video"); Directory.CreateDirectory(projectDirectory);
var project = new TrainingProject { AnnotationVersion = 2, FilePath = Path.Combine(projectDirectory, "project.json"), Name = "装配视频", RecipeName = "装配", RecipeDirectory = directory, Width = 100, Height = 100, Frames = [new FrameAnnotation { Index = 0, Image = "frame.png", Objects = [new() {Label="支架", Box=[0,0,90,90]}, new() {Label="螺丝", Box=[20,20,30,30]}] }] };
project.Save();
Check(PartCatalog.ProjectNames(directory).Contains("支架") && PartCatalog.ProjectNames(directory).Contains("螺丝") && !PartCatalog.ProjectNames(directory).Contains("装配视频"), "Multi-part annotation references use object labels instead of the video title");
var trainer = new MainViewModel(new WorkerClient()); trainer.RecipeName = "装配";
Check(trainer.PartNames.SequenceEqual(saved.Sop.Parts!), "Training offers the same catalog");
trainer.Load(project.FilePath);
Check(trainer.Label == "支架", "Loading a project selects its existing catalog part");
var training = new TrainingPage(trainer, null); var trainingWindow = new Window { Content = training, Width = 1180, Height = 820 }; trainingWindow.Show(); trainingWindow.UpdateLayout();
var targetPart = training.FindControl<ComboBox>("TrainingTargetPart")!;
Check(targetPart.SelectedItem?.ToString() == "支架", "Training offers a part selector after loading a project");
targetPart.SelectedItem = "螺丝";
Check(trainer.Label == "螺丝", "Annotation part can switch within a video");
trainer.RefreshPartNames();
Check(trainer.Label == "螺丝", "Catalog refresh preserves the selected annotation part");
trainingWindow.Close();
var other = new SopConfig(); other.Sop.Name = "另一配方"; other.Sop.Parts = ["外壳"];
Directory.CreateDirectory(storage.DirectoryFor(other.Sop.Name)); SopConfigLoader.Save(other, storage.ConfigPath(other.Sop.Name));
trainer.RecipeName = other.Sop.Name;
Check(trainer.PartNames.SequenceEqual(new[] { "外壳" }) && trainer.Label == "外壳" && trainer.Project is null, "Switching recipes clears the previous project and selects an available part");
var changed = SopConfigLoader.Load(storage.ConfigPath("装配")); changed.Sop.Parts!.Remove("支架"); changed.Sop.Steps.Clear();
try { PartCatalog.Validate(changed, directory); throw new Exception("Annotation reference was ignored"); }
catch (InvalidDataException error) { Check(error.Message.Contains("支架"), "Parts referenced only by annotation projects cannot be removed"); }
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();
}
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);
}
}