diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs
index edaeb31..d95e548 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs
@@ -353,22 +353,46 @@ public partial class RecipeEditorViewModel
/// 将当前草稿转换为编辑节点,协调录像工具和预览,供用户继续编辑与保存。
private async Task ApplyAgentDraftAsync()
{
- if (!CanApplyAgentDraft() || _agentSample is null) return;
+ if (!CanApplyAgentDraft() || _agentSample is not { } sample) return;
_isApplyingAgentDraft = true;
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
try
{
var draft = new SopVideoDraft { Steps = AgentDraftSteps.Select(row => row.Step).ToList(), RegionAdjustments = [.. _agentRegionAdjustments] };
var definitions = Recipe.ToConfig().Sop.Regions;
- try { SopVideoDraftClient.Validate(draft, _agentSample, definitions.Keys.ToArray(), definitions); }
+ try { SopVideoDraftClient.Validate(draft, sample, definitions.Keys.ToArray(), definitions); }
catch (FormatException error) { AgentStatus = "草稿未添加:" + error.Message; return; }
var resolved = SopDraftConfigBuilder.Build(CreateAgentDraftTemplate(), draft);
- var currentVideo = new FileInfo(_agentSample.Path);
- if (!currentVideo.Exists || _agentSample.SourceLength > 0 && (currentVideo.Length != _agentSample.SourceLength || currentVideo.LastWriteTimeUtc != _agentSample.SourceModifiedUtc))
+ var currentVideo = new FileInfo(sample.Path);
+ if (!currentVideo.Exists || sample.SourceLength > 0 && (currentVideo.Length != sample.SourceLength || currentVideo.LastWriteTimeUtc != sample.SourceModifiedUtc))
{ AgentStatus = "标准视频已变化,请重新生成。"; return; }
var choice = ChooseAgentApplyAsync is { } choose ? await choose() : AgentRecipeApplyChoice.Cancel;
- if (choice == AgentRecipeApplyChoice.Cancel || _agentClosed || IsAgentBusy || _draftApplied || _agentSample is null) return;
- foreach (var adjusted in _agentRegionAdjustments)
+ if (choice == AgentRecipeApplyChoice.Cancel || _agentClosed || IsAgentBusy || _draftApplied || !ReferenceEquals(_agentSample, sample)) return;
+
+ // 按证据帧的时间重新解码,整批成功后才写入区域和步骤,避免读帧失败留下半份配方。
+ var evidenceTimes = draft.Steps.Select(step => sample.Frames[step.EvidenceFrame].Seconds).ToArray();
+ using var cancellation = new CancellationTokenSource();
+ _agentCancellation = cancellation;
+ IsAgentBusy = true;
+ AgentStatus = "正在读取原分辨率关键帧…";
+ IReadOnlyList keyFrames;
+ try
+ {
+ keyFrames = await Task.Run(() => SopVideoSampler.ReadFrames(sample, evidenceTimes, 0, cancellation.Token,
+ preserveResolution: true));
+ cancellation.Token.ThrowIfCancellationRequested();
+ }
+ catch (OperationCanceledException)
+ { AgentStatus = "已取消读取关键帧,当前配方未修改。"; return; }
+ catch (Exception error) when (error is IOException or InvalidDataException or OpenCvSharp.OpenCVException)
+ { AgentStatus = "草稿未添加,读取原分辨率关键帧失败:" + error.Message; return; }
+ finally
+ {
+ _agentCancellation = null;
+ IsAgentBusy = false;
+ }
+ if (_agentClosed || !ReferenceEquals(_agentSample, sample)) return;
+ foreach (var adjusted in draft.RegionAdjustments)
{
var source = resolved.Sop.Regions[adjusted.Key];
var region = Recipe.Regions.FirstOrDefault(r => r.Key.Equals(adjusted.Key, StringComparison.OrdinalIgnoreCase)) ?? Recipe.AddRegion(adjusted.Key);
@@ -379,19 +403,19 @@ public partial class RecipeEditorViewModel
? _agentAppliedNodes.Where(Recipe.Steps.Contains).ToArray() : Array.Empty();
var previousSteps = Recipe.Steps.ToArray();
var applied = new List();
- for (var i = 0; i < AgentDraftSteps.Count; i++)
+ for (var i = 0; i < draft.Steps.Count; i++)
{
- var step = AgentDraftSteps[i].Step; var node = i < existing.Length ? existing[i] : Recipe.AddStep();
+ var step = draft.Steps[i]; var node = i < existing.Length ? existing[i] : Recipe.AddStep();
applied.Add(node);
node.Name = step.Name; node.Description = step.Description;
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 已为 Agent 缩图,保留原视频尺寸供静态送检换算固定区域。
- var frame = _agentSample.Frames[step.EvidenceFrame];
+ // 记录原视频尺寸,使送检能区分原分辨率 JPEG 与未记录尺寸的旧缩图。
+ var frame = keyFrames[i];
node.KeyFrameBase64 = Convert.ToBase64String(frame.Jpeg);
node.KeyFrameSeconds = frame.Seconds;
- node.KeyFrameSourceSize = new() { Width = _agentSample.Width, Height = _agentSample.Height };
+ node.KeyFrameSourceSize = new() { Width = sample.Width, Height = sample.Height };
}
if (choice == AgentRecipeApplyChoice.Overwrite)
{
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs
index 5e2fc88..8c69e6f 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoSampler.cs
@@ -27,7 +27,9 @@ public static class SopVideoSampler
}
/// 按请求时间定位并解码图像,帧索引从调用方给定起点连续分配。
- public static IReadOnlyList ReadFrames(SopVideoSample info, IReadOnlyList times, int firstIndex, CancellationToken token)
+ /// 保存配方关键帧时保留原始像素尺寸,使图像与区域坐标对齐。模型取样默认限制长边。
+ public static IReadOnlyList ReadFrames(SopVideoSample info, IReadOnlyList times, int firstIndex,
+ CancellationToken token, bool preserveResolution = false)
{
if (times.Count is < 1 or > 60 || times.Any(t => !double.IsFinite(t) || t < 0 || t > info.DurationSeconds))
throw new ArgumentException("读取时间须在视频时长内");
@@ -42,9 +44,14 @@ 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(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)]))
+ var image = source;
+ if (!preserveResolution && Math.Max(source.Width, source.Height) > SampleMaxEdge)
+ {
+ var scale = (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))));
+ image = resized;
+ }
+ if (!Cv2.ImEncode(".jpg", image, out var jpeg, [new ImageEncodingParam(ImwriteFlags.JpegQuality, preserveResolution ? 95 : 80)]))
throw new IOException("视频画面编码失败");
frames.Add(new(firstIndex + frames.Count, frameIndex / video.Fps, jpeg));
}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index d2f35c6..6802258 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -1319,8 +1319,9 @@ internal static class Smoke
var video=Path.Combine(store.Root,"agent-standard.avi");
using(var writer=new VideoWriter())
{
- Check(writer.Open(video,FourCC.MJPG,10,new OpenCvSharp.Size(64,48)),"Agent test video opens");
- for(var i=0;i<40;i++){using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(i*4,60,90));writer.Write(frame);}
+ // 视频长边超过模型取样上限,便于区分保存的关键帧和分析缩图。
+ Check(writer.Open(video,FourCC.MJPG,10,new OpenCvSharp.Size(800,600)),"Agent test video opens");
+ for(var i=0;i<40;i++){using var frame=new Mat(600,800,MatType.CV_8UC3,new Scalar(i*4,60,90));writer.Write(frame);}
}
var client=new UiSopAgent();model.AgentClient=client;
Check(model.AgentContextLength==131702&&model.AgentMaxTokens==8192,"Assistant defaults use the requested context and output lengths");
@@ -1448,9 +1449,13 @@ internal static class Smoke
var regionList=editor.FindControl("StepRegionNavigation")!;
var triggerRegion=editor.FindControl("TriggerRegionRow")!.Children.OfType().Single();
var imageRegion=editor.FindControl("AiImageRegionPicker")!;
- Check(regionList.Items.OfType().Any(r=>r.Key=="料盒2"&&r.X1==4&&r.X2==30)
+ Check(regionList.Items.OfType().Any(r=>r.Key=="料盒2"&&r.X1==670&&r.X2==730)
&&Equals(triggerRegion.SelectedItem,"料盒2")&&Equals(imageRegion.SelectedItem,"料盒2"),
"A generated region appears in the region list and is selected for the step trigger and image crop");
+ // 区域位于缩图右边界之外,关键帧必须保留原视频坐标下的画面和原证据时间。
+ var savedStep=model.Recipe.Steps[originalCount+1];
+ Check(savedStep.KeyFrameImage?.PixelSize==new PixelSize(800,600)&&savedStep.KeyFrameSeconds==3.9,
+ "Applied keyframe keeps the original video resolution and evidence timestamp");
tabs.SelectedItem=tabs.Items.OfType().Single(t=>Equals(t.Header,"Agent助手"));
model.ApplyAgentDraftCommand.Execute();
Check(model.Recipe.Steps.Count==originalCount+2&&!model.ApplyAgentDraftCommand.CanExecute(),"A draft cannot be applied twice");
@@ -1940,7 +1945,7 @@ internal sealed class UiSopAgent : ISopVideoDraftClient
if(Hold){Held=true;return new TaskCompletionSource().Task;}
return Task.FromResult(new SopVideoDraft{Summary="放入并取走零件",
ObservedFrames=SopVideoSampler.ReadFrames(request.Video,[0,2,3.9],0,token),
- RegionAdjustments=[new(){Key="料盒2",Name="第二个料盒",X1=4,Y1=4,X2=30,Y2=30,EvidenceFrame=2,Note="取走零件的位置"}],Steps=[
+ RegionAdjustments=[new(){Key="料盒2",Name="第二个料盒",X1=670,Y1=4,X2=730,Y2=30,EvidenceFrame=2,Note="取走零件的位置"}],Steps=[
new(){Name="放入零件",Description="盒子里有零件",StartSeconds=0,EndSeconds=2,Region="work",EvidenceFrame=1},
new(){Name="取走零件",Description="盒子里没有零件",StartSeconds=2,EndSeconds=4,Region="料盒2",EvidenceFrame=2}]});
}