From beabee131bcc1e4083075203cb95ab6b986cdeb1 Mon Sep 17 00:00:00 2001 From: wanglei Date: Thu, 26 Nov 2026 21:05:39 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20Agent=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=AD=A5=E9=AA=A4=E6=97=B6=E5=85=B3=E9=94=AE=E5=B8=A7=E8=A3=81?= =?UTF-8?q?=E5=89=AA=E8=B6=8A=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VVMs/RecipeEditor/EditorNodes.cs | 5 ++ .../RecipeEditor/OptimizeStepsViewModel.cs | 9 ++- .../RecipeEditor/SopVideoAgentViewModel.cs | 3 +- .../RecipeEditor/StepKeyFrameViewModel.cs | 2 + .../RecipeEditor/StepTestDecisionViewModel.cs | 71 +++++++++++++++++-- .../Sop/SopConfig.cs | 17 +++-- .../SopAgent/SopVideoSampler.cs | 7 +- .../AgentDraftGenerationChecks.cs | 55 +++++++++++--- .../OptimizeStepsChecks.cs | 13 ++-- 9 files changed, 152 insertions(+), 30 deletions(-) diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs index a10e85d..ed27a2a 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs @@ -384,6 +384,7 @@ public class RecipeNode : EditorNode Name = step.Name, Description = step.Description, KeyFrameBase64 = step.KeyFrameBase64, KeyFrameSeconds = step.KeyFrameSeconds, + KeyFrameSourceSize = step.KeyFrameSourceSize, Timeout = step.Timeout, StandardDurationMs = step.StandardDurationMs, SaveCompletionImage = step.SaveCompletionImage, @@ -448,6 +449,7 @@ public class RecipeNode : EditorNode Name = step.Name, Description = step.Description, KeyFrameBase64 = step.KeyFrameBase64, KeyFrameSeconds = step.KeyFrameSeconds, + KeyFrameSourceSize = step.KeyFrameSourceSize, Timeout = step.Timeout, StandardDurationMs = step.StandardDurationMs, SaveCompletionImage = step.SaveCompletionImage, @@ -621,6 +623,7 @@ public class StepNode : EditorNode { private string _keyFrameBase64 = ""; private double? _keyFrameSeconds; + private KeyFrameSourceSize? _keyFrameSourceSize; private Avalonia.Media.Imaging.Bitmap? _keyFrameImage; private bool _keyFrameImageLoaded; public string KeyFrameBase64 @@ -660,6 +663,8 @@ public class StepNode : EditorNode } public bool HasKeyFrameImage => KeyFrameImage is not null; public double? KeyFrameSeconds { get => _keyFrameSeconds; set { if (SetProperty(ref _keyFrameSeconds, value)) RaisePropertyChanged(nameof(KeyFrameLabel)); } } + /// 保留 Agent 关键帧的原始坐标系,随步骤保存及交换。 + public KeyFrameSourceSize? KeyFrameSourceSize { get => _keyFrameSourceSize; set => SetProperty(ref _keyFrameSourceSize, value); } public string KeyFrameLabel => string.IsNullOrEmpty(KeyFrameBase64) ? "尚未保存关键帧" : $"已保存关键帧:{KeyFrameSeconds:0.###} 秒(保存配方后持久化)"; private int _aiCheckWindowMs = 10000; diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs index eee53ca..950ec13 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs @@ -30,6 +30,7 @@ public partial class RecipeEditorViewModel var recipe = Recipe; var recipeName = recipe.Name; var config = recipe.ToConfig(); + var videoPaths = KeyFrameVideoPaths(); var configSnapshot = System.Text.Json.JsonSerializer.Serialize(config); var steps = recipe.Steps.Select(node => new { @@ -54,15 +55,17 @@ public partial class RecipeEditorViewModel ResetAgentStepTaskHistory(); var results = new List<(StepNode Node, string Description)>(); var unchanged = 0; + var currentLabel = ""; try { var timeout = (SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs; foreach (var step in steps) { var label = $"步骤 {step.Id}「{step.Name}」"; + currentLabel = label; AgentStatus = $"{label}:正在查看关键帧并生成9条同义完成说明…"; var definition = config.Sop.Steps.First(s => s.Id == step.Id); - var prepared = await Task.Run(() => PrepareStepDecisionImage(step.KeyFrameBase64, definition, config.Sop.Regions), token); + var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, token), token); var jpeg = prepared.Jpeg; AppendStepDecisionLog($"{label} · 优化实际送检:{prepared.Scope}"); var report = new StepOptimizationReport(label, step.Description, jpeg, step.KeyFrameSeconds, prepared.Scope); @@ -111,12 +114,12 @@ public partial class RecipeEditorViewModel catch (OperationCanceledException) { AgentStatus = "步骤优化已取消或请求超时,当前配方未修改。"; } catch (ArgumentException error) { - AgentStatus = "步骤优化未应用:" + error.Message; + AgentStatus = $"步骤优化未应用:{currentLabel} · {error.Message}"; AgentChatMessages.Add(new("系统", AgentStatus)); } catch (FormatException error) { - AgentStatus = "步骤优化未应用:" + error.Message + "。请核对原说明与关键帧。"; + AgentStatus = $"步骤优化未应用:{currentLabel} · {error.Message}。请核对原说明与关键帧。"; AgentChatMessages.Add(new("系统", AgentStatus)); } catch (Exception error) diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs index f10144b..edaeb31 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs @@ -387,10 +387,11 @@ public partial class RecipeEditorViewModel node.StandardDurationMs = Math.Max(1, (int)Math.Round((step.EndSeconds - step.StartSeconds) * 1000)); node.Detection = ConditionNode.From(resolved.Sop.Steps[i].Detection!); node.AiConfirmation = resolved.Sop.Steps[i].AiConfirmation; - // 直接复用草稿参考画面的整图 JPEG 和视频时间,供步骤按送检规则裁剪。 + // JPEG 已为 Agent 缩图,保留原视频尺寸供静态送检换算固定区域。 var frame = _agentSample.Frames[step.EvidenceFrame]; node.KeyFrameBase64 = Convert.ToBase64String(frame.Jpeg); node.KeyFrameSeconds = frame.Seconds; + node.KeyFrameSourceSize = new() { Width = _agentSample.Width, Height = _agentSample.Height }; } if (choice == AgentRecipeApplyChoice.Overwrite) { diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepKeyFrameViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepKeyFrameViewModel.cs index 3d0597d..02b5c70 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepKeyFrameViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepKeyFrameViewModel.cs @@ -23,6 +23,8 @@ public partial class RecipeEditorViewModel var bytes = frame.ToPngBytes(); step.KeyFrameBase64 = Convert.ToBase64String(bytes); step.KeyFrameSeconds = ReferenceEquals(frame, recording?.Playback.Frame) ? recording!.Playback.DisplayedSeconds : null; + // 手动取得的画面以位图像素为准,覆盖 Agent 关键帧后清除原视频尺寸。 + step.KeyFrameSourceSize = null; StepKeyFrameStatus = $"已获取步骤 {step.Id}「{step.Name}」关键帧,请保存配方。"; } catch (Exception) { StepKeyFrameStatus = "关键帧保存失败,请重新获取。"; } diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs index 7cef934..f10068b 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs @@ -3,6 +3,7 @@ using OpenCvSharp; using Prism.Commands; using SopHelper.Engine.Sop; +using SopHelper.Engine.SopAgent; namespace SopHelper.VVMs.RecipeEditor; @@ -66,9 +67,9 @@ public partial class RecipeEditorViewModel var id = step.Id; var name = step.Name; var description = step.Description; - var base64 = step.KeyFrameBase64; var config = Recipe.ToConfig(); var definition = config.Sop.Steps.First(s => s.Id == id); + var videoPaths = KeyFrameVideoPaths(); var seconds = step.KeyFrameSeconds; var threshold = step.AiMinConfidence; var timeoutMs = checked((SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs); @@ -79,7 +80,7 @@ public partial class RecipeEditorViewModel StepTestStatus = $"{label}:正在按送检规则处理关键帧…"; try { - var prepared = await Task.Run(() => PrepareStepDecisionImage(base64, definition, config.Sop.Regions), cancellation.Token); + var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, cancellation.Token), cancellation.Token); var jpeg = prepared.Jpeg; AppendStepDecisionLog($"{label} · 实际送检:{prepared.Scope}"); cancellation.Token.ThrowIfCancellationRequested(); @@ -108,14 +109,70 @@ public partial class RecipeEditorViewModel } } - private static (byte[] Jpeg, string Scope) PrepareStepDecisionImage(string base64, StepDef step, IReadOnlyDictionary regions) + /// 固定本次旧关键帧核对可用的来源,后台取图不访问编辑器状态。 + private string?[] KeyFrameVideoPaths() => [AgentVideoPath, SopRecording?.StandardVideoPath]; + + /// 共用运行时送检规则,将原视频坐标转换为关键帧像素后再裁剪。 + private static (byte[] Jpeg, string Scope) PrepareStepDecisionImage(StepDef step, IReadOnlyDictionary regions, + string?[] videoPaths, CancellationToken token) { var options = step.AiConfirmation ?? new(); var region = VisionDecisionImage.ResolveRegion(options, regions); - using var image = Cv2.ImDecode(Convert.FromBase64String(base64), ImreadModes.Color); - var jpeg = VisionDecisionImage.Encode(image, region); - var scope = region is null ? "整帧" : $"区域 {options.ImageRegion} [{region.X1},{region.Y1},{region.X2},{region.Y2}]"; - return (jpeg, scope); + var bytes = Convert.FromBase64String(step.KeyFrameBase64); + using var image = Cv2.ImDecode(bytes, ImreadModes.Color); + if (image.Empty()) throw new FormatException("关键帧解码失败"); + if (region is null) return (VisionDecisionImage.Encode(image, null), "整帧"); + + var source = step.KeyFrameSourceSize; + if (source is null && step.KeyFrameSeconds is { } seconds && bytes.Length >= 2 && bytes[0] == 0xff && bytes[1] == 0xd8 + && Math.Max(image.Width, image.Height) == SopVideoSampler.SampleMaxEdge) + { + source = FindLegacyKeyFrameSource(bytes, seconds, videoPaths, token) + ?? throw new ArgumentException("无法确认旧 Agent 关键帧的原视频尺寸。请在 Agent 助手中选择原视频,或重新获取关键帧。"); + } + + var width = source?.Width ?? image.Width; + var height = source?.Height ?? image.Height; + if (width < image.Width || height < image.Height) + throw new ArgumentException("关键帧记录的原视频尺寸无效,请重新获取关键帧。"); + var scope = $"区域 {options.ImageRegion} [{region.X1},{region.Y1},{region.X2},{region.Y2}]"; + if (region.X1 < 0 || region.Y1 < 0 || region.X2 <= region.X1 || region.Y2 <= region.Y1 || region.X2 > width || region.Y2 > height) + throw new ArgumentException($"{scope} 无效或超出关键帧原始画面 {width}×{height},请核对送检区域或重新获取关键帧。"); + if (width != image.Width || height != image.Height) + { + // 左上向下、右下向上取整,保留原区域覆盖到的像素;按两轴实际尺寸处理缩图取整差异。 + region = new() + { + X1 = (int)((long)region.X1 * image.Width / width), + Y1 = (int)((long)region.Y1 * image.Height / height), + X2 = (int)(((long)region.X2 * image.Width + width - 1) / width), + Y2 = (int)(((long)region.Y2 * image.Height + height - 1) / height) + }; + scope += $" · 关键帧裁剪 [{region.X1},{region.Y1},{region.X2},{region.Y2}]"; + } + return (VisionDecisionImage.Encode(image, region), scope); + } + + /// 旧配方缺少尺寸时重抽同一时刻,只有 JPEG 内容匹配才采用候选视频的尺寸。 + private static KeyFrameSourceSize? FindLegacyKeyFrameSource(byte[] jpeg, double seconds, string?[] videoPaths, CancellationToken token) + { + foreach (var path in videoPaths.Distinct()) + { + token.ThrowIfCancellationRequested(); + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) continue; + try + { + var video = SopVideoSampler.ReadInfo(path, token); + var frame = SopVideoSampler.ReadFrames(video, [seconds], 0, token)[0]; + if (jpeg.AsSpan().SequenceEqual(frame.Jpeg)) + return new() { Width = video.Width, Height = video.Height }; + } + catch (Exception error) when (error is ArgumentException or IOException or InvalidDataException or OpenCVException) + { + // 候选视频损坏、替换或不含该时刻时,继续尝试其余来源。 + } + } + return null; } private async Task RunStepDecisionAsync(string label, VisionDecisionRequest request, CancellationToken token) diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs index caaf930..54a83f0 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs @@ -107,14 +107,23 @@ public class RegionDef public string Color { get; set; } = "#4CAF50"; } -/// -/// 步骤定义 -/// +/// 缩放关键帧对应的原始整帧尺寸,固定区域按此坐标系标定。 +public sealed record KeyFrameSourceSize +{ + public int Width { get; init; } + public int Height { get; init; } +} + +/// 步骤定义。 public class StepDef { - /// 用户选取的标准关键帧PNG,随步骤交换,不参与在线判定。 + /// 手动获取的 PNG 或 Agent 抽帧 JPEG,随步骤交换,用于编辑器静态判定。 public string KeyFrameBase64 { get; set; } = ""; + /// 视频中的关键帧时间(秒),从相机预览取图时为空。 public double? KeyFrameSeconds { get; set; } + /// Agent 抽帧前的视频尺寸。手动取图和旧配方没有此字段。 + [YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)] + public KeyFrameSourceSize? KeyFrameSourceSize { get; set; } /// 步骤号(不必从 1 开始,状态机取最小值起步) public int Id { get; set; } diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs index 1336a9e..5e2fc88 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs @@ -10,6 +10,9 @@ public sealed record SopVideoSample(string Path, double DurationSeconds, int Wid public static class SopVideoSampler { + /// 模型抽帧的最长边上限,用于识别可能被缩放过的旧关键帧。 + public const int SampleMaxEdge = 640; + /// 只读取视频元数据并检查可解码性,不据元数据推断操作步骤。 public static SopVideoSample ReadInfo(string path, CancellationToken token) { @@ -39,7 +42,7 @@ public static class SopVideoSampler var frameIndex = Math.Clamp((long)Math.Round(seconds * video.Fps), 0, video.FrameCount - 1); if (!video.Set(VideoCaptureProperties.PosFrames, frameIndex) || !video.Read(source) || source.Empty()) throw new InvalidDataException("视频画面读取失败"); - var scale = Math.Min(1, 640d / Math.Max(source.Width, source.Height)); + var scale = Math.Min(1d, (double)SampleMaxEdge / Math.Max(source.Width, source.Height)); Cv2.Resize(source, resized, new Size(Math.Max(1, (int)Math.Round(source.Width * scale)), Math.Max(1, (int)Math.Round(source.Height * scale)))); if (!Cv2.ImEncode(".jpg", resized, out var jpeg, [new ImageEncodingParam(ImwriteFlags.JpegQuality, 80)])) throw new IOException("视频画面编码失败"); @@ -78,7 +81,7 @@ public static class SopVideoSampler var index = (long)Math.Round(i * (count - 1d) / (wanted - 1)); if (!video.Set(VideoCaptureProperties.PosFrames, index) || !video.Read(source) || source.Empty()) throw new InvalidDataException($"视频第 {index} 帧解码失败,未生成步骤"); - var scale = Math.Min(1, 640d / Math.Max(source.Width, source.Height)); + var scale = Math.Min(1d, (double)SampleMaxEdge / Math.Max(source.Width, source.Height)); Cv2.Resize(source, resized, new Size(Math.Max(1, (int)Math.Round(source.Width * scale)), Math.Max(1, (int)Math.Round(source.Height * scale)))); if (!Cv2.ImEncode(".jpg", resized, out var jpeg, [new ImageEncodingParam(ImwriteFlags.JpegQuality, 80)])) throw new IOException("视频画面编码失败"); diff --git a/tests/VideoFlowTest.Smoke/AgentDraftGenerationChecks.cs b/tests/VideoFlowTest.Smoke/AgentDraftGenerationChecks.cs index 285d644..1891863 100644 --- a/tests/VideoFlowTest.Smoke/AgentDraftGenerationChecks.cs +++ b/tests/VideoFlowTest.Smoke/AgentDraftGenerationChecks.cs @@ -20,14 +20,15 @@ internal static class AgentDraftGenerationChecks var access = SopHelper.Models.UserAccess.Current; if (!access.IsAdministrator) access.Setup("agent-smoke-admin", "AgentSmokePassword123"); var video = Path.Combine(root, "agent-generation.avi"); - using (var writer = new VideoWriter(video, FourCC.MJPG, 10, new OpenCvSharp.Size(64, 48))) + // 视频超过 Agent 的抽帧尺寸上限,同一时刻的像素可用于核对旧关键帧。 + using (var writer = new VideoWriter(video, FourCC.MJPG, 10, new OpenCvSharp.Size(800, 600))) { Check(writer.IsOpened(), "Agent generation test video opens"); - for (var i = 0; i < 20; i++) { using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(20, 50, 100)); writer.Write(image); } + for (var i = 0; i < 20; i++) { using var image = new Mat(600, 800, MatType.CV_8UC3, new Scalar(20, 50, 100 + i * 5)); writer.Write(image); } } var config = new SopConfig(); config.Sop.Name = "代理草稿生成"; config.Sop.Parts = []; ReferenceEvidenceChecks.Run(video); - config.Sop.Regions["work"] = new() { X2 = 64, Y2 = 48 }; + config.Sop.Regions["work"] = new() { X1 = 640, X2 = 800, Y2 = 600 }; config.Sop.Steps = [new() { Id = 1, Name = "保留人工步骤", Description = "人工要求" }]; Directory.CreateDirectory(Path.Combine(root,"workspace")); File.WriteAllText(Path.Combine(root,"workspace","sop-agent.json"),"{\"endpoint\":\"http://127.0.0.1:1/v1\",\"model\":\"unit-test\",\"autoVerify\":true}"); @@ -98,7 +99,7 @@ internal static class AgentDraftGenerationChecks client.Failure = null; model.AgentDraftSteps[0].Description = "人工补充的静态结果"; Check(model.ApplyAgentDraftCommand.CanExecute(), "Manual draft edits remain applicable without replay"); - model.Recipe.Regions[0].X2 = 60; + model.Recipe.Regions[0].X2 = 798; model.ChooseAgentApplyAsync = () => Task.FromResult(AgentRecipeApplyChoice.Append); model.ShowAgentApplyCompletedAsync = _ => Task.CompletedTask; model.ApplyAgentDraftCommand.Execute(); @@ -112,8 +113,9 @@ internal static class AgentDraftGenerationChecks // 比对实际采样的 JPEG 和时间,确保步骤沿用草稿的参考画面。 var evidence = client.Evidence!; var keyFrame = Convert.ToBase64String(evidence.Jpeg); - Check(model.Recipe.Steps[1].KeyFrameBase64 == keyFrame && model.Recipe.Steps[1].KeyFrameSeconds == evidence.Seconds, - "应用草稿时将参考图及视频时间写入步骤关键帧"); + Check(model.Recipe.Steps[1].KeyFrameBase64 == keyFrame && model.Recipe.Steps[1].KeyFrameSeconds == evidence.Seconds + && model.Recipe.Steps[1].KeyFrameSourceSize is { Width: 800, Height: 600 }, + "应用草稿时将参考图、视频时间和原图尺寸写入步骤关键帧"); Check(File.ReadAllBytes(path).SequenceEqual(before), "Applying generated draft still requires explicit recipe save"); model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy); Check(!client.SawVerification&&model.ApplyAgentDraftCommand.CanExecute(),"Regenerated draft is directly applicable"); @@ -134,12 +136,49 @@ internal static class AgentDraftGenerationChecks Check(model.Recipe.Steps.Count == 2 && File.ReadAllBytes(path).SequenceEqual(before), "Cancelling generation leaves the recipe untouched"); model.SaveCommand.Execute(); var savedStep = SopConfigLoader.Load(path).Sop.Steps[1]; - Check(savedStep.KeyFrameBase64 == keyFrame && savedStep.KeyFrameSeconds == evidence.Seconds, - "保存并重新读取配方后保留草稿关键帧及视频时间"); + Check(savedStep.KeyFrameBase64 == keyFrame && savedStep.KeyFrameSeconds == evidence.Seconds + && savedStep.KeyFrameSourceSize is { Width: 800, Height: 600 }, + "保存并重新读取配方后保留草稿关键帧的原始坐标系"); + CheckLegacyKeyFrame(model); model.ConfirmCloseAsync = () => Task.FromResult(RecipeCloseChoice.Discard); Pump(model.ShutdownAsync()); window.Close(); Until(() => !window.IsVisible); model.OnDialogClosed(); } + /// 模拟缺少尺寸的旧配方,验证同源帧能送检,不能确认来源时拒绝发送。 + private static void CheckLegacyKeyFrame(RecipeEditorViewModel model) + { + var step = model.Recipe.Steps[1]; + model.Recipe.SelectedStep = step; + step.KeyFrameSourceSize = null; + var probe = new KeyFrameDecisionProbe(); + model.StepTestDecisionClient = probe; + model.TestStepDecisionCommand.Execute(); + Until(() => !model.IsTestingStep); + Check(probe.Request is not null && model.StepDecisionLog.Contains("关键帧裁剪 [512,0,639,480]"), + "旧草稿关键帧根据原视频恢复缩放坐标"); + using (var crop = Cv2.ImDecode(probe.Request!.Jpeg, ImreadModes.Color)) + Check(crop.Width == 127 && crop.Height == 480, "旧草稿送检图使用实际换算后的固定区域"); + + // 即使原区域落在缩图内,也不能把原图坐标直接套用到未核实的缩图。 + model.Recipe.Regions.First(r => r.Key == "work").X1 = 0; + model.Recipe.Regions.First(r => r.Key == "work").X2 = 600; + step.KeyFrameSeconds = 1.5; + probe.Request = null; + model.TestStepDecisionCommand.Execute(); + Until(() => !model.IsTestingStep); + Check(probe.Request is null && model.StepTestStatus.Contains("重新获取关键帧"), "同视频不同内容的帧不得作为尺寸来源"); + } + + private sealed class KeyFrameDecisionProbe : IVisionDecisionClient + { + public VisionDecisionRequest? Request { get; set; } + public Task DecideAsync(VisionDecisionRequest request, CancellationToken token) + { + Request = request; + return Task.FromResult(new VisionDecisionResult(true, .99, "固定区域可判定")); + } + } + private static void Pump(Task task) { Until(() => task.IsCompleted); task.GetAwaiter().GetResult(); } private static void Until(Func ready) { diff --git a/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs b/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs index 78f86e4..4c86b64 100644 --- a/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs +++ b/tests/VideoFlowTest.Smoke/OptimizeStepsChecks.cs @@ -21,8 +21,10 @@ internal static class OptimizeStepsChecks Check(model.AgentStatus.Contains("关键帧"), "缺关键帧不优化"); using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 40, 230)); first.KeyFrameBase64 = Convert.ToBase64String(image.ToBytes(".png")); first.KeyFrameSeconds = 2.5; + // 模拟缩放帧,配方区域的右下角在原图边缘,直接套用坐标会越界。 + first.KeyFrameSourceSize = new() { Width = 128, Height = 96 }; var inspect = model.Recipe.AddRegion("inspect"); - inspect.X1 = 16; inspect.Y1 = 12; inspect.X2 = 48; inspect.Y2 = 36; + inspect.X1 = 65; inspect.Y1 = 49; inspect.X2 = 128; inspect.Y2 = 96; first.AiImageMode = VisionImageMode.FixedRegion; first.AiImageRegion = "inspect"; var second = model.Recipe.AddStep(); second.Description = "盖子关闭"; second.KeyFrameBase64 = first.KeyFrameBase64; var original = first.Description; @@ -53,10 +55,11 @@ internal static class OptimizeStepsChecks Check(report.EvidenceImage.PixelWidth == (stepIndex == 0 ? 32 : 64) && report.EvidenceImage.PixelHeight == (stepIndex == 0 ? 24 : 48) && descriptions.Images[stepIndex].SequenceEqual(decisions.Requests[stepIndex * 10].Jpeg), "Agent与djev接收完全相同的关键帧且界面显示该图片"); } - Check(model.OptimizationReports[0].EvidenceLabel.Contains("inspect [16,12,48,36]"), "优化公开送检区名称和坐标"); + Check(model.OptimizationReports[0].EvidenceLabel.Contains("inspect [65,49,128,96] · 关键帧裁剪 [32,24,64,48]"), + "优化公开原区域和实际裁剪坐标"); using (var decoded = Cv2.ImDecode(Convert.FromBase64String(first.KeyFrameBase64), ImreadModes.Color)) - Check(VisionDecisionImage.Encode(decoded, VisionDecisionImage.ResolveRegion(new() { ImageMode = VisionImageMode.FixedRegion, ImageRegion = "inspect" }, - model.Recipe.ToConfig().Sop.Regions)).SequenceEqual(decisions.Requests[0].Jpeg), "优化裁剪与正式运行共用的范围解析及编码一致"); + Check(VisionDecisionImage.Encode(decoded, new() { X1 = 32, Y1 = 24, X2 = 64, Y2 = 48 }).SequenceEqual(decisions.Requests[0].Jpeg), + "优化按换算后的固定区域裁剪,Agent 与 djev 共用结果"); Check(model.AgentChatMessages.Count(m => m.Text.Contains("10 · 同义改写")) == 2, "对话保留每步全部候选及分数"); decisions = new Decisions { Invalid = true }; model.StepTestDecisionClient = decisions; @@ -93,7 +96,7 @@ internal static class OptimizeStepsChecks descriptions.Pending = new(TaskCreationOptions.RunContinuationsAsynchronously); model.OptimizeStepsCommand.Execute(); Until(() => model.IsAgentBusy); - inspect.X2 = 50; + inspect.X2 = 126; descriptions.Pending.SetResult(Enumerable.Range(1, 9).Select(i => "用户修改" + "改写" + i).ToArray()); Until(() => !model.IsAgentBusy); Check(first.Description == "用户修改" && model.AgentStatus.Contains("送检规则"), "优化中改变区域配置时不应用旧范围的分数");