313 lines
20 KiB
C#
313 lines
20 KiB
C#
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Headless;
|
|
using Avalonia.Markup.Xaml.Styling;
|
|
using Avalonia.Themes.Fluent;
|
|
using Avalonia.Threading;
|
|
using Avalonia.VisualTree;
|
|
using OpenCvSharp;
|
|
using Prism.Dialogs;
|
|
using SopHelper.Engine.Common;
|
|
using SopHelper.Engine.Sop;
|
|
using SopHelper.Engine.Training;
|
|
using SopHelper.Training;
|
|
using SopHelper.VVMs.RecipeEditor;
|
|
using SopHelper.VVMs.SopPage;
|
|
using Window = Avalonia.Controls.Window;
|
|
|
|
internal static class Program
|
|
{
|
|
private static string? _overlayPreviewPath;
|
|
[STAThread]
|
|
public static void Main(string[] args)
|
|
{
|
|
var previewIndex = Array.IndexOf(args, "--overlay-preview");
|
|
if (previewIndex >= 0 && previewIndex + 1 < args.Length) _overlayPreviewPath = args[previewIndex + 1];
|
|
var root = Path.Combine(Path.GetTempPath(), "video-flow-test-" + Guid.NewGuid().ToString("N"));
|
|
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
|
|
try
|
|
{
|
|
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).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") });
|
|
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
|
|
CheckAiFlow();
|
|
CheckSequenceEditor();
|
|
AgentDraftVerificationChecks.Run(root);
|
|
StandardVideoImportChecks.Run(root);
|
|
CheckVideoPage(root);
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previousRoot);
|
|
if (Directory.Exists(root)) Directory.Delete(root, true);
|
|
}
|
|
}
|
|
|
|
private static void CheckSequenceEditor()
|
|
{
|
|
var config = new SopConfig();
|
|
config.Sop.Steps.Add(new() { Id = 1, Description = "状态变化", AiConfirmation = new()
|
|
{ EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationSampleMs = 300 } });
|
|
var editor = RecipeNode.From(config, "试验.yaml", false);
|
|
Check(editor.Steps[0].UsesSequenceEvidence, "编辑器须识别过程时序模式");
|
|
var restored = SopConfigLoader.Parse(SopConfigLoader.ToYaml(editor.ToConfig())).Sop.Steps[0].AiConfirmation!;
|
|
Check(restored.EvidenceMode == VisionEvidenceMode.Sequence && restored.ObservationMinMs == 1800
|
|
&& restored.ObservationMaxFrames == 13 && restored.ObservationSampleMs == 300, "编辑保存不得丢失时序模式与窗口参数");
|
|
Console.WriteLine("PASS: 编辑器过程时序模式及观察参数往返保留");
|
|
}
|
|
|
|
private static void CheckAiFlow()
|
|
{
|
|
var config = SopConfigLoader.Parse("""
|
|
sop:
|
|
name: 流程测试
|
|
settings: { auto_reset_on_complete: true }
|
|
regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } }
|
|
steps:
|
|
- id: 1
|
|
name: 装配
|
|
description: 零件安装到位
|
|
detection: { method: hand_in_region, region: work, stable_frames: 1, tolerance: 1 }
|
|
ai_confirmation: { image_mode: fixed_region, image_region: work, timeout_seconds: 2 }
|
|
""");
|
|
var fake = new FakeDecision();
|
|
using var test = new SopVideoFlowTest(config, fake);
|
|
test.Start();
|
|
byte[]? sentImage = null;
|
|
test.DecisionImageCaptured += (jpeg, frameId) => { sentImage = jpeg; Check(frameId == 12, "Diagnostic image identifies the actual submitted video frame"); };
|
|
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90));
|
|
var frame = new FrameResult { FrameId = 12, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] };
|
|
test.ProcessResult(frame, image);
|
|
Until(() => fake.Request is not null);
|
|
Check(!test.IsCompleted && fake.Request!.FrameId == 12 && fake.Request.Jpeg.Length > 0, "Hand trigger submits the exact video frame to AI without completing early");
|
|
Check(ReferenceEquals(sentImage, fake.Request!.Jpeg), "Diagnostic image is exactly the image sent to AI");
|
|
var drain = test.FinishPendingDecisionAsync();
|
|
Check(!drain.IsCompleted, "End of video waits for the outstanding AI decision");
|
|
fake.Result.SetResult(new(true, .99, "已安装"));
|
|
Pump(drain);
|
|
Check(test.IsCompleted && test.Finish("播放结束").Contains("检测通过") && test.Details.Contains("✓ 1 装配"), "Final AI confirmation completes the flow and preserves the completed step result");
|
|
Check(config.Sop.Settings.AutoResetOnComplete, "Test run preserves the editor configuration");
|
|
using var cancelled = new SopVideoFlowTest(config, new FakeDecision());
|
|
cancelled.Start();
|
|
cancelled.ProcessResult(frame, image);
|
|
var cancelledDrain = cancelled.FinishPendingDecisionAsync();
|
|
cancelled.Dispose(); Pump(cancelledDrain);
|
|
Check(!cancelled.IsCompleted, "Stopping a test cancels pending AI without reporting success");
|
|
var rejectedClient = new FakeDecision();
|
|
using var rejected = new SopVideoFlowTest(config, rejectedClient); rejected.Start();
|
|
rejected.ProcessResult(frame, image);
|
|
rejectedClient.Result.SetResult(new(false, .15, "裁剪图没有纸盒"));
|
|
Pump(rejected.FinishPendingDecisionAsync());
|
|
rejected.ProcessResult(new FrameResult { FrameId = 13, Size = (64, 48) }, image);
|
|
Check(rejected.Details.Contains("裁剪图没有纸盒") && rejected.Details.Contains("未检出手"), "A later hand message preserves the last AI rejection reason");
|
|
}
|
|
|
|
private static void CheckVideoPage(string root)
|
|
{
|
|
var store = new RecipeWorkspace(root);
|
|
var config = new SopConfig(); config.Sop.Name = "视频测试界面"; config.Sop.Parts = [];
|
|
var vm = new RecipeEditorViewModel();
|
|
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
|
|
vm.SaveCommand.Execute();
|
|
var model = vm.SopRecording!;
|
|
Check(!model.TestFlowCommand.CanExecute(), "Test flow is disabled without a saved standard video");
|
|
Directory.CreateDirectory(Path.GetDirectoryName(model.StandardVideoPath)!);
|
|
using (var writer = new VideoWriter(model.StandardVideoPath, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48)))
|
|
{
|
|
Check(writer.IsOpened(), "Standard test video opens");
|
|
for (var i = 0; i < 10; i++)
|
|
{
|
|
using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); writer.Write(image);
|
|
}
|
|
}
|
|
CheckRealtimePlayback(model.StandardVideoPath);
|
|
CheckContinuousPlayback(model.StandardVideoPath);
|
|
// Unsupported condition exercises playback and incomplete results without hardware/models/API.
|
|
config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }];
|
|
config.Sop.Regions["标定区"] = new() { X1 = 10, Y1 = 5, X2 = 50, Y2 = 40, Name = "标定区", Color = "#FF00FF" };
|
|
model.FlowTestConfigProvider = () => config;
|
|
var view = new RecipeEditor { DataContext = vm };
|
|
var window = new Window { Content = view, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout();
|
|
var tabs = view.GetVisualDescendants().OfType<TabControl>().Single();
|
|
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "SOP流程视频");
|
|
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
|
var button = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.TestFlowCommand));
|
|
Check(button.Content?.ToString() == "测试流程" && button.IsEffectivelyVisible && model.TestFlowCommand.CanExecute(), "SOP video page exposes the enabled test flow button");
|
|
var importButton = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.ImportVideoCommand));
|
|
Check(importButton.Content?.ToString() == "导入视频" && importButton.IsEffectivelyVisible && importButton.IsEnabled, "SOP video page exposes the enabled import button");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(model.IsTestingFlow && model.Playback.IsPlaying && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Test button plays and displays the standard video without a camera");
|
|
Check(!model.TestFlowCommand.CanExecute() && !model.PlayVideoCommand.CanExecute() && !model.PreviewCommand.CanExecute() && !model.CanSeekVideo, "Test run prevents restart, playback switching, camera switching, and seeking");
|
|
Check(!view.FindControl<Slider>("VideoSeekSlider")!.IsEnabled, "Actual seek slider is disabled during flow testing");
|
|
var regionsOverlay = view.FindControl<FlowTestRegionOverlay>("FlowTestRegionsOverlay")!;
|
|
var handsOverlay = view.FindControl<HandOverlay>("FlowTestHandsOverlay")!;
|
|
Check(regionsOverlay.IsEffectivelyVisible && regionsOverlay.Regions!.ContainsKey("标定区")
|
|
&& handsOverlay.IsEffectivelyVisible && handsOverlay.ShowBounds && !handsOverlay.IsHitTestVisible,
|
|
"Video test displays the recipe region layer and hand skeleton/contact bounds without intercepting input");
|
|
var analyze = model.Playback.FrameAnalyzer!;
|
|
model.Playback.FrameAnalyzer = (image, id, seconds) =>
|
|
{
|
|
var result = analyze(image, id, seconds)!;
|
|
result.Hands = id % 2 == 0 ? [new Hand { HandType = HandType.Left, Rect = new(20, 10, 20, 25),
|
|
Keypoints = Enumerable.Range(0, 21).Select(i => new HandPoint { Index = i, X = 20 + i % 5 * 3, Y = 10 + i / 5 * 5, Confidence = 1 }).ToList() }] : [];
|
|
return result;
|
|
};
|
|
Until(() => model.Playback.Analysis is { FrameId: >= 2, Hands.Count: 1 });
|
|
Check(ReferenceEquals(handsOverlay.Result, model.Playback.Analysis) && handsOverlay.Result!.Size == (64, 48),
|
|
"Hand overlay receives the analysis published with the displayed video frame");
|
|
if (_overlayPreviewPath is not null)
|
|
{
|
|
window.UpdateLayout();
|
|
using var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
|
|
rendered.Render(window); rendered.Save(_overlayPreviewPath);
|
|
}
|
|
void CheckAlignment()
|
|
{
|
|
window.UpdateLayout();
|
|
var host = (Grid)regionsOverlay.Parent!;
|
|
var videoImage = host.Children.OfType<Image>().Single();
|
|
var start = videoImage.TranslatePoint(new Avalonia.Point(), window)!.Value;
|
|
var end = videoImage.TranslatePoint(new Avalonia.Point(videoImage.Bounds.Width, videoImage.Bounds.Height), window)!.Value;
|
|
foreach (var overlay in new Control[] { regionsOverlay, handsOverlay })
|
|
{
|
|
var overlayStart = overlay.TranslatePoint(new Avalonia.Point(), window)!.Value;
|
|
var overlayEnd = overlay.TranslatePoint(new Avalonia.Point(overlay.Bounds.Width, overlay.Bounds.Height), window)!.Value;
|
|
Check(Math.Abs(start.X - overlayStart.X) < .01 && Math.Abs(start.Y - overlayStart.Y) < .01
|
|
&& Math.Abs(end.X - overlayEnd.X) < .01 && Math.Abs(end.Y - overlayEnd.Y) < .01,
|
|
"Region and hand layers exactly follow the image bounds through uniform scaling and letterboxing");
|
|
}
|
|
Check(Math.Abs((end.X - start.X) / (end.Y - start.Y) - 64d / 48) < .001, "Overlay host preserves the original video aspect ratio");
|
|
}
|
|
CheckAlignment();
|
|
window.Width = 840; window.Height = 900; CheckAlignment();
|
|
window.Width = 1040; window.Height = 760;
|
|
Until(() => model.Playback.Analysis is { FrameId: >= 3, Hands.Count: 0 });
|
|
Check(handsOverlay.Result!.Hands.Count == 0, "A frame with no hands clears the previous skeleton instead of retaining old detections");
|
|
Until(() => !model.IsTestingFlow);
|
|
Check(model.Playback.IsAtEnd && model.FlowTestStatus.Contains("流程未完成") && model.FlowTestDetails.Contains("待配置步骤"), "Video EOF reports incomplete flow and shows the step reason");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(model.Playback.Progress < 50, "Each test restarts the video from its beginning");
|
|
model.StopVideoCommand.Execute(); Until(() => !model.IsBusy);
|
|
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.FlowTestStatus.Contains("测试已停止"), "Stop playback also stops detection and preserves the test summary");
|
|
Check(model.Playback.Analysis is null && !model.ShowFlowTestOverlay, "Stopping playback clears the hand analysis and hides test overlays");
|
|
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
|
|
Pump(vm.ShutdownAsync());
|
|
Check(!model.IsTestingFlow && !model.Playback.IsLoaded && model.Playback.FrameProcessor is null && model.Playback.FrameAnalyzer is null, "Closing the editor releases playback and flow detection");
|
|
using (var exclusive = new FileStream(model.StandardVideoPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
|
Check(exclusive.Length > 0, "Closing flow test unlocks the video file");
|
|
window.Close(); vm.OnDialogClosed();
|
|
}
|
|
|
|
private static void CheckRealtimePlayback(string path)
|
|
{
|
|
var playback = new RecordedVideoPlayback();
|
|
var ids = new System.Collections.Concurrent.ConcurrentQueue<long>();
|
|
var config = SopConfigLoader.Parse("""
|
|
sop:
|
|
name: 连续播放
|
|
regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } }
|
|
steps:
|
|
- id: 1
|
|
name: 装配
|
|
description: 盒内可见零件
|
|
detection: { method: hand_in_region, region: work, stable_frames: 1 }
|
|
ai_confirmation: { timeout_seconds: 5 }
|
|
""");
|
|
var fake = new FakeDecision();
|
|
using var test = new SopVideoFlowTest(config, fake); test.Start();
|
|
playback.FrameProcessor = (image, id, _) =>
|
|
{
|
|
ids.Enqueue(id);
|
|
test.ProcessResult(new FrameResult { FrameId = id, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] }, image);
|
|
};
|
|
Pump(playback.PlayAsync(path));
|
|
using (var wait = new CancellationTokenSource(350)) Dispatcher.UIThread.MainLoop(wait.Token);
|
|
Check(fake.Request is not null && !fake.Result.Task.IsCompleted && ids.Count > 1 && playback.IsPlaying && playback.Progress > 0,
|
|
"Video and frame detection continue while AI is still pending");
|
|
Until(() => playback.IsAtEnd);
|
|
Check(!fake.Result.Task.IsCompleted && !test.IsCompleted && ids.Last() > ids.First(), "Video reaches EOF without waiting for AI or reporting premature success");
|
|
fake.Result.SetResult(new(true, .99, "盒内可见零件"));
|
|
Pump(test.FinishPendingDecisionAsync());
|
|
Check(test.IsCompleted, "Background AI result can still complete the flow after video EOF");
|
|
Pump(playback.StopAsync());
|
|
ids.Clear();
|
|
playback.FrameProcessor = (_, id, _) => { Thread.Sleep(140); ids.Enqueue(id); };
|
|
Pump(playback.PlayAsync(path));
|
|
Until(() => playback.IsAtEnd);
|
|
Check(ids.Count < 10 && ids.SequenceEqual(ids.OrderBy(id => id)), "Slow inference catches up with the video clock instead of slowing playback to process every frame");
|
|
Pump(playback.StopAsync());
|
|
Check(!playback.IsLoaded, "Stopping realtime playback releases the video reader");
|
|
}
|
|
|
|
private static void CheckContinuousPlayback(string path)
|
|
{
|
|
var config = new SopConfig(); config.Sop.Name = "AI延迟跨三步";
|
|
for (var i = 0; i < 3; i++)
|
|
{
|
|
var key = "r" + i;
|
|
config.Sop.Regions[key] = new() { X1 = i * 20, Y1 = 0, X2 = i * 20 + 18, Y2 = 40 };
|
|
config.Sop.Steps.Add(new() { Id = i + 1, Name = "连续操作" + (i + 1), Description = "区域内可见操作结果",
|
|
Detection = new() { Method = ConditionMethod.HandInRegion, Region = key, Hand = "right", StableFrames = 1, Tolerance = 1 },
|
|
AiConfirmation = new() { ImageMode = VisionImageMode.FixedRegion, ImageRegion = key, TimeoutSeconds = 5 } });
|
|
}
|
|
var fake = new MultiDecision();
|
|
using var test = new SopVideoFlowTest(config, fake); test.Start();
|
|
var playback = new RecordedVideoPlayback();
|
|
playback.FrameProcessor = (image, id, _) =>
|
|
{
|
|
var region = id < 3 ? 0 : id < 6 ? 1 : 2;
|
|
test.ProcessResult(new() { FrameId = id, Timestamp = DateTime.Now, Size = (64, 48),
|
|
Hands = [new Hand { HandType = HandType.Right, Rect = new(region * 20 + 4, 10, 6, 6) }] }, image);
|
|
};
|
|
Pump(playback.PlayAsync(path));
|
|
Until(() => playback.IsAtEnd);
|
|
Check(fake.Calls.Count == 1 && !test.IsCompleted && test.Details.Contains("动作已取图"),
|
|
"Continuous video captures later steps even when the first AI request lasts until EOF");
|
|
var drain = test.FinishPendingDecisionAsync();
|
|
for (var i = 0; i < 3; i++)
|
|
{
|
|
Until(() => fake.Calls.Count == i + 1);
|
|
var call = fake.Calls.ElementAt(i);
|
|
Check(call.Request.StepId == i + 1 && call.Request.FrameId / 3 == i,
|
|
"After EOF each AI request uses its own original action frame in process order");
|
|
call.Result.SetResult(new(true, .99, "可见本步结果"));
|
|
}
|
|
Pump(drain);
|
|
Check(test.IsCompleted && test.Details.Split('✓').Length == 4,
|
|
"Buffered video actions complete all three steps without pausing playback or repeating actions");
|
|
Pump(playback.StopAsync());
|
|
}
|
|
|
|
private static void Until(Func<bool> ready)
|
|
{
|
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
using var cancellation = new CancellationTokenSource(10);
|
|
Dispatcher.UIThread.MainLoop(cancellation.Token);
|
|
}
|
|
if (!ready()) throw new TimeoutException("Smoke test timed out");
|
|
Dispatcher.UIThread.RunJobs();
|
|
}
|
|
private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); }
|
|
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
|
|
private sealed class FakeDecision : IVisionDecisionClient
|
|
{
|
|
public VisionDecisionRequest? Request;
|
|
public TaskCompletionSource<VisionDecisionResult> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
|
|
{ Request = request; return Result.Task.WaitAsync(cancellationToken); }
|
|
}
|
|
private sealed class MultiDecision : IVisionDecisionClient
|
|
{
|
|
public System.Collections.Concurrent.ConcurrentQueue<(VisionDecisionRequest Request, TaskCompletionSource<VisionDecisionResult> Result)> Calls { get; } = new();
|
|
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
|
|
{
|
|
var result = new TaskCompletionSource<VisionDecisionResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
Calls.Enqueue((request, result)); return result.Task.WaitAsync(cancellationToken);
|
|
}
|
|
}
|
|
}
|