125 lines
11 KiB
C#
125 lines
11 KiB
C#
using SopHelper.Engine.Training;
|
|
using SopHelper.Engine.Sop;
|
|
using System.Text.Json.Nodes;
|
|
|
|
var root = Path.Combine(Path.GetTempPath(), "parttrainer-test-" + Guid.NewGuid().ToString("N"));
|
|
Directory.CreateDirectory(root);
|
|
try
|
|
{
|
|
var project = new TrainingProject { FilePath = Path.Combine(root, "project.json"), Name = "中文零件", Width = 640, Height = 480,
|
|
Frames = [new FrameAnnotation { Image = "frames/000000.jpg", Box = [10, 20, 100, 200], Status = "reviewed", Prompt = true }] };
|
|
project.Save();
|
|
var loaded = TrainingProject.Load(project.FilePath);
|
|
if (loaded.Name != project.Name || !loaded.Frames[0].Prompt || loaded.Frames[0].Box![2] != 100) throw new Exception("Project round trip failed");
|
|
foreach (var invalid in new double[][] { [-1,0,10,10], [0,0,0,10], [0,0,641,10], [double.NaN,0,1,1] })
|
|
{
|
|
try { loaded.ValidateBox(invalid); throw new Exception("Invalid box accepted"); }
|
|
catch (ArgumentException) { }
|
|
}
|
|
loaded.Frames[0].Image = "../outside.jpg"; loaded.Save();
|
|
try { TrainingProject.Load(loaded.FilePath); throw new Exception("Traversal accepted"); }
|
|
catch (InvalidDataException) { }
|
|
Console.WriteLine("PASS: project persistence, Unicode, invalid box rejection, path traversal rejection");
|
|
var storageRoot=Path.Combine(root,"layout");
|
|
var store=new RecipeWorkspace(storageRoot);
|
|
var legacyConfigs=Path.Combine(storageRoot,"configs","sop");Directory.CreateDirectory(legacyConfigs);
|
|
var legacyTraining=Path.Combine(storageRoot,"workspace","training","配方甲");
|
|
var part=Path.Combine(legacyTraining,"parts","part1");Directory.CreateDirectory(part);
|
|
var video=Path.Combine(root,"source.avi");File.WriteAllText(video,"video");
|
|
File.WriteAllText(Path.Combine(part,"frame.jpg"),"image");
|
|
var oldProject=new TrainingProject {FilePath=Path.Combine(part,"project.json"),RecipeName="配方甲",RecipeDirectory=legacyTraining,Name="零件甲",Video=video,Width=100,Height=100,
|
|
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};oldProject.Save();
|
|
var externalPart=Path.Combine(root,"external-part");Directory.CreateDirectory(externalPart);
|
|
File.WriteAllText(Path.Combine(externalPart,"frame.jpg"),"image");
|
|
var externalProject=new TrainingProject {FilePath=Path.Combine(externalPart,"project.json"),Name="零件乙",Video=video,Width=100,Height=100,
|
|
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};externalProject.Save();
|
|
var externalRun=Path.Combine(root,"external-run");Directory.CreateDirectory(externalRun);
|
|
var weights=Path.Combine(externalRun,"配方甲.pt");File.WriteAllText(weights,"weights");
|
|
var onnx=Path.ChangeExtension(weights,".onnx");File.WriteAllText(onnx,"model");
|
|
File.WriteAllText(Path.Combine(legacyTraining,"latest-model.json"),System.Text.Json.JsonSerializer.Serialize(new {weights,onnx,runDirectory=externalRun,recipeName="配方甲",classes=new[]{"零件甲"},imageSize=640}));
|
|
File.WriteAllText(Path.Combine(legacyTraining,"recipe-training.json"),new JsonObject { ["projects"]=new JsonArray(oldProject.FilePath,externalProject.FilePath),["labels"]=new JsonObject{[oldProject.FilePath]="零件甲",[externalProject.FilePath]="零件乙"},["classes"]=new JsonArray("零件甲","零件乙")}.ToJsonString());
|
|
var config=new SopConfig();config.Sop.Name="配方甲";config.Sop.Model=new ModelDef{Path=onnx};
|
|
SopConfigLoader.Save(config,Path.Combine(legacyConfigs,"配方甲.yaml"));
|
|
store.Initialize(legacyConfigs);
|
|
var recipe=store.DirectoryFor("配方甲");
|
|
var migratedProject=TrainingProject.Load(Path.Combine(recipe,"parts","part1","project.json"));
|
|
if(migratedProject.RecipeDirectory!=recipe||!RecipeWorkspace.IsWithin(migratedProject.Video,recipe)||!File.Exists(migratedProject.Video))throw new Exception("Project/video migration failed");
|
|
var latest=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"latest-model.json")))!;
|
|
if(!RecipeWorkspace.IsWithin(latest["weights"]!.GetValue<string>(),recipe)||!File.Exists(latest["onnx"]!.GetValue<string>()))throw new Exception("External training output was not migrated");
|
|
var registry=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"recipe-training.json")))!;
|
|
if(registry["projects"]![0]!.GetValue<string>()!=migratedProject.FilePath||registry["labels"]![migratedProject.FilePath]!.GetValue<string>()!="零件甲")throw new Exception("Registry references were not rebased");
|
|
var relocatedExternal=registry["projects"]![1]!.GetValue<string>();
|
|
if(!RecipeWorkspace.IsWithin(relocatedExternal,recipe)||TrainingProject.Load(relocatedExternal).RecipeDirectory!=recipe)throw new Exception("External annotation projects were not migrated");
|
|
var managedModel=SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Model!.Path;
|
|
if(Path.IsPathRooted(managedModel)||!File.Exists(Path.Combine(recipe,managedModel)))throw new Exception("Configured model was not localized");
|
|
File.WriteAllText(Path.Combine(legacyConfigs,"配方甲.yaml"),"obsolete");store.Initialize(legacyConfigs);
|
|
if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Migration overwrote managed settings");
|
|
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Migration modified original data");
|
|
foreach(var bad in new[]{"..","../escape","a/b","a\\b","配方:甲","配方*甲","配方?","配方\"","配方<","配方>","配方|","末尾 ","末尾.","CON","nul.txt","COM1","LPT9","COM¹","换\n行",new string('长',100)})
|
|
try{store.DirectoryFor(bad);throw new Exception("Unsafe recipe name accepted");}catch(ArgumentException){}
|
|
foreach(var good in new[]{"装配线A","配方.v1","配方 甲","COM10","普通配方(测试)"})
|
|
if(RecipeWorkspace.GetNameError(good) is not null)throw new Exception("Valid recipe name rejected: "+good);
|
|
var renamedDisplay=SopConfigLoader.Load(store.ConfigPath("配方甲"));renamedDisplay.Sop.Name="另一个显示名称";
|
|
SopConfigLoader.Save(renamedDisplay,store.ConfigPath("配方甲"));store.Initialize(legacyConfigs);
|
|
if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Existing recipe name differs from filename");
|
|
Console.WriteLine("PASS: Unified recipe migration, model/video copies, registry rebasing, independent config and safe names");
|
|
var portable=new RecipeWorkspace(Path.Combine(root,"portable"));portable.ImportFrom(storageRoot);
|
|
var portableRoot=portable.DirectoryFor("配方甲");
|
|
var portableRegistry=JsonNode.Parse(File.ReadAllText(Path.Combine(portableRoot,"recipe-training.json")))!;
|
|
var portableProject=TrainingProject.Load(portableRegistry["projects"]![0]!.GetValue<string>());
|
|
if(!RecipeWorkspace.IsWithin(portableProject.Video,portableRoot)||portableProject.RecipeDirectory!=portableRoot)throw new Exception("Portable recipe references source data");
|
|
var portableModel=JsonNode.Parse(File.ReadAllText(Path.Combine(portableRoot,"latest-model.json")))!;
|
|
if(!RecipeWorkspace.IsWithin(portableModel["weights"]!.GetValue<string>(),portableRoot))throw new Exception("Portable model references source data");
|
|
var portableConfig=SopConfigLoader.Load(portable.ConfigPath("配方甲"));portableConfig.Sop.Version="local-version";SopConfigLoader.Save(portableConfig,portable.ConfigPath("配方甲"));
|
|
portable.ImportFrom(storageRoot);
|
|
if(SopConfigLoader.Load(portable.ConfigPath("配方甲")).Sop.Version!="local-version")throw new Exception("Source recipe overwrote a runtime recipe");
|
|
Console.WriteLine("PASS: Runtime-directory migration rebases assets and preserves existing runtime recipes");
|
|
var relocated=new RecipeWorkspace(Path.Combine(root,"relocated"));
|
|
foreach(var file in Directory.GetFiles(store.RecipesDirectory,"*",SearchOption.AllDirectories))
|
|
{
|
|
var target=Path.Combine(relocated.RecipesDirectory,Path.GetRelativePath(store.RecipesDirectory,file));
|
|
Directory.CreateDirectory(Path.GetDirectoryName(target)!);File.Copy(file,target);
|
|
}
|
|
relocated.Initialize();
|
|
var relocatedRegistry=JsonNode.Parse(File.ReadAllText(Path.Combine(relocated.DirectoryFor("配方甲"),"recipe-training.json")))!;
|
|
var movedProject=TrainingProject.Load(relocatedRegistry["projects"]![0]!.GetValue<string>());
|
|
if(!RecipeWorkspace.IsWithin(movedProject.Video,relocated.RecipesDirectory)||!File.Exists(movedProject.Video))throw new Exception("Moving a complete runtime directory left stale source references");
|
|
Console.WriteLine("PASS: Moving the entire runtime directory automatically rebases recipe paths");
|
|
var archive=store.Delete("配方甲");
|
|
if(Directory.Exists(store.DirectoryFor("配方甲"))||!File.Exists(Path.Combine(archive,"配方甲.yaml"))||!Directory.Exists(Path.Combine(archive,"parts")))
|
|
throw new Exception("Recipe deletion failed to preserve its complete directory");
|
|
store.Initialize(legacyConfigs);store.ImportFrom(portable.Root);
|
|
if(File.Exists(store.ConfigPath("配方甲")))throw new Exception("Deleted recipe was automatically reimported");
|
|
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Deletion modified legacy/source data");
|
|
Directory.CreateDirectory(store.DirectoryFor("配方甲"));SopConfigLoader.Save(new SopConfig{Sop=new SopBody{Name="配方甲"}},store.ConfigPath("配方甲"));
|
|
if(!store.Names().Contains("配方甲"))throw new Exception("Deleted name could not be reused for a new recipe");
|
|
store.Delete("配方甲");
|
|
if(Directory.GetDirectories(Path.Combine(store.DeletedRecipesDirectory,"配方甲")).Length!=2)throw new Exception("Second deletion overwrote the first archive");
|
|
try{store.Delete("../escape");throw new Exception("Delete accepted traversal");}catch(ArgumentException){}
|
|
Console.WriteLine("PASS: Recipe deletion archives all data, blocks automatic reimport, allows name reuse and rejects unsafe paths");
|
|
if (args.Length > 0)
|
|
{
|
|
var script = Path.Combine(root, "worker.py");
|
|
File.WriteAllText(script, "import json,sys,time\nr=json.load(open(sys.argv[1]))\nprint('worker-ready',flush=True)\ntime.sleep(r.get('sleep',0))\nsys.exit(r.get('exit',0))\n");
|
|
var client = new WorkerClient();
|
|
var lines = new List<string>();
|
|
await client.RunAsync(args[0], script, new { sleep = 0 }, line => { lock(lines) lines.Add(line); }, CancellationToken.None);
|
|
if (!lines.Contains("worker-ready")) throw new Exception("Worker output was lost");
|
|
try
|
|
{
|
|
await client.RunAsync(args[0], script, new { exit = 2 }, _ => { }, CancellationToken.None);
|
|
throw new Exception("Worker exit failure was ignored");
|
|
}
|
|
catch (InvalidOperationException) { }
|
|
using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
|
try
|
|
{
|
|
await client.RunAsync(args[0], script, new { sleep = 60 }, _ => { }, cancel.Token);
|
|
throw new Exception("Worker cancellation was ignored");
|
|
}
|
|
catch (OperationCanceledException) { }
|
|
Console.WriteLine("PASS: real Python process output, exit failure, cancellation");
|
|
}
|
|
}
|
|
finally { Directory.Delete(root, true); }
|