aisop/tests/Training.UiSmoke/Program.cs

113 lines
7.8 KiB
C#

using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SopHelper.Training;
using SopHelper.Engine.Training;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var app = new SopHelper.App(); app.InitializeComponent();
var model = new MainViewModel(new WorkerClient());
if (args.Length > 0) model.Load(Path.GetFullPath(args[0]));
var window = new TrainingPage(model, null);
var content = (FrameworkElement)window.Content;
window.Content = null;
content.DataContext = model;
content.Margin = new Thickness(0);
content.Width = 1404; content.Height = 844;
content.Measure(new Size(1404, 844)); content.Arrange(new Rect(0, 0, 1404, 844)); content.UpdateLayout();
content.Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
content.UpdateLayout();
if (content.ActualWidth < 1000) throw new Exception("Layout failed");
var image = new RenderTargetBitmap(1440, 880, 96, 96, PixelFormats.Pbgra32);
var visual = new DrawingVisual();
using (var drawing = visual.RenderOpen()) drawing.DrawRectangle(new SolidColorBrush(Color.FromRgb(16,24,32)), null, new Rect(0,0,1440,880));
image.Render(visual); image.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image));
var output = args.Length > 1 ? args[1] : Path.Combine(Path.GetTempPath(), "parttrainer-ui.png");
using (var stream = File.Create(output)) encoder.Save(stream);
Console.WriteLine("PASS: WPF resources, view model, preview layout rendered to " + output);
if (model.Project != null)
{
model.DrawBox([1,1,Math.Min(100,model.Project.Width), Math.Min(100,model.Project.Height)]);
if (model.SelectedFrame?.Prompt != true || model.SelectedFrame.Status != "reviewed") throw new Exception("Manual seed not saved");
model.ExcludeCommand.Execute();
if (model.SelectedFrame?.Box != null || model.SelectedFrame?.Prompt != false) throw new Exception("Exclusion failed");
model.NextCommand.Execute();
Console.WriteLine("PASS: manual correction persistence, exclusion, frame navigation");
}
TestApproveAll();
return 0;
}
private static void TestApproveAll()
{
var root = Path.Combine(Path.GetTempPath(), "parttrainer-review-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var bitmap = BitmapSource.Create(100,80,96,96,PixelFormats.Bgr24,null,new byte[100*80*3],300);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var image = File.Create(Path.Combine(root,"frame.png"))) encoder.Save(image);
var states = new[] { "auto", "auto", "excluded", "reviewed", "auto", "unlabeled" };
var project = new TrainingProject { FilePath = Path.Combine(root,"project.json"), Width = 100, Height = 80 };
for (var index = 0; index < states.Length; index++)
project.Frames.Add(new FrameAnnotation { Index = index, Image = "frame.png", Status = states[index],
Box = index == 1 ? null : [10,10,50,50], Prompt = index == 4 });
project.Save();
var weights = Path.Combine(root,"runs","test","weights","best.pt");
File.WriteAllText(Path.Combine(root,"latest-model.json"), System.Text.Json.JsonSerializer.Serialize(new
{ weights, runDirectory = Path.Combine(root,"runs","test"), metrics = new Dictionary<string,double> { ["metrics/mAP50(B)"] = 0.75 } }));
var model = new MainViewModel(new WorkerClient()); model.Load(project.FilePath,1);
if (model.LatestWeights != weights || !model.TrainingMetrics.Contains("0.7500")) throw new Exception("Training result did not reload");
TestModelPlayback(root,model.Python);
model.ApproveAllCommand.Execute();
var saved = TrainingProject.Load(project.FilePath);
var expected = new[] { "reviewed", "auto", "excluded", "reviewed", "reviewed", "unlabeled" };
if (!saved.Frames.Select(f => f.Status).SequenceEqual(expected)) throw new Exception("Batch review changed incorrect frames");
if (saved.Frames[0].Prompt || !saved.Frames[4].Prompt) throw new Exception("Batch review changed keyframe flags");
if (model.SelectedFrame?.Index != 1 || model.Frames[0].Display.Contains("待复核")) throw new Exception("Batch review did not refresh selection/list");
model.ApproveAllCommand.Execute();
if (model.Status != "没有带目标框的待复核帧") throw new Exception("Repeated batch review did not handle empty batch");
Console.WriteLine("PASS: batch review persistence, pending boxes only, negative/excluded/unlabeled preservation, keyframe preservation, selection refresh, repeated click");
}
finally { Directory.Delete(root,true); }
}
private static void TestModelPlayback(string root,string python)
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(Application.Current.Dispatcher));
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
Directory.CreateDirectory(Path.Combine(root,"tools"));
var image = Convert.ToBase64String(File.ReadAllBytes(Path.Combine(root,"frame.png")));
var payload = System.Text.Json.JsonSerializer.Serialize(new { message="检测画面", @event="test_frame", image,
frame=1,totalFrames=10,seconds=0.1,duration=1,processingFps=10, detections=new[] {new {label="零件",confidence=0.9}} });
File.WriteAllText(Path.Combine(root,"tools","worker.py"), "import time\nprint(" + System.Text.Json.JsonSerializer.Serialize(payload) + ",flush=True)\ntime.sleep(30)\n");
var test = new ModelTestViewModel(root,python) { VideoPath=Path.Combine(root,"frame.png"), ModelPath=Path.Combine(root,"frame.png") };
var window = new ModelTestWindow(test);
test.StartCommand.Execute();
var watch = System.Diagnostics.Stopwatch.StartNew();
void PumpUntil(Func<bool> ready)
{
while (!ready())
{
if (watch.Elapsed.TotalSeconds>15) throw new Exception("Playback test timed out: " + test.Status + test.Logs);
Application.Current.Dispatcher.Invoke(()=>{},System.Windows.Threading.DispatcherPriority.ApplicationIdle); Thread.Sleep(10);
}
}
PumpUntil(()=>test.Preview!=null || !test.IsBusy);
if (test.Preview==null || !test.Detections.Contains("90") || test.StartCommand.CanExecute()) throw new Exception("Playback state/targets missing: " + test.Status);
var view = (FrameworkElement)window.Content; window.Content=null; view.DataContext=test; view.Margin=new Thickness(0);
view.Width=1164;view.Height=760;view.Measure(new Size(1164,760));view.Arrange(new Rect(0,0,1164,760));view.UpdateLayout();
var rendered=new RenderTargetBitmap(1164,760,96,96,PixelFormats.Pbgra32); rendered.Render(view);
var encoder=new PngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(rendered));
using(var file=File.Create(Path.Combine(Path.GetTempPath(),"parttrainer-model-test.png"))) encoder.Save(file);
test.StopCommand.Execute();PumpUntil(()=>!test.IsBusy);
if(!test.StartCommand.CanExecute() || test.StopCommand.CanExecute()) throw new Exception("Playback stop did not restore controls");
var closed=false;window.Closed+=(_,_)=>closed=true;window.Close();PumpUntil(()=>closed);
Console.WriteLine("PASS: model testing window, streamed image/targets, start/stop controls, worker cancellation, window cleanup");
}
}