640 lines
42 KiB
C#
640 lines
42 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.Recipes;
|
||
using SopHelper.SopVideo;
|
||
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; }
|
||
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
|
||
// 独立验证步骤单图测试,无需先执行视频回放流程。
|
||
if (args.Contains("--step-test-only")) { StepTestDecisionChecks.Run(); return; }
|
||
if (args.Contains("--optimization-only")) { OptimizeStepsChecks.Run(); return; }
|
||
// 独立验证配方关闭流程,避免受标准视频编解码环境影响。
|
||
if (args.Contains("--recipe-close-only")) { RecipeCloseChecks.Run(root); return; }
|
||
// 单独验证步骤交换和 Excel 导出,无需先执行视频判定用例。
|
||
if (args.Contains("--step-transfer-only")) { StepTransferChecks.Run(root); return; }
|
||
CheckLegacyRecipeRoundTrip();
|
||
// 单独验证标准视频链路,便于定位回放与流程回测问题。
|
||
if (args.Contains("--standard-video-only"))
|
||
{
|
||
RecipeCloseChecks.Run(root);
|
||
StandardVideoImportChecks.Run(root);
|
||
CheckVideoPage(root);
|
||
return;
|
||
}
|
||
CheckAiFlow();
|
||
CheckSequenceEditor();
|
||
StepTestDecisionChecks.Run();
|
||
OptimizeStepsChecks.Run();
|
||
RecipeCloseChecks.Run(root);
|
||
CheckRuntimeSettings(root);
|
||
StepTransferChecks.Run(root);
|
||
AgentDraftGenerationChecks.Run(root);
|
||
StandardVideoImportChecks.Run(root);
|
||
CheckVideoPage(root);
|
||
}
|
||
finally
|
||
{
|
||
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previousRoot);
|
||
if (Directory.Exists(root)) Directory.Delete(root, true);
|
||
}
|
||
}
|
||
|
||
/// <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,
|
||
"新建步骤默认使用10秒限时复检");
|
||
var config = new SopConfig();
|
||
config.Sop.Steps.Add(new() { Id = 1, Description = "状态变化", AiConfirmation = new()
|
||
{ EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationRequestMaxFrames = 7, ObservationSampleMs = 300,
|
||
CheckWindowMs = 7000 } });
|
||
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.ObservationRequestMaxFrames == 7 && restored.ObservationSampleMs == 300,
|
||
"编辑保存不得丢失时序模式、缓存容量与单次请求预算");
|
||
Check(editor.Steps[0].AiContinueAfterWindow && restored.CheckWindowMs == 7000, "编辑保存须保留连续操作限时复检参数");
|
||
editor.Steps[0].AiContinueAfterWindow = false;
|
||
Check(editor.ToConfig().Sop.Steps[0].AiConfirmation!.CheckWindowMs == 0, "关闭限时复检须恢复原等待策略");
|
||
Console.WriteLine("PASS: 编辑器过程时序模式及观察参数往返保留");
|
||
}
|
||
|
||
private static void CheckRuntimeSettings(string root)
|
||
{
|
||
var store = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration"));
|
||
var legacy = SopConfigLoader.Parse("sop: {settings: {frame_stride: 3, auto_reset_on_complete: false, reset_delay_sec: 4}}");
|
||
var options = store.LoadOrMigrate(legacy);
|
||
Check(options.FrameStride == 3 && !options.AutoResetOnComplete && options.ResetDelaySec == 4 && options.DjevTimeoutMs == 300, "首次使用旧配方时迁移运行设置,djev超时使用独立默认值");
|
||
options.FrameStride = 2; options.AutoResetOnComplete = true; options.ResetDelaySec = 6; options.DjevTimeoutMs = 375;
|
||
store.Save(options);
|
||
var other = SopConfigLoader.Parse("sop: {settings: {frame_stride: 9, auto_reset_on_complete: false, reset_delay_sec: 30}}");
|
||
var loaded = new SopHelper.Models.RuntimeSettingsStore(Path.Combine(root, "runtime-migration")).LoadOrMigrate(other);
|
||
loaded.Apply(other);
|
||
Check(other.Sop.Settings.FrameStride == 2 && other.Sop.Settings.AutoResetOnComplete && other.Sop.Settings.ResetDelaySec == 6 && other.Sop.Settings.DjevTimeoutMs == 375,
|
||
"重启及切换配方沿用独立运行设置,不被旧配方覆盖");
|
||
File.WriteAllText(store.FilePath, "{\"FrameStride\":2,\"DjevTimeoutSeconds\":2}");
|
||
Check(store.Read()!.DjevTimeoutMs == 1000, "旧秒单位设置转换为毫秒,并限制在1000ms上限内");
|
||
File.WriteAllText(store.FilePath, "{\"DjevTimeoutMs\":375,\"DjevTimeoutSeconds\":2}");
|
||
var migrated = store.Read()!; store.Save(migrated);
|
||
Check(migrated.DjevTimeoutMs == 375 && !File.ReadAllText(store.FilePath).Contains("DjevTimeoutSeconds"),
|
||
"毫秒设置优先,保存后仅写毫秒字段");
|
||
}
|
||
|
||
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("手未在 work 内"), $"A later hand message preserves the last AI rejection reason: {rejected.Details}");
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|
||
var runtimeStore = SopHelper.Models.RuntimeSettingsStore.Current;
|
||
var runtime = runtimeStore.Read() ?? new();
|
||
var originalTimeout = runtime.DjevTimeoutMs;
|
||
runtime.DjevTimeoutMs = 1000; runtimeStore.Save(runtime);
|
||
try { CheckStridedHandPlayback(model.StandardVideoPath); CheckRealtimePlayback(model.StandardVideoPath); CheckContinuousPlayback(model.StandardVideoPath); CheckEditorPlayback(model.StandardVideoPath); }
|
||
finally { runtime.DjevTimeoutMs = originalTimeout; runtimeStore.Save(runtime); }
|
||
vm.Recipe.AddStepCommand.Execute();
|
||
var selected = vm.Recipe.SelectedStep!;
|
||
vm.CaptureStepKeyFrameCommand.Execute();
|
||
Check(selected.KeyFrameBase64.Length == 0, "Cannot capture a keyframe without a displayed video frame");
|
||
model.ToggleVideoPlaybackCommand.Execute(); Until(() => !model.IsBusy && model.Playback.IsPlaying);
|
||
Check(model.ToggleVideoPlaybackCommand.CanExecute() && model.PlayVideoButtonText == "暂停播放", "Combined playback button switches to pause while playing");
|
||
model.ToggleVideoPlaybackCommand.Execute(); Until(() => !model.IsBusy && !model.Playback.IsPlaying);
|
||
Check(model.ToggleVideoPlaybackCommand.CanExecute() && model.PlayVideoButtonText == "继续播放", "Combined playback button pauses and remains available to resume");
|
||
Pump(model.Playback.SeekAsync(50));
|
||
var displayed = Convert.ToBase64String(model.Playback.Frame!.ToPngBytes());
|
||
vm.CaptureStepKeyFrameCommand.Execute();
|
||
Check(selected.KeyFrameBase64 == displayed && selected.KeyFrameSeconds == model.Playback.DisplayedSeconds,
|
||
"Capture stores the exact displayed frame and timestamp after paused seeking");
|
||
vm.Recipe.AddStepCommand.Execute();
|
||
Check(vm.Recipe.SelectedStep!.KeyFrameBase64.Length == 0 && selected.KeyFrameBase64 == displayed,
|
||
"Keyframes belong to the selected step and do not leak across selection changes");
|
||
var transferred = SopStepTransfer.Read(SopStepTransfer.Export(vm.Recipe.ToConfig()));
|
||
Check(transferred.Sop.Steps[0].KeyFrameBase64 == displayed,
|
||
"Keyframe image and timestamp survive step export and import");
|
||
vm.SaveCommand.Execute();
|
||
var savedKeyFrames = RecipeNode.From(SopConfigLoader.Load(store.ConfigPath(config.Sop.Name)), "test.yaml", false);
|
||
Check(savedKeyFrames.Steps[0].KeyFrameBase64 == displayed && savedKeyFrames.Steps[0].KeyFrameSeconds == selected.KeyFrameSeconds,
|
||
"Saving and reopening the recipe preserves the selected step keyframe");
|
||
Pump(model.Playback.StopAsync());
|
||
|
||
// 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 stepVideo = view.FindControl<Border>("StepVideoViewport")!;
|
||
var parameters = view.FindControl<ScrollViewer>("StepParameters")!;
|
||
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "区域"),
|
||
"Region editing is integrated into the step tab");
|
||
Check(!view.GetVisualDescendants().OfType<TabItem>().Any(t => t.Header?.ToString() == "全局设置"), "配方编辑不再包含全局设置页");
|
||
var regionNavigation = view.FindControl<ListBox>("StepRegionNavigation")!;
|
||
var regionParameters = view.FindControl<ScrollViewer>("RegionParameters")!;
|
||
Check(regionNavigation.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height
|
||
&& regionParameters.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height,
|
||
"Region navigation and parameters sit below the step video player");
|
||
// 前面的保存检查已停止播放器;先加载并暂停,确保界面绑定与逐帧命令使用真实视频画面。
|
||
Pump(model.Playback.PlayAsync(model.StandardVideoPath)); model.Playback.Pause();
|
||
Pump(model.Playback.SeekAsync(50)); window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
||
var regionCanvas = view.FindControl<RegionCanvas>("StepVideoRegions")!;
|
||
Check(ReferenceEquals(regionCanvas.Image, model.Playback.Frame) && ReferenceEquals(regionCanvas.Regions, vm.Recipe.Regions),
|
||
"Integrated region canvas receives actual playback pixels and all recipe regions");
|
||
vm.Recipe.AddRegionCommand.Execute(); window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
||
Check(ReferenceEquals(regionCanvas.SelectedRegion, vm.Recipe.SelectedRegion)
|
||
&& ReferenceEquals(regionNavigation.SelectedItem, vm.Recipe.SelectedRegion),
|
||
"Region navigation, parameters and canvas share the selected editable region");
|
||
var playbackButtons = ((Panel)view.FindControl<Button>("StepPlayPauseButton")!.Parent!).Children.OfType<Button>().Where(button => button is not CheckBox).ToArray();
|
||
Check(playbackButtons.Length == 5 && playbackButtons[1].Content?.ToString() == "上一帧"
|
||
&& playbackButtons[2].Content?.ToString() == "下一帧"
|
||
&& playbackButtons[3].Content?.ToString() == "获取关键帧" && playbackButtons[4].Content?.ToString() == "停止",
|
||
"步骤播放控件包含逐帧按钮,获取关键帧位于停止之前");
|
||
var halfSpeed = view.FindControl<CheckBox>("StepHalfSpeed")!;
|
||
halfSpeed.IsChecked = true;
|
||
Check(model.Playback.HalfSpeed, "步骤半速控件绑定实际播放速度");
|
||
halfSpeed.IsChecked = false;
|
||
model.NextVideoFrameCommand.Execute(); Until(() => !model.IsBusy);
|
||
Check(Math.Abs(model.Playback.DisplayedSeconds - .6) < .001 && !model.Playback.IsPlaying,
|
||
"步骤下一帧命令定位并暂停");
|
||
model.PreviousVideoFrameCommand.Execute(); Until(() => !model.IsBusy);
|
||
Check(Math.Abs(model.Playback.DisplayedSeconds - .5) < .001,
|
||
"步骤上一帧命令精确返回原帧");
|
||
Pump(model.Playback.StopAsync());
|
||
vm.Recipe.SelectedStep = selected;
|
||
Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
|
||
var keyFrame = view.FindControl<Image>("StepKeyFrameImage")!;
|
||
Check(ReferenceEquals(view.FindControl<Button>("TestStepDecisionButton")!.Command, vm.TestStepDecisionCommand),
|
||
"步骤关键帧测试按钮绑定编辑器测试判定命令");
|
||
var navigationAndLog = view.FindControl<Grid>("StepNavigationAndLog")!;
|
||
var navigationPanel = view.FindControl<DockPanel>("StepNavigationPanel")!;
|
||
var logPanel = view.FindControl<Grid>("StepDecisionLogPanel")!;
|
||
Check(Math.Abs(logPanel.Bounds.Height - navigationPanel.Bounds.Height) < 1
|
||
&& logPanel.Bounds.Y >= navigationAndLog.Bounds.Height / 2
|
||
&& view.FindControl<SelectableTextBlock>("StepDecisionLogText")!.Text == vm.StepDecisionLog,
|
||
"左侧上下等分步骤导航和可选择复制的判定日志,并绑定日志内容");
|
||
var keyFrameRegions = view.FindControl<KeyFrameRegionOverlay>("StepKeyFrameRegions")!;
|
||
Check(keyFrame.Source is Avalonia.Media.Imaging.Bitmap && ReferenceEquals(keyFrame.Source, selected.KeyFrameImage)
|
||
&& ReferenceEquals(keyFrameRegions.Image, selected.KeyFrameImage)
|
||
&& ReferenceEquals(keyFrameRegions.Regions, vm.Recipe.Regions),
|
||
"Saved native keyframe bitmap binds to both the original image and all-region overlay");
|
||
Check(((Grid)keyFrame.Parent!).Bounds.Height == 360 && !parameters.IsVisualAncestorOf(keyFrame),
|
||
"Double-height keyframe remains outside the scrolling parameters");
|
||
using (var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize(320, 360)))
|
||
{
|
||
rendered.Render(keyFrame);
|
||
using var png = new MemoryStream(); rendered.Save(png);
|
||
using var pixels = Cv2.ImDecode(png.ToArray(), ImreadModes.Color);
|
||
Check(Cv2.Mean(pixels).Val1 > 10, "Keyframe control actually renders saved image pixels");
|
||
}
|
||
var keyFramePosition = keyFrame.TranslatePoint(default, window);
|
||
parameters.Offset = new Vector(0, 400);
|
||
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
||
Check(keyFrame.TranslatePoint(default, window) == keyFramePosition,
|
||
"Scrolling step parameters does not move the keyframe");
|
||
parameters.Offset = default;
|
||
CheckStepParameterLayout(vm, view, window);
|
||
if (_overlayPreviewPath is not null)
|
||
{
|
||
using var rendered = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
|
||
rendered.Render(window);
|
||
rendered.Save(Path.Combine(Path.GetDirectoryName(_overlayPreviewPath)!, "step-editor.png"));
|
||
parameters.Offset = new Vector(0, parameters.Extent.Height);
|
||
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
|
||
using var details = new Avalonia.Media.Imaging.RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
|
||
details.Render(window);
|
||
details.Save(Path.Combine(Path.GetDirectoryName(_overlayPreviewPath)!, "step-parameters.png"));
|
||
parameters.Offset = default;
|
||
}
|
||
Check(parameters.Bounds.Width > window.Bounds.Width * .30 && parameters.Bounds.Width < window.Bounds.Width * .37
|
||
&& parameters.Extent.Width <= parameters.Viewport.Width + 1,
|
||
"Parameters occupy 35 percent and fit without horizontal scrolling");
|
||
|
||
Check(stepVideo.Bounds.Width >= window.Bounds.Width * .44 && stepVideo.Bounds.Width <= window.Bounds.Width * .53,
|
||
"Step video occupies half the available editor width");
|
||
|
||
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");
|
||
vm.ConfirmCloseAsync = () => Task.FromResult(RecipeCloseChoice.Discard);
|
||
window.Close(); Until(() => !window.IsVisible); vm.OnDialogClosed();
|
||
}
|
||
|
||
private static void CheckStridedHandPlayback(string path)
|
||
{
|
||
var store = SopHelper.Models.RuntimeSettingsStore.Current;
|
||
var options = store.Read()!;
|
||
var originalStride = options.FrameStride;
|
||
var playback = new RecordedVideoPlayback();
|
||
try
|
||
{
|
||
options.FrameStride = 3; store.Save(options);
|
||
var config = new SopConfig();
|
||
config.Sop.Steps = [new StepDef { Id = 1, Detection = new() { Method = "unsupported" } }];
|
||
using var test = new SopVideoFlowTest(config); test.Start();
|
||
FrameResult? expected = null;
|
||
var detections = 0;
|
||
var skippedWithHands = 0;
|
||
var skippedWithoutHands = 0;
|
||
var samples = new List<(FrameResult? Actual, FrameResult? Expected)>();
|
||
playback.FrameAnalyzer = (image, id, seconds) =>
|
||
{
|
||
var result = test.AnalyzeFrame(image, id, seconds);
|
||
if (result is not null)
|
||
{
|
||
// 无需模型,模拟第一次检出手,后续检测确认手已离开。
|
||
if (++detections == 1) result.Hands = [new Hand { Rect = new(20, 10, 20, 25) }];
|
||
expected = result;
|
||
}
|
||
else if (expected?.Hands.Count > 0) skippedWithHands++;
|
||
else if (expected is not null) skippedWithoutHands++;
|
||
return result;
|
||
};
|
||
playback.PropertyChanged += (_, e) =>
|
||
{
|
||
if (e.PropertyName == nameof(RecordedVideoPlayback.Progress) && playback.IsPlaying)
|
||
samples.Add((playback.Analysis, expected));
|
||
};
|
||
Pump(playback.PlayAsync(path));
|
||
Until(() => playback.IsAtEnd);
|
||
Check(detections >= 2 && skippedWithHands > 0 && skippedWithoutHands > 0,
|
||
"抽帧回放覆盖初始未检测、有手后的跳帧及无手后的跳帧");
|
||
Check(samples.All(s => ReferenceEquals(s.Actual, s.Expected)),
|
||
"跳帧保留最近骨架,实际无手结果立即清除骨架且后续跳帧不恢复旧手");
|
||
Pump(playback.StopAsync());
|
||
Check(playback.Analysis is null, "停止抽帧测试清空旧骨架");
|
||
playback.FrameAnalyzer = null;
|
||
Pump(playback.PlayAsync(path));
|
||
Check(playback.Analysis is null, "重新普通播放不会沿用上轮测试骨架");
|
||
Console.WriteLine("PASS: 视频测试抽帧骨架连续显示与无手清除");
|
||
}
|
||
finally
|
||
{
|
||
Pump(playback.StopAsync());
|
||
options.FrameStride = originalStride; store.Save(options);
|
||
}
|
||
}
|
||
|
||
/// <summary>用已知帧率视频验证逐帧边界、播放中暂停定位和半速实际耗时。</summary>
|
||
private static void CheckEditorPlayback(string path)
|
||
{
|
||
var playback = new RecordedVideoPlayback();
|
||
try
|
||
{
|
||
Pump(playback.PlayAsync(path));
|
||
Pump(playback.StepFrameAsync(1));
|
||
Check(!playback.IsPlaying && Math.Abs(playback.DisplayedSeconds - .1) < .001,
|
||
"播放中下一帧暂停且精确前进一帧");
|
||
Pump(playback.StepFrameAsync(-1));
|
||
Pump(playback.StepFrameAsync(-1));
|
||
Check(playback.DisplayedSeconds == 0, "上一帧在视频起点钳位");
|
||
Pump(playback.SeekAsync(100));
|
||
Pump(playback.StepFrameAsync(1));
|
||
Check(Math.Abs(playback.DisplayedSeconds - .9) < .001, "下一帧在视频终点钳位");
|
||
Pump(playback.StepFrameAsync(-1));
|
||
Check(Math.Abs(playback.DisplayedSeconds - .8) < .001, "视频尾部可以返回上一帧");
|
||
Pump(playback.StopAsync());
|
||
playback.HalfSpeed = true;
|
||
var elapsed = System.Diagnostics.Stopwatch.StartNew();
|
||
Pump(playback.PlayAsync(path));
|
||
Until(() => playback.IsAtEnd);
|
||
Check(elapsed.Elapsed.TotalSeconds >= 1.8, "0.5倍速按实时时钟播放,1秒视频至少播放1.8秒");
|
||
playback.HalfSpeed = false;
|
||
Pump(playback.PlayAsync(path));
|
||
Pump(playback.SeekAsync(50));
|
||
playback.HalfSpeed = true;
|
||
Check(playback.DisplayedSeconds >= .5 && playback.IsPlaying, "播放中切换半速保持当前位置与播放状态");
|
||
}
|
||
finally { Pump(playback.StopAsync()); }
|
||
}
|
||
|
||
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");
|
||
// EOF可能发生在首次送检后仍未到期,明确等待配置期限后再模拟迟到结果。
|
||
var remainingDeadline = fake.Request!.TimeoutMs - RealtimeDecisionPolicy.Elapsed(fake.Request.StartedTimestamp);
|
||
if (remainingDeadline > 0)
|
||
{
|
||
using var deadlineWait = new CancellationTokenSource(TimeSpan.FromMilliseconds(remainingDeadline + 30));
|
||
Dispatcher.UIThread.MainLoop(deadlineWait.Token);
|
||
}
|
||
fake.Result.SetResult(new(true, .99, "盒内可见零件"));
|
||
Pump(test.FinishPendingDecisionAsync());
|
||
Check(!test.IsCompleted, "Late background result after EOF cannot bypass the configured deadline");
|
||
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 firstRequest = fake.Calls.First().Request;
|
||
var remainingDeadline = firstRequest.TimeoutMs - RealtimeDecisionPolicy.Elapsed(firstRequest.StartedTimestamp);
|
||
if (remainingDeadline > 0) Pump(Task.Delay(TimeSpan.FromMilliseconds(remainingDeadline + 50)));
|
||
var drain = test.FinishPendingDecisionAsync();
|
||
fake.Calls.First().Result.TrySetResult(new(true, .99, "迟到的通过"));
|
||
Pump(drain);
|
||
Check(!test.IsCompleted && fake.Calls.Count == 1,
|
||
"Expired buffered video actions cannot generate late real-time passes or queue old model requests");
|
||
Pump(playback.StopAsync());
|
||
}
|
||
|
||
private static void CheckStepParameterLayout(RecipeEditorViewModel model, RecipeEditor view, Window window)
|
||
{
|
||
var step = model.Recipe.SelectedStep!;
|
||
var condition = step.Detection!;
|
||
var original = condition.Method;
|
||
var windowMs = step.AiCheckWindowMs;
|
||
var timing = step.StandardDurationMs = 1234;
|
||
var notifications = new HashSet<string?>();
|
||
System.ComponentModel.PropertyChangedEventHandler changed = (_, e) => notifications.Add(e.PropertyName);
|
||
condition.PropertyChanged += changed;
|
||
bool Visible(string name) => view.FindControl<Control>(name)!.IsVisible;
|
||
void Method(string method) { condition.Method = method; Dispatcher.UIThread.RunJobs(); window.UpdateLayout(); }
|
||
try
|
||
{
|
||
Method(ConditionMethod.HandInRegion);
|
||
Check(view.FindControl<NumericUpDown>("AiTimeoutSecondsInput") is null,
|
||
"配方步骤没有djev超时入口,超时由独立运行设置统一控制");
|
||
Check(Visible("TriggerRegionRow") && Visible("TriggerStableField") && !Visible("TriggerMoveRows") && !Visible("TriggerDurationRow"),
|
||
"区域触发仅显示操作区域和稳定帧,不显示移动或计时参数");
|
||
Method(ConditionMethod.HandMove);
|
||
Check(Visible("TriggerMoveRows") && !Visible("TriggerRegionRow") && !Visible("TriggerStableField") && !Visible("TriggerDurationRow"),
|
||
"移动触发显示起终点并隐藏不生效的稳定帧和计时参数");
|
||
Method(ConditionMethod.TimeElapsed);
|
||
Check(Visible("TriggerDurationRow") && !Visible("TriggerMoveRows") && !Visible("TriggerRegionRow") && !condition.UsesHandTrigger,
|
||
"计时触发仅显示持续时间,不显示手部区域参数");
|
||
Check(notifications.Contains(nameof(ConditionNode.UsesTriggerRegion)) && notifications.Contains(nameof(ConditionNode.IsTimedTrigger)),
|
||
"切换触发方式通知界面刷新相关参数");
|
||
Check(!view.FindControl<Expander>("StepAdditionalSettings")!.IsExpanded
|
||
&& !view.FindControl<ScrollViewer>("StepParameters")!.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == "节拍毫秒")
|
||
&& model.Recipe.ToConfig().Sop.Steps.First(s => s.Id == step.Id).StandardDurationMs == timing,
|
||
"低频设置折叠,移除无运行用途的节拍输入并保留原配方数据");
|
||
step.AiContinueAfterWindow = false; Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
|
||
Check(step.AiCheckWindowMs == 0 && !step.AiContinueAfterWindow, "紧凑复检控件不会把关闭的窗口强制重新开启");
|
||
}
|
||
finally
|
||
{
|
||
condition.PropertyChanged -= changed;
|
||
condition.Method = original; step.AiCheckWindowMs = windowMs;
|
||
Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
|
||
}
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|
||
}
|