From 2a424cd6514f806c05380c72a37726a0b11dc173 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 28 Nov 2026 15:23:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=AD=A5=E9=AA=A4=E8=AF=B4?= =?UTF-8?q?=E6=98=8E=E6=97=B6=E6=8C=89=E7=BD=AE=E4=BF=A1=E5=BA=A6=E7=AD=9B?= =?UTF-8?q?=E9=80=89=E5=B9=B6=E6=94=AF=E6=8C=81=E8=87=AA=E5=8A=A8=E9=87=8D?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../RecipeEditor/OptimizeStepsViewModel.cs | 111 +++++++++--------- .../VVMs/RecipeEditor/RecipeEditor.axaml | 4 +- .../OptimizeStepsChecks.cs | 41 ++++--- 4 files changed, 82 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index 96d66a4..6770884 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配 “Agent助手”接收本地标准视频路径,通过工具自主查看不同时间点、继续检查细节,再生成步骤草稿。模型需支持 Chat Completions 工具调用和图片输入,不需要上传完整视频。每次工具读取上限默认 3 张,可修改并记住。草稿包含时间段、参考画面、步骤说明和手部规则,修改后追加到配方,最后手动保存。接口地址、模型名、密钥及生成参数自动保存,下次启动恢复;模型列表可自动获取。运行时仍由 djev 确认步骤完成。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。 -“Agent助手 → 优化步骤”优化当前配方已有步骤的完成说明,无需重新分析视频。默认选择“全部步骤”,也可以选择“指定步骤”并在下拉框中选定一步。选定范围内的每步都须先填写说明并获取关键帧;Agent同时接收原说明和与djev测试相同的送检图,依据图片保留工艺含义做小幅改写,生成9条同义描述;不得编造图中内容或删减原要求,图片与原说明明显冲突时停止生成。9条改写,与原说明一起各判定一次,每步共10次。判定复用“测试判定”的送检规则、djev接口和全局毫秒超时,整帧模式使用整图,固定区域模式先裁剪再缩放,区域缺失或越界时停止且不回退整图;跟手模式依赖运行轨迹,静态关键帧不能还原时提示使用“测试流程”,不发送替代图片。选有效结果中置信度最高的说明,同分优先保留原文或较早候选;10次均无有效结果则保留原说明。选定范围内的步骤全部完成后统一更新编辑中的配方,点击“保存”落盘;取消、失败或过程中说明/关键帧发生变化时不应用结果。Agent页面的优化明细区显示实际送检图及区域坐标、原说明以及编号01–10的全部候选描述,实时列出每条置信度、判定状态和原因,并标记最高分选中项。超时及无效结果照样公开,注明不参与择优;尚未测试的候选显示“待测试”。每步完成后完整明细也保留在Agent对话中,可选择复制,不依赖有长度上限的判定日志。最高分只代表这张关键帧的完成概率,使用前仍需核对改写是否完整保留原要求。 +“Agent助手 → 优化步骤”优化当前配方已有步骤的完成说明,无需重新分析视频。默认使用“指定步骤”,可在下拉框中选定一步,也可切换到“全部步骤”。选定范围内的每步都须先填写说明并获取关键帧;Agent同时接收原说明和与djev测试相同的送检图,依据图片保留工艺含义做小幅改写,生成9条同义描述;不得编造图中内容或删减原要求,图片与原说明明显冲突时停止生成。9条改写,与原说明一起各判定一次,每轮共10次。判定复用“测试判定”的送检规则、djev接口和全局毫秒超时,整帧模式使用整图,固定区域模式先裁剪再缩放,区域缺失或越界时停止且不回退整图;跟手模式依赖运行轨迹,静态关键帧不能还原时提示使用“测试流程”,不发送替代图片。从判定为完成且达到该步骤 AI 最低置信度的候选中选最高分,同分优先保留原文或较早候选。首轮没有达标候选时,使用相同原说明和送检图重新生成及测试一轮。两轮均未达标则保留原说明。选定范围内的步骤处理完毕后统一更新配方,点击“保存”写入文件。取消、失败或优化期间配方发生变化时,已有说明会保留。Agent 页面的优化结果区显示实际送检图、区域坐标和入选说明及其置信度,对话中也可查看入选结果。 旧配方的 YOLO 模型绑定会被忽略,物体触发规则会提示已移除;需要手动改成手部/计时规则,并将物品要求写进步骤说明。不会根据旧类别名猜测或重写现场工艺。 diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs index 31e0938..06dd21a 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs @@ -1,4 +1,4 @@ -// 编辑器的步骤说明优化部分:按范围生成同义候选、逐条测试并展示报告,回写前检查配方未被并发修改。 +// 编辑器的步骤说明优化部分:按范围生成同义候选、逐条测试并展示达标结果,回写前检查配方未被并发修改。 using OpenCvSharp; using System.Collections.ObjectModel; @@ -12,7 +12,7 @@ namespace SopHelper.VVMs.RecipeEditor; public partial class RecipeEditorViewModel { - private int _optimizationScopeIndex; + private int _optimizationScopeIndex = 1; public ISopDescriptionClient DescriptionClient { get; set; } = new SopDescriptionClient(AgentHttp); public DelegateCommand OptimizeStepsCommand { get; private set; } = null!; @@ -35,7 +35,7 @@ public partial class RecipeEditorViewModel OptimizationReports.Clear(); } - /// 固定本次优化的目标步骤,逐条测试原说明及九条同义候选,并在配方快照仍一致时统一回写。 + /// 固定本次优化的目标步骤,每轮测试原说明及九条同义候选,首轮未达标时重试一次,并在配方快照仍一致时统一回写。 private async Task OptimizeStepsAsync() { if (!CanStartAgentStepTask()) return; @@ -50,7 +50,7 @@ public partial class RecipeEditorViewModel : recipeSteps.AsEnumerable(); var steps = targetSteps.Select(node => new { - Node = node, node.Id, node.Name, node.Description, node.KeyFrameBase64, node.KeyFrameSeconds + Node = node, node.Id, node.Name, node.Description, node.KeyFrameBase64, node.KeyFrameSeconds, node.AiMinConfidence }).ToArray(); if (steps.Length == 0) { AgentStatus = "请选择要优化的步骤。"; return; } var missing = steps.FirstOrDefault(step => string.IsNullOrWhiteSpace(step.Description) || string.IsNullOrWhiteSpace(step.KeyFrameBase64)); @@ -76,6 +76,7 @@ public partial class RecipeEditorViewModel ResetAgentStepTaskHistory(); var results = new List<(StepNode Node, string Description)>(); var unchanged = 0; + var retried = 0; var currentLabel = ""; try { @@ -89,37 +90,48 @@ public partial class RecipeEditorViewModel 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); + var report = new StepOptimizationReport(label, jpeg, step.KeyFrameSeconds, prepared.Scope); OptimizationReports.Add(report); - var rewrites = await DescriptionClient.RewriteAsync(step.Name, step.Description, jpeg, connection, token).WaitAsync(token); - // 对注入的客户端同样检查,保证每步始终恰好10个候选。 - var candidates = new[] { step.Description }.Concat(rewrites).ToArray(); - if (candidates.Length != 10 || candidates.Any(string.IsNullOrWhiteSpace) - || candidates.Distinct(StringComparer.Ordinal).Count() != 10) - throw new FormatException("Agent未返回9条有效且不同的同义完成说明"); - report.SetCandidates(candidates); string? best = null; - var bestIndex = -1; - var bestConfidence = double.NegativeInfinity; - for (var i = 0; i < candidates.Length; i++) + VisionDecisionResult? bestResult = null; + // 每轮使用相同原说明、送检图和达标阈值;首轮没有达标候选时重新生成一次。 + for (var round = 1; round <= 2 && best is null; round++) { token.ThrowIfCancellationRequested(); - AgentStatus = $"{label}:测试 {i + 1}/10(当前第 {results.Count + 1}/{steps.Length} 步)…"; - var description = candidates[i]; - var request = new VisionDecisionRequest(recipeName, step.Id, step.Name, description, description, 0, DateTime.Now, jpeg, - SourceSeconds: step.KeyFrameSeconds, TimeoutMs: timeout); - var result = await RunStepDecisionAsync($"{label} · 优化 {i + 1}/10", request, token); - token.ThrowIfCancellationRequested(); - var valid = result.EffectiveStatus is VisionDecisionStatus.Completed or VisionDecisionStatus.NotCompleted - && double.IsFinite(result.Confidence) && result.Confidence is >= 0 and <= 1; - AppendStepDecisionLog($"{label} · 优化 {i + 1}/10:{result.EffectiveStatus};置信度 {result.Confidence:P1};{result.Reason}"); - report.SetResult(i, result, valid); - if (valid && result.Confidence > bestConfidence) { best = description; bestConfidence = result.Confidence; bestIndex = i; } + if (round == 2) retried++; + AgentStatus = $"{label}:第 {round} 轮生成9条同义完成说明…"; + var rewrites = await DescriptionClient.RewriteAsync(step.Name, step.Description, jpeg, connection, token).WaitAsync(token); + // 对注入的客户端同样检查,保证每轮恰好10个不同候选。 + var candidates = new[] { step.Description }.Concat(rewrites).ToArray(); + if (candidates.Length != 10 || candidates.Any(string.IsNullOrWhiteSpace) + || candidates.Distinct(StringComparer.Ordinal).Count() != 10) + throw new FormatException("Agent未返回9条有效且不同的同义完成说明"); + for (var i = 0; i < candidates.Length; i++) + { + token.ThrowIfCancellationRequested(); + var testLabel = $"{label} · 第 {round} 轮优化 {i + 1}/10"; + AgentStatus = $"{testLabel}(当前第 {results.Count + 1}/{steps.Length} 步)…"; + var description = candidates[i]; + var request = new VisionDecisionRequest(recipeName, step.Id, step.Name, description, description, 0, DateTime.Now, jpeg, + SourceSeconds: step.KeyFrameSeconds, TimeoutMs: timeout); + var result = await RunStepDecisionAsync(testLabel, request, token); + token.ThrowIfCancellationRequested(); + AppendStepDecisionLog($"{testLabel}:{result.EffectiveStatus};置信度 {result.Confidence:P1};{result.Reason}"); + // 与单步测试判定使用同一放行条件;分数相同时保留原文或先测试的候选。 + if (result.EffectiveStatus == VisionDecisionStatus.Completed && result.Completed + && double.IsFinite(result.Confidence) && result.Confidence >= step.AiMinConfidence + && result.Confidence is >= 0 and <= 1 + && (bestResult is null || result.Confidence > bestResult.Confidence)) + { + best = description; + bestResult = result; + } + } } - report.Select(bestIndex); + report.ShowResult(best, bestResult, step.AiMinConfidence); results.Add((step.Node, best ?? step.Description)); if (best is null) unchanged++; - AgentChatMessages.Add(new("优化步骤 · 全部候选及置信度", report.Text)); + AgentChatMessages.Add(new("优化步骤", $"{label}\n{report.Text}")); } token.ThrowIfCancellationRequested(); // 单步优化也保留整份配方的并发检查,避免用旧送检配置或已被替换的节点回写。 @@ -127,11 +139,11 @@ public partial class RecipeEditorViewModel || System.Text.Json.JsonSerializer.Serialize(recipe.ToConfig()) != configSnapshot || !recipe.Steps.SequenceEqual(recipeSteps) || steps.Any(s => s.Node.Description != s.Description || s.Node.Name != s.Name || s.Node.Id != s.Id - || s.Node.KeyFrameBase64 != s.KeyFrameBase64 || s.Node.KeyFrameSeconds != s.KeyFrameSeconds)) + || s.Node.KeyFrameBase64 != s.KeyFrameBase64 || s.Node.KeyFrameSeconds != s.KeyFrameSeconds || s.Node.AiMinConfidence != s.AiMinConfidence)) { AgentStatus = "优化期间配方、送检规则或关键帧已变化,结果未应用,请重新优化。"; return; } foreach (var result in results) result.Node.Description = result.Description; RefreshWarnings(); - AgentStatus = $"已优化 {steps.Length} 步,每步测试10次;{unchanged} 步无有效判定保留原说明。请点击“保存”写入配方文件。"; + AgentStatus = $"已优化 {steps.Length} 步,{retried} 步重试一次;{unchanged} 步未达标,保留原说明。请点击“保存”写入配方文件。"; } catch (OperationCanceledException) { AgentStatus = "步骤优化已取消或请求超时,当前配方未修改。"; } catch (ArgumentException error) @@ -157,49 +169,32 @@ public partial class RecipeEditorViewModel } } +/// 展示该步骤入选的说明与实际送检图,持有图像直至报告清除。 public sealed class StepOptimizationReport : BindableBase, IDisposable { public string Label { get; } - public string Original { get; } public BitmapSource EvidenceImage { get; } public string EvidenceLabel { get; } - private string[] _candidates = []; - private readonly string[] _scores = Enumerable.Repeat("待测试", 10).ToArray(); - private int _selected = -1; + private string _text = "正在生成并测试候选说明…"; private string _outcome = "正在优化,尚未应用到配方。"; public string Outcome { get => _outcome; set => SetProperty(ref _outcome, value); } - public string Text => $"{Label}\n原说明:{Original}\n" - + (_candidates.Length == 0 ? "正在请Agent查看上方关键帧并改写…" : string.Join("\n\n", _candidates.Select((text, i) => - $"{i + 1:00} · {(i == 0 ? "原说明" : "同义改写")}{(i == _selected ? " · ★ 最高分选中" : "")}\n{text}\n{_scores[i]}"))); + public string Text { get => _text; private set => SetProperty(ref _text, value); } - public StepOptimizationReport(string label, string original, byte[] jpeg, double? seconds, string scope) + public StepOptimizationReport(string label, byte[] jpeg, double? seconds, string scope) { - Label = label; Original = original; + Label = label; EvidenceLabel = "Agent与djev共用此送检图 · " + scope + (seconds is { } time ? $" · {time:F3}s" : ""); using var image = Cv2.ImDecode(jpeg, ImreadModes.Color); EvidenceImage = BitmapSource.Create(image.Width, image.Height, 96, 96, PixelFormats.Bgr24, null, image.Data, checked((int)(image.Step() * image.Height)), checked((int)image.Step())); } - public void SetCandidates(string[] candidates) { _candidates = candidates; RaisePropertyChanged(nameof(Text)); } - public void SetResult(int index, VisionDecisionResult result, bool valid) + /// 界面仅显示选中的说明及其置信度,两轮均未达标时显示保留原说明的结果。 + public void ShowResult(string? description, VisionDecisionResult? result, double threshold) { - var status = result.EffectiveStatus switch - { - VisionDecisionStatus.Completed => "完成", - VisionDecisionStatus.NotCompleted => "未完成", - VisionDecisionStatus.TimedOut => "超时", - VisionDecisionStatus.Unsupported => "不可用", - _ => "证据不足或接口异常" - }; - _scores[index] = $"置信度:{(valid ? result.Confidence.ToString("P4") : "无有效分数")}(返回值:{result.Confidence:R})\n" - + $"判定:{status};{(valid ? "参与择优" : "不参与择优")};{result.Reason}"; - RaisePropertyChanged(nameof(Text)); - } - public void Select(int index) - { - _selected = index; - Outcome = index < 0 ? "10次均无有效结果,保留原说明。" : $"选中第 {index + 1} 条;同分优先原说明或较早候选,尚未应用。"; - RaisePropertyChanged(nameof(Text)); + Text = result is null + ? $"两轮均未达标(阈值 {threshold:P1}),保留原说明。" + : $"选中说明:{description}\n置信度 {result.Confidence:P1}(阈值 {threshold:P1})\n{result.Reason}"; } + public void Dispose() => EvidenceImage.Dispose(); } diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index d4349b3..22db0c6 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -505,7 +505,7 @@