diff --git a/HAND_AI.md b/HAND_AI.md
index aa870c4..65ff793 100644
--- a/HAND_AI.md
+++ b/HAND_AI.md
@@ -8,6 +8,20 @@
手部动作表示“到了检查这个步骤的时机”。D3 的 `noul` 是该完成条件的正例概率,模型判断为真且达到配方阈值才算完成。D3 不生成解释,也没有自动拒答字段;界面显示的是实际概率和 HTTP 耗时,不能把它当成已标定准确率。纯手部配方不加载 YOLO,也不需要标注、训练零件模型。手部检测仍需要 `models/` 中的 palm 和 landmark ONNX。
+## 标准视频 Agent 助手
+
+配方编辑器的“Agent助手”页支持从标准 SOP 视频生成步骤草稿。先在“SOP流程视频”页停止并保存录像,或选择本地视频;填写完整的 Chat Completions 地址(如 `https://your-server/v1/chat/completions`)、视觉模型名和密钥,可补充工艺背景或拆分要求,然后点击“分析视频并生成步骤”。地址可自行设置,不绑定服务商。
+
+这里需要能够接收多张图片并生成文字的视觉模型。D3-lite 的 `/v1/systemone` 只能判定条件,不用于生成步骤;运行时仍使用原 D3 配置。助手请求采用 `messages`、`image_url` 的 JPEG data URL、`stream=false`、`max_tokens=4096`,模型返回包含步骤、时间段、参考帧和触发规则的 JSON。
+
+视频最长约 5 分钟;均匀抽取最多 4–60 张画面(默认上限 40,短视频实际帧数更少),最长边缩至 640 像素,JPEG 总量限制为 10MB。发送的是带时间戳的抽样图片,不是完整视频,短暂动作或细小物体可能漏掉。服务还需支持所选数量的多图输入。分析总超时为 5 分钟,可取消;取消或失败不修改当前配方。
+
+生成后逐步显示时间段、参考画面、名称、说明、区域键和提醒,可先修改。点击“将草稿添加到当前配方”才追加步骤,已有步骤和 ID 保留,同一份草稿不能重复添加。完成条件直接使用生成并编辑后的步骤说明;触发规则使用手在区域、离开区域或区域间移动。缺少区域时保留空值并提醒标定,不猜测坐标。到“步骤”页核对左右手、移动起终点及送检范围,最后点击“保存”写入配方文件。
+
+成功分析后仅将地址和模型名记入工作区的 `workspace/sop-agent.json`;密钥只在当前编辑器内存中使用,不落盘。也可通过环境变量 `SOPHELPER_AGENT_ENDPOINT`、`SOPHELPER_AGENT_MODEL`、`SOPHELPER_AGENT_API_KEY` 提供设置。图片会发送到填写的接口。
+
+验证使用合成视频与模拟视觉服务,覆盖实际取帧、多图请求、时间/区域校验、草稿编辑、取消、追加和密钥不落盘;尚未连接用户实际视觉模型,不代表真实 SOP 拆解准确率已验证。
+
## 配置接口
### 当前版本:本机 D3-lite
@@ -136,7 +150,7 @@ dotnet run --project src/SopHelper.Avalonia -p:BundlePythonRuntime=false
本分支已移除 YOLO 检测器、运行管线和相关设置界面。旧配方的模型路径不再加载;`object_*`、`hand_near_object` 已不支持,会提示改用手部或计时触发。`must_keep` / `required_objects` 不再检查,请将物料与装配结果写入步骤说明交给 D3 判断。旧的标注、权重和训练数据保留在原目录,不会自动删除。
-编辑器只保留“步骤、区域、全局设置、SOP流程视频”四页;已移除零件列表、检测模型、标注训练入口、目标类别、物品保留规则和 YOLO 阈值。曝光设置在“全局设置”中。打开编辑器不再初始化训练工具或 Python worker,默认构建和发布不再打包 YOLO/SAM2 权重与训练用 Python;本机 D3 服务仍使用自己独立的 Python 环境。
+编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页;已移除零件列表、检测模型、标注训练入口、目标类别、物品保留规则和 YOLO 阈值。曝光设置在“全局设置”中。打开编辑器不再初始化训练工具或 Python worker,默认构建和发布不再打包 YOLO/SAM2 权重与训练用 Python;本机 D3 服务仍使用自己独立的 Python 环境。
模型输出概率/置信度用于实验门控,尚未经过工位数据标定。需要用真实操作、未完成、遮挡和缺件样本验证误判率及响应时间。回归检查覆盖模拟服务、界面和裁剪取图;另已验证本机 D3 真实图片接口,但未验证现场流程准确率,也未解决间歇请求超过 200ms 的限制。
diff --git a/README.md b/README.md
index 827e2e8..8381d31 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
-2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频”四页。在原始相机画面上绘制区域;相机曝光在全局设置中。
+2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光在全局设置中。
3. 每个步骤填写原来的“说明”,AI 就用这段文字检查是否完成。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
@@ -26,6 +26,8 @@ pwsh -File tools/Start-HandAiD3.ps1
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。配方选择和相机选择会记忆;恢复选择不会自动开始采集。
+“Agent助手”可读取已录好的标准视频或选择本地视频,配置兼容 Chat Completions 的视觉模型完整接口地址、模型名和密钥后,抽取带时间戳的画面生成步骤草稿。草稿包含参考画面、步骤说明和手部触发规则,可修改后追加到当前配方,最后手动保存。地址和模型名会记住,密钥不写入文件。它与运行时 D3-lite 判定接口分开,需使用能生成文字的视觉模型;抽样分析可能漏掉短暂动作,必须核对草稿。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。
+
旧配方的 YOLO 模型绑定会被忽略,物体触发规则会提示已移除;需要手动改成手部/计时规则,并将物品要求写进步骤说明。不会根据旧类别名猜测或重写现场工艺。
## 数据和发布
@@ -51,6 +53,7 @@ pwsh -File tools/Publish-Avalonia.ps1
dotnet run --project tests/VisionDecision.Smoke
dotnet run --project tests/Pipeline.Smoke
dotnet run --project tests/Avalonia.Smoke -- --vision-only
+dotnet run --project tests/SopVideoAgent.Smoke
dotnet run --project tests/TensorPreprocessing.Smoke
```
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
index ead93fd..20f6b97 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
@@ -456,6 +456,74 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
index 48f849a..253697c 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
@@ -19,7 +19,7 @@ namespace SopHelper.VVMs.RecipeEditor;
/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
///
-public class RecipeEditorViewModel : BindableBase, IDialogAware
+public partial class RecipeEditorViewModel : BindableBase, IDialogAware
{
private RecipeNode _recipe = new();
private string _path = "";
@@ -54,6 +54,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
OpenImageCommand.RaiseCanExecuteChanged();
SaveCommand.RaiseCanExecuteChanged();
CloseCommand.RaiseCanExecuteChanged();
+ GenerateStepsCommand?.RaiseCanExecuteChanged();
}
}
public DelegateCommand CaptureImageCommand { get; }
@@ -97,7 +98,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
///
public RecipeEditorViewModel()
{
- SaveCommand = new DelegateCommand(Save, () => !IsCapturing && NameValidationMessage.Length == 0);
+ SaveCommand = new DelegateCommand(Save, () => !IsCapturing && !IsAgentBusy && NameValidationMessage.Length == 0);
CloseCommand = new DelegateCommand(async () =>
{
_closingDialog = true; CloseCommand.RaiseCanExecuteChanged();
@@ -106,6 +107,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
+ InitializeAgentCommands();
}
///
@@ -133,6 +135,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
Recipe = RecipeNode.From(config, fileName, _isNew);
Recipe.Changed += RefreshWarnings;
InitializeRecipeTools();
+ LoadAgentSettings();
RefreshWarnings();
}
@@ -158,9 +161,16 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true, selectedCameraProvider: _selectedCameraProvider);
RaisePropertyChanged(nameof(HasSopRecording));
+ UpdateAgentDefaultVideo();
}
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
- private Task ShutdownCoreAsync() => ShutdownSopRecordingAsync();
+ private async Task ShutdownCoreAsync()
+ {
+ _agentCancellation?.Cancel();
+ if (_agentTask is not null) await _agentTask;
+ ClearAgentDraft();
+ await ShutdownSopRecordingAsync();
+ }
public async Task ShutdownSopRecordingAsync()
{
if (SopRecording is null) return;
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs
new file mode 100644
index 0000000..2c18f87
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs
@@ -0,0 +1,197 @@
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Net.Http;
+using System.Text.Json;
+using OpenCvSharp;
+using Prism.Commands;
+using Prism.Mvvm;
+using SopHelper.Engine.Sop;
+using SopHelper.Engine.SopAgent;
+using SopHelper.Presentation;
+using SopHelper.Presentation.Imaging;
+
+namespace SopHelper.VVMs.RecipeEditor;
+
+public partial class RecipeEditorViewModel
+{
+ private static readonly HttpClient AgentHttp = new() { Timeout = Timeout.InfiniteTimeSpan, MaxResponseContentBufferSize = 1024 * 1024 };
+ public ISopVideoDraftClient AgentClient { get; set; } = new SopVideoDraftClient(AgentHttp);
+ private CancellationTokenSource? _agentCancellation;
+ private Task? _agentTask;
+ private SopVideoSample? _agentSample;
+ private bool _isAgentBusy, _draftApplied;
+ private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
+ private string _agentStatus = "选择标准 SOP 视频,设置视觉模型接口后生成步骤草稿。", _agentSummary = "";
+ private int _agentMaxFrames = 40;
+ public ObservableCollection AgentDraftSteps { get; } = [];
+ public string AgentEndpoint { get => _agentEndpoint; set => SetProperty(ref _agentEndpoint, value); }
+ public string AgentModel { get => _agentModel; set => SetProperty(ref _agentModel, value); }
+ public string AgentApiKey { get => _agentApiKey; set => SetProperty(ref _agentApiKey, value); }
+ public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
+ public int AgentMaxFrames { get => _agentMaxFrames; set => SetProperty(ref _agentMaxFrames, value); }
+ public string AgentVideoPath
+ {
+ get => _agentVideoPath;
+ set { if (SetProperty(ref _agentVideoPath, value) && !IsAgentBusy) ClearAgentDraft(); }
+ }
+ public string AgentStatus { get => _agentStatus; private set => SetProperty(ref _agentStatus, value); }
+ public string AgentSummary { get => _agentSummary; private set => SetProperty(ref _agentSummary, value); }
+ public bool AgentIsIdle => !IsAgentBusy;
+ public bool AgentCanEditDraft => !IsAgentBusy && !_draftApplied;
+ public bool IsAgentBusy
+ {
+ get => _isAgentBusy;
+ private set
+ {
+ if (!SetProperty(ref _isAgentBusy, value)) return;
+ RaisePropertyChanged(nameof(AgentIsIdle));
+ RaisePropertyChanged(nameof(AgentCanEditDraft));
+ GenerateStepsCommand.RaiseCanExecuteChanged(); CancelAgentCommand.RaiseCanExecuteChanged();
+ ApplyAgentDraftCommand.RaiseCanExecuteChanged(); BrowseAgentVideoCommand.RaiseCanExecuteChanged();
+ SaveCommand.RaiseCanExecuteChanged();
+ }
+ }
+ public DelegateCommand GenerateStepsCommand { get; private set; } = null!;
+ public DelegateCommand CancelAgentCommand { get; private set; } = null!;
+ public DelegateCommand ApplyAgentDraftCommand { get; private set; } = null!;
+ public DelegateCommand BrowseAgentVideoCommand { get; private set; } = null!;
+ private string AgentSettingsPath => Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "sop-agent.json");
+
+ private void InitializeAgentCommands()
+ {
+ GenerateStepsCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync(), () => !IsAgentBusy && !IsCapturing);
+ CancelAgentCommand = new DelegateCommand(() => _agentCancellation?.Cancel(), () => IsAgentBusy);
+ ApplyAgentDraftCommand = new DelegateCommand(ApplyAgentDraft, () => !IsAgentBusy && !_draftApplied && AgentDraftSteps.Count > 0);
+ BrowseAgentVideoCommand = new DelegateCommand(async () =>
+ {
+ var dialog = new OpenFileDialog { Title = "选择标准 SOP 视频", Filter = "视频|*.avi;*.mp4;*.mov;*.mkv;*.webm|所有文件|*.*" };
+ if (await dialog.ShowDialogAsync() == true) AgentVideoPath = dialog.FileName;
+ }, () => !IsAgentBusy);
+ }
+
+ private void LoadAgentSettings()
+ {
+ try
+ {
+ if (File.Exists(AgentSettingsPath))
+ {
+ using var document = JsonDocument.Parse(File.ReadAllText(AgentSettingsPath));
+ AgentEndpoint = document.RootElement.GetProperty("endpoint").GetString() ?? "";
+ AgentModel = document.RootElement.GetProperty("model").GetString() ?? "";
+ }
+ }
+ catch (Exception) { AgentStatus = "模型连接设置无法读取,请重新填写地址和模型名。"; }
+ AgentEndpoint = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_ENDPOINT") ?? AgentEndpoint;
+ AgentModel = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_MODEL") ?? AgentModel;
+ AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? "";
+ UpdateAgentDefaultVideo();
+ }
+ private void UpdateAgentDefaultVideo()
+ {
+ if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
+ }
+
+ private async Task AnalyzeVideoAsync()
+ {
+ if (IsAgentBusy || IsCapturing) return;
+ if (SopRecording?.IsRecording == true) { AgentStatus = "请先停止并保存 SOP 录像,再开始分析。"; return; }
+ if (!File.Exists(AgentVideoPath)) { AgentStatus = "请先录制标准 SOP 视频,或选择已有视频。"; return; }
+ if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")
+ || string.IsNullOrWhiteSpace(AgentModel)) { AgentStatus = "请先设置完整的视觉模型接口地址和模型名。"; return; }
+ if (AgentMaxFrames is < 4 or > 60 || AgentInstructions.Length > 4000) { AgentStatus = "最大抽帧数须为 4–60,补充要求须小于 4000 字。"; return; }
+ var path = AgentVideoPath; var maxFrames = AgentMaxFrames;
+ var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim());
+ var regions = Recipe.RegionNames.Where(r => !string.IsNullOrWhiteSpace(r)).ToArray();
+ var recipeName = Recipe.Name; var instructions = AgentInstructions;
+ _agentCancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5));
+ var token = _agentCancellation.Token;
+ IsAgentBusy = true;
+ AgentStatus = "正在读取标准 SOP 视频…";
+ var progress = new Progress(value => { if (IsAgentBusy) AgentStatus = value; });
+ try
+ {
+ var sample = await Task.Run(() => SopVideoSampler.Sample(path, maxFrames, token, progress), token);
+ AgentStatus = $"已抽取 {sample.Frames.Count} 帧,正在发送给视觉模型生成步骤…";
+ var draft = await AgentClient.AnalyzeAsync(new(recipeName, instructions, sample, regions), connection, token).WaitAsync(token);
+ token.ThrowIfCancellationRequested();
+ SopVideoDraftClient.Validate(draft, sample, regions);
+ ClearAgentDraft(); _agentSample = sample;
+ foreach (var step in draft.Steps) AgentDraftSteps.Add(new(step, sample.Frames[step.EvidenceFrame]));
+ AgentSummary = draft.Summary + (draft.Warnings.Count == 0 ? "" : "\n需核对:" + string.Join(";", draft.Warnings));
+ _draftApplied = false;
+ AgentStatus = $"已生成 {draft.Steps.Count} 步草稿(基于 {sample.Frames.Count} 张抽样画面)。请核对、修改后再添加到配方。";
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(AgentSettingsPath)!);
+ File.WriteAllText(AgentSettingsPath, JsonSerializer.Serialize(new { endpoint = connection.Endpoint, model = connection.Model }));
+ }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+ { AgentStatus += " 连接设置未能记住。"; }
+ }
+ catch (OperationCanceledException) { AgentStatus = "分析已取消或超时,当前配方未修改。"; }
+ catch (Exception error) when (error is ArgumentException or InvalidDataException or FileNotFoundException or FormatException)
+ { AgentStatus = "分析未完成:" + error.Message + " 当前配方未修改。"; }
+ catch (Exception) { AgentStatus = "分析失败,请检查视频、接口、模型名和密钥;当前配方未修改。"; }
+ finally
+ {
+ _agentCancellation.Dispose(); _agentCancellation = null;
+ IsAgentBusy = false;
+ }
+ }
+
+ private void ApplyAgentDraft()
+ {
+ if (IsAgentBusy || _draftApplied || _agentSample is null || AgentDraftSteps.Count == 0) return;
+ var draft = new SopVideoDraft { Steps = AgentDraftSteps.Select(row => row.Step).ToList() };
+ try { SopVideoDraftClient.Validate(draft, _agentSample, Recipe.RegionNames.Where(r => !string.IsNullOrWhiteSpace(r)).ToArray()); }
+ catch (FormatException error) { AgentStatus = "草稿未添加:" + error.Message; return; }
+ foreach (var row in AgentDraftSteps)
+ {
+ var step = row.Step; var node = Recipe.AddStep();
+ node.Name = step.Name; node.Description = step.Description;
+ node.StandardDurationMs = Math.Max(1, (int)Math.Round((step.EndSeconds - step.StartSeconds) * 1000));
+ node.Detection = new ConditionNode { Method = step.Method, Region = step.Region, FromRegion = step.FromRegion,
+ ToRegion = step.ToRegion, Hand = step.Hand, StableFrames = 3, Tolerance = 10 };
+ var imageRegion = step.Method == ConditionMethod.HandMove ? step.ToRegion : step.Region;
+ node.AiImageMode = string.IsNullOrWhiteSpace(imageRegion) ? VisionImageMode.FullFrame : VisionImageMode.FixedRegion;
+ node.AiImageRegion = imageRegion;
+ }
+ _draftApplied = true;
+ RaisePropertyChanged(nameof(AgentCanEditDraft));
+ ApplyAgentDraftCommand.RaiseCanExecuteChanged();
+ RefreshWarnings();
+ AgentStatus = $"已添加 {AgentDraftSteps.Count} 步到配方草稿,原有步骤保留。请到“步骤”页检查触发区域和步骤说明,最后点击保存。";
+ }
+
+ private void ClearAgentDraft()
+ {
+ foreach (var row in AgentDraftSteps) row.Dispose();
+ AgentDraftSteps.Clear(); _agentSample = null; _draftApplied = false; AgentSummary = "";
+ RaisePropertyChanged(nameof(AgentCanEditDraft));
+ ApplyAgentDraftCommand?.RaiseCanExecuteChanged();
+ }
+}
+
+public sealed class AgentDraftRow : BindableBase, IDisposable
+{
+ public SopDraftStep Step { get; }
+ public string Name { get => Step.Name; set { Step.Name = value; RaisePropertyChanged(); } }
+ public string Description { get => Step.Description; set { Step.Description = value; RaisePropertyChanged(); } }
+ public string Region
+ {
+ get => Step.Method == ConditionMethod.HandMove ? Step.ToRegion : Step.Region;
+ set { if (Step.Method == ConditionMethod.HandMove) Step.ToRegion = value; else Step.Region = value; RaisePropertyChanged(); RaisePropertyChanged(nameof(Note)); }
+ }
+ public string Timeline => $"{TimeSpan.FromSeconds(Step.StartSeconds):mm\\:ss\\.f} – {TimeSpan.FromSeconds(Step.EndSeconds):mm\\:ss\\.f}";
+ public string EvidenceLabel { get; }
+ public string Note => Step.Note + (string.IsNullOrWhiteSpace(Region) ? " 请在添加后设置触发区域。" : "");
+ public BitmapSource EvidenceImage { get; }
+ public AgentDraftRow(SopDraftStep step, SopVideoFrame frame)
+ {
+ Step = step; EvidenceLabel = $"参考画面 {frame.Seconds:F1}s";
+ using var image = Cv2.ImDecode(frame.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 Dispose() => EvidenceImage.Dispose();
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
index fe5c9f2..91d3cf6 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
@@ -128,6 +128,10 @@ public static partial class SopConfigLoader
config.Warnings.Add($"步骤 {step.Id}({step.Name})未设置完成条件,请选择判定方法;等待后完成请选择 time_elapsed");
continue;
}
+ if (condition.Method is ConditionMethod.HandInRegion or ConditionMethod.HandLeaveRegion && string.IsNullOrWhiteSpace(condition.Region))
+ config.Warnings.Add($"步骤 {step.Id}({step.Name})请设置触发区域");
+ if (condition.Method == ConditionMethod.HandMove && (string.IsNullOrWhiteSpace(condition.FromRegion) || string.IsNullOrWhiteSpace(condition.ToRegion)))
+ config.Warnings.Add($"步骤 {step.Id}({step.Name})请设置起点和终点区域");
if (!supported.Contains(condition.Method))
{
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
index 0412389..1a8df88 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
@@ -110,7 +110,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
{
if (string.IsNullOrWhiteSpace(value)) return "";
return regions.FirstOrDefault(r => r.Equals(value, StringComparison.OrdinalIgnoreCase))
- ?? throw new FormatException($"模型引用了未定义的区域:{value},请重新分析");
+ ?? throw new FormatException("模型引用了未定义的区域,请先标定区域或重新分析");
}
}
}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index fec370e..ea876af 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -16,6 +16,7 @@ using SopHelper.VVMs.RecipeEditor;
using System.Text.Json;
using Avalonia.VisualTree;
using OpenCvSharp;
+using SopHelper.Engine.SopAgent;
using Window = Avalonia.Controls.Window;
using Point = Avalonia.Point;
using Size = Avalonia.Size;
@@ -650,7 +651,7 @@ internal static class Smoke
{
Check(!editor.GetVisualDescendants().OfType().Any(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成"),"AI confirmation no longer has an opt-out checkbox");
var headers=editor.GetVisualDescendants().OfType().Select(t=>t.Header?.ToString()).ToArray();
- Check(headers.SequenceEqual(new[]{"步骤","区域","全局设置","SOP流程视频"}),"Recipe editor removes parts, detection-model and annotation/training settings");
+ Check(headers.SequenceEqual(new[]{"步骤","区域","全局设置","SOP流程视频","Agent助手"}),"Recipe editor retains hand/AI controls and adds the video assistant without YOLO settings");
Check(editor.FindControl("TargetPartPicker") is null,"Step editor removes YOLO target-class picker");
Check(editorVm.Recipe.Methods.All(m=>!m.StartsWith("object_")&&m!="hand_near_object"),"Only hand and timer trigger methods are offered");
Check(editor.FindControl("CameraExposureInput") is not null,"Camera exposure remains available in global settings");
@@ -674,6 +675,7 @@ internal static class Smoke
editorVm.Recipe.Steps.Remove(added);
editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[0];await Task.Delay(20);
Save(dialog,"hand-ai-confirmation-settings");
+ await CheckVideoAgent(editorVm,editor,dialog,store);
}
finally{await editorVm.ShutdownAsync();dialog.Close();}
var settingsView=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(sop);
@@ -712,6 +714,47 @@ internal static class Smoke
finally{sop.IsRunning=false;engine.Stop();}
}
+ private static async Task CheckVideoAgent(RecipeEditorViewModel model,RecipeEditor editor,Window dialog,RecipeWorkspace store)
+ {
+ 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);}
+ }
+ var client=new UiSopAgent();model.AgentClient=client;
+ model.AgentVideoPath=video;model.AgentEndpoint="https://custom.invalid/v1/chat/completions";
+ model.AgentModel="custom-vision";model.AgentApiKey="not-to-be-saved";model.AgentMaxFrames=4;
+ var originalCount=model.Recipe.Steps.Count;
+ var configPath=store.ConfigPath("手部AI验证");var before=File.ReadAllBytes(configPath);
+ var tabs=editor.GetVisualDescendants().OfType().First();tabs.SelectedIndex=4;await Task.Delay(30);
+ Check(editor.FindControl("AgentEndpointBox")!.IsEffectivelyVisible,"Assistant exposes configurable endpoint and model fields");
+ model.GenerateStepsCommand.Execute();
+ for(var i=0;i<300&&model.IsAgentBusy;i++)await Task.Delay(10);
+ Check(!model.IsAgentBusy&&model.AgentDraftSteps.Count==2,"Assistant samples video and presents model-generated draft steps");
+ Check(client.Connection?.Endpoint==model.AgentEndpoint&&client.Connection.Model==model.AgentModel&&client.Request?.Video.Frames.Count==3,"Assistant uses current connection and real sampled frames");
+ Check(model.Recipe.Steps.Count==originalCount&&File.ReadAllBytes(configPath).SequenceEqual(before),"Generating a draft does not replace steps or write the recipe");
+ var settings=File.ReadAllText(Path.Combine(store.Root,"workspace","sop-agent.json"));
+ Check(settings.Contains("custom-vision")&&!settings.Contains(model.AgentApiKey)&&!settings.Contains("apiKey"),"Only endpoint/model are remembered; key is not persisted");
+ model.AgentDraftSteps[0].Description="把连接器放入盒子,盒内可见连接器";
+ Save(dialog,"sop-video-agent-draft");
+ client.Hold=true;
+ model.GenerateStepsCommand.Execute();
+ for(var i=0;i<200&&!client.Held;i++)await Task.Delay(10);
+ Check(model.IsAgentBusy&&client.Held,"Assistant cancellation test reaches pending model request");
+ model.CancelAgentCommand.Execute();
+ for(var i=0;i<100&&model.IsAgentBusy;i++)await Task.Delay(10);
+ Check(!model.IsAgentBusy&&model.Recipe.Steps.Count==originalCount,"Cancelling analysis never mutates the recipe");
+ model.ApplyAgentDraftCommand.Execute();
+ Check(model.Recipe.Steps.Count==originalCount+2&&model.Recipe.Steps[0].Name=="装配","Applying generated steps preserves existing steps and appends the draft");
+ Check(model.Recipe.Steps[originalCount].Description=="把连接器放入盒子,盒内可见连接器"&&model.Recipe.Steps[originalCount].Detection?.Method=="hand_leave_region","Edited draft description becomes the D3 criterion with a hand trigger");
+ model.ApplyAgentDraftCommand.Execute();
+ Check(model.Recipe.Steps.Count==originalCount+2&&!model.ApplyAgentDraftCommand.CanExecute(),"A draft cannot be applied twice");
+ Check(File.ReadAllBytes(configPath).SequenceEqual(before),"Adding draft steps still requires explicit recipe save");
+ foreach(var step in model.Recipe.Steps.Skip(originalCount).ToArray())model.Recipe.RemoveStep(step);
+ model.Recipe.SelectedStep=model.Recipe.Steps[0];tabs.SelectedIndex=0;
+ }
+
private static void Save(Window window,string name)
{
window.UpdateLayout();
@@ -746,3 +789,18 @@ internal sealed class UiVisionDecision : SopHelper.Engine.Sop.IVisionDecisionCli
public Task DecideAsync(SopHelper.Engine.Sop.VisionDecisionRequest request,CancellationToken token)
{Called.TrySetResult();return Result.Task;}
}
+
+internal sealed class UiSopAgent : ISopVideoDraftClient
+{
+ public SopAgentConnection? Connection;
+ public SopVideoAnalysisRequest? Request;
+ public bool Hold,Held;
+ public Task AnalyzeAsync(SopVideoAnalysisRequest request,SopAgentConnection connection,CancellationToken token)
+ {
+ Request=request;Connection=connection;
+ if(Hold){Held=true;return new TaskCompletionSource().Task;}
+ return Task.FromResult(new SopVideoDraft{Summary="放入并取走零件",Steps=[
+ new(){Name="放入零件",Description="盒子里有零件",StartSeconds=0,EndSeconds=2,Region="work",EvidenceFrame=1},
+ new(){Name="取走零件",Description="盒子里没有零件",StartSeconds=2,EndSeconds=4,Region="work",EvidenceFrame=2}]});
+ }
+}