476 lines
30 KiB
C#
476 lines
30 KiB
C#
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;
|
||
using SopHelper.Training;
|
||
|
||
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 SopVideoAgentClient(AgentHttp);
|
||
private CancellationTokenSource? _agentCancellation;
|
||
private object? _agentPromptSession;
|
||
private Task? _agentTask;
|
||
private SopVideoSample? _agentSample;
|
||
private bool _isAgentBusy, _draftApplied;
|
||
private bool _agentSettingsLoaded, _agentUseForSequence;
|
||
public bool AgentUseForSequence { get => _agentUseForSequence; set { if (SetProperty(ref _agentUseForSequence, value)) SaveAgentSettings(); } }
|
||
private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
|
||
private string _agentStatus = "", _agentSummary = "";
|
||
private int _agentMaxFrames = 3;
|
||
private int _agentContextLength = 131702, _agentMaxTokens = 8192, _agentTimeoutSeconds = 300;
|
||
private double _agentTemperature = .2, _agentTopP = .9;
|
||
private CancellationTokenSource? _modelDiscoveryCancellation;
|
||
private bool _agentClosed;
|
||
private readonly List<SopAgentChatTurn> _agentConversation = [];
|
||
private readonly List<StepNode> _agentAppliedNodes = [];
|
||
private string _agentChatInput = "";
|
||
public ObservableCollection<AgentChatLine> AgentChatMessages { get; } = [];
|
||
public string AgentChatInput
|
||
{
|
||
get => _agentChatInput;
|
||
set { if (SetProperty(ref _agentChatInput, value)) SendAgentChatCommand?.RaiseCanExecuteChanged(); }
|
||
}
|
||
public string AgentApplyLabel => _agentAppliedNodes.Count == 0 ? "添加到配方" : "更新配方";
|
||
public ObservableCollection<string> AgentModels { get; } = [];
|
||
public int AgentContextLength { get => _agentContextLength; set { if (SetProperty(ref _agentContextLength, value)) SaveAgentSettings(); } }
|
||
public int AgentMaxTokens { get => _agentMaxTokens; set { if (SetProperty(ref _agentMaxTokens, value)) SaveAgentSettings(); } }
|
||
public int AgentTimeoutSeconds { get => _agentTimeoutSeconds; set { if (SetProperty(ref _agentTimeoutSeconds, value)) SaveAgentSettings(); } }
|
||
public double AgentTemperature { get => _agentTemperature; set { if (SetProperty(ref _agentTemperature, value)) SaveAgentSettings(); } }
|
||
public double AgentTopP { get => _agentTopP; set { if (SetProperty(ref _agentTopP, value)) SaveAgentSettings(); } }
|
||
public ObservableCollection<AgentDraftRow> AgentDraftSteps { get; } = [];
|
||
public string AgentEndpoint { get => _agentEndpoint; set { if (SetProperty(ref _agentEndpoint, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||
public string AgentModel { get => _agentModel; set { if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
|
||
public string AgentApiKey { get => _agentApiKey; set { if (SetProperty(ref _agentApiKey, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||
public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
|
||
public int AgentMaxFrames { get => _agentMaxFrames; set { if (SetProperty(ref _agentMaxFrames, value)) SaveAgentSettings(); } }
|
||
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();
|
||
SendAgentChatCommand.RaiseCanExecuteChanged();
|
||
ClearAgentChatCommand.RaiseCanExecuteChanged();
|
||
VerifyAgentDraftCommand?.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!;
|
||
public DelegateCommand FetchAgentModelsCommand { get; private set; } = null!;
|
||
public DelegateCommand SendAgentChatCommand { get; private set; } = null!;
|
||
public DelegateCommand ClearAgentChatCommand { 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);
|
||
SendAgentChatCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync(AgentChatInput.Trim()),
|
||
() => !IsAgentBusy && !IsCapturing && !string.IsNullOrWhiteSpace(AgentChatInput));
|
||
ClearAgentChatCommand = new DelegateCommand(ClearAgentConversation, () => !IsAgentBusy);
|
||
FetchAgentModelsCommand = new DelegateCommand(() => ScheduleModelDiscovery(immediate: true));
|
||
CancelAgentCommand = new DelegateCommand(() => _agentCancellation?.Cancel(), () => IsAgentBusy);
|
||
ApplyAgentDraftCommand = new DelegateCommand(ApplyAgentDraft, CanApplyAgentDraft);
|
||
VerifyAgentDraftCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync("请基于当前草稿保留工艺要求,用标准视频回测,并仅按实际失败证据修订,返回完整草稿;不要重新从头生成,不要只回复讨论文字。", verifyDraft: true),
|
||
() => !IsAgentBusy && !IsCapturing && 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()
|
||
{
|
||
_agentSettingsLoaded = false;
|
||
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() ?? "";
|
||
AgentApiKey = document.RootElement.TryGetProperty("apiKey", out var key) ? key.GetString() ?? "" : "";
|
||
var root = document.RootElement;
|
||
if (root.TryGetProperty("useForSequence", out var sequence)) AgentUseForSequence = sequence.GetBoolean();
|
||
if (root.TryGetProperty("maxFrames", out var frames)) AgentMaxFrames = frames.GetInt32();
|
||
if (root.TryGetProperty("contextLength", out var context)) AgentContextLength = context.GetInt32();
|
||
if (root.TryGetProperty("maxTokens", out var output)) AgentMaxTokens = output.GetInt32();
|
||
if (root.TryGetProperty("temperature", out var temperature)) AgentTemperature = temperature.GetDouble();
|
||
if (root.TryGetProperty("topP", out var topP)) AgentTopP = topP.GetDouble();
|
||
if (root.TryGetProperty("timeoutSeconds", out var timeout)) AgentTimeoutSeconds = timeout.GetInt32();
|
||
}
|
||
}
|
||
catch (Exception) { AgentStatus = "模型连接设置无法读取,请重新填写地址和模型名。"; }
|
||
AgentEndpoint = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_ENDPOINT") ?? AgentEndpoint;
|
||
AgentModel = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_MODEL") ?? AgentModel;
|
||
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? AgentApiKey;
|
||
_agentSettingsLoaded = true;
|
||
UpdateAgentDefaultVideo();
|
||
ScheduleModelDiscovery();
|
||
}
|
||
|
||
private void SaveAgentSettings()
|
||
{
|
||
if (!_agentSettingsLoaded) return;
|
||
var temporary = AgentSettingsPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||
try
|
||
{
|
||
Directory.CreateDirectory(Path.GetDirectoryName(AgentSettingsPath)!);
|
||
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
|
||
if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||
using (var stream = new FileStream(temporary, options))
|
||
JsonSerializer.Serialize(stream, new { endpoint = AgentEndpoint, model = AgentModel, apiKey = AgentApiKey,
|
||
useForSequence = AgentUseForSequence, maxFrames = AgentMaxFrames, contextLength = AgentContextLength, maxTokens = AgentMaxTokens,
|
||
temperature = AgentTemperature, topP = AgentTopP, timeoutSeconds = AgentTimeoutSeconds });
|
||
File.Move(temporary, AgentSettingsPath, overwrite: true);
|
||
}
|
||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||
{ AgentStatus = "模型设置保存失败。"; }
|
||
finally
|
||
{
|
||
try { File.Delete(temporary); }
|
||
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
|
||
}
|
||
}
|
||
|
||
private void ScheduleModelDiscovery(bool immediate = false)
|
||
{
|
||
if (!_agentSettingsLoaded || _agentClosed) return;
|
||
_modelDiscoveryCancellation?.Cancel();
|
||
_modelDiscoveryCancellation = null;
|
||
AgentModels.Clear();
|
||
if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")) return;
|
||
var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||
_modelDiscoveryCancellation = cancellation;
|
||
_ = DiscoverModelsAsync(AgentEndpoint.Trim(), AgentApiKey.Trim(), cancellation, immediate);
|
||
}
|
||
|
||
private async Task DiscoverModelsAsync(string endpoint, string key, CancellationTokenSource cancellation, bool immediate)
|
||
{
|
||
try
|
||
{
|
||
if (!immediate) await Task.Delay(600, cancellation.Token);
|
||
var models = await new SopVideoDraftClient(AgentHttp).GetModelsAsync(endpoint, key, cancellation.Token);
|
||
cancellation.Token.ThrowIfCancellationRequested();
|
||
foreach (var model in models) AgentModels.Add(model);
|
||
if (string.IsNullOrWhiteSpace(AgentModel) && models.Count > 0) AgentModel = models[0];
|
||
if (!IsAgentBusy) AgentStatus = models.Count == 0 ? "没有可用模型。" : $"已获取 {models.Count} 个模型。";
|
||
}
|
||
catch (OperationCanceledException) { ReportDiscoveryError("获取模型超时。"); }
|
||
catch (HttpRequestException error)
|
||
{
|
||
ReportDiscoveryError(error.StatusCode switch
|
||
{
|
||
System.Net.HttpStatusCode.Unauthorized => "获取模型失败:401,请填写正确的密钥。",
|
||
System.Net.HttpStatusCode.Forbidden => "获取模型失败:403,密钥无访问权限。",
|
||
System.Net.HttpStatusCode.NotFound => "获取模型失败:404,请检查接口地址。",
|
||
{ } status => $"获取模型失败:HTTP {(int)status}。",
|
||
_ => "无法连接模型服务。"
|
||
});
|
||
}
|
||
catch (Exception) { ReportDiscoveryError("模型列表响应格式无效。"); }
|
||
finally
|
||
{
|
||
if (ReferenceEquals(_modelDiscoveryCancellation, cancellation)) _modelDiscoveryCancellation = null;
|
||
cancellation.Dispose();
|
||
}
|
||
|
||
void ReportDiscoveryError(string message)
|
||
{
|
||
if (ReferenceEquals(_modelDiscoveryCancellation, cancellation) && !_agentClosed && !IsAgentBusy)
|
||
AgentStatus = message;
|
||
}
|
||
}
|
||
private void UpdateAgentDefaultVideo()
|
||
{
|
||
if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
|
||
}
|
||
|
||
private async Task AnalyzeVideoAsync(string? userMessage = null, bool verifyDraft = false)
|
||
{
|
||
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 < 2 or > 60 || AgentInstructions.Length > 4000) { AgentStatus = "最大抽帧数须为 2–60,补充要求须小于 4000 字。"; return; }
|
||
if (userMessage is { Length: > 4000 }) { AgentStatus = "消息须小于 4000 字。"; return; }
|
||
var path = AgentVideoPath; var maxFrames = AgentMaxFrames;
|
||
var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim(),
|
||
AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds);
|
||
try { SopVideoDraftClient.ValidateSettings(connection); }
|
||
catch (ArgumentException error) { AgentStatus = error.Message; return; }
|
||
var regionDefinitions = Recipe.ToConfig().Sop.Regions;
|
||
var regions = regionDefinitions.Keys.ToArray();
|
||
var recipeName = Recipe.Name; var instructions = AgentInstructions;
|
||
_agentCancellation = new CancellationTokenSource(); // 每次模型请求和每轮回测分别限时,支持整段视频多轮验证。
|
||
var token = _agentCancellation.Token;
|
||
IsAgentBusy = true;
|
||
AgentStatus = "正在读取标准 SOP 视频…";
|
||
var activeAnalysis = _agentCancellation;
|
||
SopAgentRunLog? runLog = null;
|
||
var promptSession = _agentPromptSession = new object();
|
||
var promptLog = new Progress<SopAgentPrompt>(prompt =>
|
||
{
|
||
if (_agentClosed || !ReferenceEquals(_agentPromptSession, promptSession)) return;
|
||
AgentChatMessages.Add(new("发送给 Agent 的提示词", prompt.Text, true,
|
||
(prompt.Round == 0 ? "历史摘要请求" : $"第 {prompt.Round} 轮") + $" · 估算输入 {prompt.EstimatedTokens:N0} / 上下文 {prompt.ContextLength:N0} tokens"
|
||
+ (string.IsNullOrWhiteSpace(prompt.Compression) ? "" : "\n" + prompt.Compression)));
|
||
});
|
||
var progress = new Progress<string>(value => { if (IsAgentBusy && ReferenceEquals(_agentCancellation, activeAnalysis)) AgentStatus = value; });
|
||
var verificationRequired = verifyDraft || userMessage is not null && _agentVerificationRequired;
|
||
var verificationTemplate = verifyDraft ? CreateAgentVerificationTemplate() : null;
|
||
Func<SopVideoDraft, SopVideoSample, CancellationToken, Task<SopDraftVerification>>? verify = verifyDraft
|
||
? async (draft, video, cancellation) =>
|
||
{
|
||
runLog?.Write(new("verification_start", 0, JsonSerializer.Serialize(draft)));
|
||
var result = await VerifyAgentDraftAsync(draft, video, verificationTemplate!, progress, cancellation);
|
||
runLog?.Write(new("verification_end", 0, JsonSerializer.Serialize(result)));
|
||
return result;
|
||
} : null;
|
||
try
|
||
{
|
||
runLog = new SopAgentRunLog(DesktopPlatform.WorkspaceRoot, connection.ApiKey);
|
||
runLog.Write(new("session_start", 0, JsonSerializer.Serialize(new
|
||
{
|
||
Recipe = recipeName, Video = path, Mode = verifyDraft ? "verify_and_revise" : userMessage is null ? "generate" : "chat",
|
||
instructions, userMessage, Endpoint = new UriBuilder(endpoint) { UserName = "", Password = "", Query = "", Fragment = "" }.Uri.ToString(),
|
||
connection.Model, connection.ContextLength, connection.MaxTokens,
|
||
connection.Temperature, connection.TopP, connection.TimeoutSeconds, MaxFrames = maxFrames, VerifyDraft = verifyDraft
|
||
})));
|
||
AgentChatMessages.Add(new("分析日志", "本次分析过程自动保存:" + runLog.Path));
|
||
var sample = await Task.Run(() => SopVideoSampler.ReadInfo(path, token), token);
|
||
runLog.Write(new("video_info", 0, JsonSerializer.Serialize(sample)));
|
||
SopVideoDraft? draft;
|
||
string reply;
|
||
if (userMessage is not null)
|
||
{
|
||
if (_agentSample is not null && (sample.Path != _agentSample.Path || sample.SourceLength != _agentSample.SourceLength
|
||
|| sample.SourceModifiedUtc != _agentSample.SourceModifiedUtc)) throw new InvalidDataException("视频已变化,请重新生成步骤");
|
||
sample = sample with { Frames = _agentSample?.Frames ?? [] };
|
||
AgentChatInput = "";
|
||
AgentChatMessages.Add(new("我", userMessage));
|
||
var result = await AgentClient.ChatAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||
userMessage, _agentConversation.ToArray(), CreateAgentDraftSnapshot(), regionDefinitions,
|
||
CreateAgentImageScopes(), VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write,
|
||
VerifyCurrentDraftFirst: verifyDraft,
|
||
CheckReference: verifyDraft ? (candidate, video, id, cancellation) => new SopDraftReferenceVerifier().CheckAsync(
|
||
SopDraftConfigBuilder.Build(verificationTemplate!, candidate), candidate, video, id, cancellation) : null), connection, token).WaitAsync(token);
|
||
token.ThrowIfCancellationRequested();
|
||
draft = result.Draft; reply = result.Reply;
|
||
sample = sample with { Frames = result.ObservedFrames };
|
||
if (draft is not null) SopVideoDraftClient.Validate(draft, sample, regions, regionDefinitions);
|
||
_agentConversation.Add(new("user", userMessage));
|
||
_agentConversation.Add(new("assistant", reply));
|
||
}
|
||
else
|
||
{
|
||
draft = await AgentClient.AnalyzeAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||
RegionDefinitions: regionDefinitions, VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write), connection, token).WaitAsync(token);
|
||
sample = sample with { Frames = draft.ObservedFrames };
|
||
reply = string.IsNullOrWhiteSpace(draft.Summary) ? $"已生成 {draft.Steps.Count} 步。" : draft.Summary;
|
||
}
|
||
token.ThrowIfCancellationRequested();
|
||
if (draft is not null)
|
||
{
|
||
SopVideoDraftClient.Validate(draft, sample, regions, regionDefinitions);
|
||
if (verify is not null && draft.Verification is null) draft.Verification = await verify(draft, sample, token);
|
||
token.ThrowIfCancellationRequested();
|
||
token.ThrowIfCancellationRequested();
|
||
ClearAgentDraft(clearConversation: false, forgetApplied: userMessage is null);
|
||
_agentVerificationRequired = verificationRequired;
|
||
for (var i = 0; i < draft.Steps.Count; i++)
|
||
{
|
||
var step = draft.Steps[i];
|
||
var actual = draft.Verification?.Images.LastOrDefault(image => image.StepId == i + 1);
|
||
var row = new AgentDraftRow(step, sample.Frames[step.EvidenceFrame], actual);
|
||
row.PropertyChanged += DraftRowChanged;
|
||
AgentDraftSteps.Add(row);
|
||
}
|
||
PresentVerification(draft);
|
||
AgentSummary = draft.Summary + (draft.Warnings.Count == 0 ? "" : "\n需核对:" + string.Join(";", draft.Warnings));
|
||
AgentStatus = draft.Verification is { Passed: false } ? "草稿回测未通过,未修改配方。可继续对话修订。"
|
||
: draft.Verification?.Passed == true ? $"已更新 {draft.Steps.Count} 步草稿,标准视频回测通过。"
|
||
: _agentVerificationRequired ? $"已更新 {draft.Steps.Count} 步草稿,请单独点击“回测并修订”后更新配方。"
|
||
: $"已更新 {draft.Steps.Count} 步草稿。可先编辑或添加到配方,再按需点击“回测并修订”。";
|
||
}
|
||
else AgentStatus = "";
|
||
_agentSample = sample;
|
||
if (userMessage is null) { _agentConversation.Clear(); _agentConversation.Add(new("assistant", reply)); }
|
||
AgentChatMessages.Add(new("Agent", reply));
|
||
}
|
||
catch (OperationCanceledException error)
|
||
{
|
||
await WaitForAgentVerificationCleanupAsync();
|
||
AgentStatus = token.IsCancellationRequested ? "分析已取消,当前配方未修改。" : "模型请求或本地回测超时,当前配方未修改。";
|
||
AgentChatMessages.Add(new("系统", AgentStatus));
|
||
try { runLog?.Write(new("cancelled_or_timeout", 0, error.ToString())); }
|
||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException) { }
|
||
}
|
||
catch (Exception error) { ReportAgentFailure(error, connection, runLog); }
|
||
finally
|
||
{
|
||
try { runLog?.Write(new("session_end", 0, AgentStatus)); }
|
||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException)
|
||
{ AgentChatMessages.Add(new("错误详情", "分析日志写入失败:" + logError.Message)); }
|
||
finally
|
||
{
|
||
try { runLog?.Dispose(); }
|
||
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(), RegionAdjustments = [.. _agentRegionAdjustments] };
|
||
var definitions = Recipe.ToConfig().Sop.Regions;
|
||
try { SopVideoDraftClient.Validate(draft, _agentSample, definitions.Keys.ToArray(), definitions); }
|
||
catch (FormatException error) { AgentStatus = "草稿未添加:" + error.Message; return; }
|
||
var resolved = SopDraftConfigBuilder.Build(CreateAgentVerificationTemplate(), draft);
|
||
if (_agentVerificationRequired && (_agentVerifiedFingerprint is null || _agentVerifiedFingerprint != SopDraftConfigBuilder.Fingerprint(resolved, _agentSample)))
|
||
{
|
||
_agentVerifiedFingerprint = null;
|
||
AgentVerificationSummary = "草稿、配方设置或区域已变化,请重新回测后应用。";
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged(); return;
|
||
}
|
||
var currentVideo = new FileInfo(_agentSample.Path);
|
||
if (!currentVideo.Exists || _agentSample.SourceLength > 0 && (currentVideo.Length != _agentSample.SourceLength || currentVideo.LastWriteTimeUtc != _agentSample.SourceModifiedUtc))
|
||
{ AgentStatus = "标准视频已变化,请重新生成并回测。"; return; }
|
||
foreach (var adjusted in _agentRegionAdjustments)
|
||
{
|
||
var source = resolved.Sop.Regions[adjusted.Key];
|
||
var region = Recipe.Regions.FirstOrDefault(r => r.Key.Equals(adjusted.Key, StringComparison.OrdinalIgnoreCase)) ?? Recipe.AddRegion(adjusted.Key);
|
||
region.X1 = source.X1; region.Y1 = source.Y1; region.X2 = source.X2; region.Y2 = source.Y2;
|
||
region.Name = source.Name; region.Description = source.Description; region.Color = source.Color;
|
||
}
|
||
var existing = _agentAppliedNodes.Where(Recipe.Steps.Contains).ToArray();
|
||
var applied = new List<StepNode>();
|
||
for (var i = 0; i < AgentDraftSteps.Count; i++)
|
||
{
|
||
var step = AgentDraftSteps[i].Step; 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;
|
||
}
|
||
foreach (var removed in existing.Skip(AgentDraftSteps.Count)) Recipe.RemoveStep(removed);
|
||
_agentAppliedNodes.Clear(); _agentAppliedNodes.AddRange(applied);
|
||
RaisePropertyChanged(nameof(AgentApplyLabel));
|
||
_draftApplied = true;
|
||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||
ApplyAgentDraftCommand.RaiseCanExecuteChanged();
|
||
RefreshWarnings();
|
||
AgentStatus = $"已写入 {AgentDraftSteps.Count} 步,待保存。"
|
||
+ (_agentVerificationRequired && Recipe.Steps.Count > applied.Count ? "已验证草稿步骤;完整配方请到“SOP流程视频”测试。" : "");
|
||
}
|
||
|
||
private SopVideoDraft? CreateAgentDraftSnapshot()
|
||
{
|
||
if (AgentDraftSteps.Count == 0) return null;
|
||
var draft = JsonSerializer.Deserialize<SopVideoDraft>(JsonSerializer.Serialize(new SopVideoDraft
|
||
{ Summary = AgentSummary, Steps = AgentDraftSteps.Select(row => row.Step).ToList(), RegionAdjustments = [.. _agentRegionAdjustments] }))!;
|
||
if (_draftApplied)
|
||
for (var i = 0; i < Math.Min(draft.Steps.Count, _agentAppliedNodes.Count); i++)
|
||
{
|
||
var node = _agentAppliedNodes[i]; var step = draft.Steps[i];
|
||
step.Name = node.Name; step.Description = node.Description;
|
||
step.Method = node.Detection?.Method ?? step.Method;
|
||
step.Region = node.Detection?.Region ?? ""; step.FromRegion = node.Detection?.FromRegion ?? "";
|
||
step.ToRegion = node.Detection?.ToRegion ?? ""; step.Hand = node.Detection?.Hand ?? "any";
|
||
step.StableFrames = node.Detection?.StableFrames; step.Tolerance = node.Detection?.Tolerance;
|
||
step.ImageMode = node.AiImageMode; step.ImageRegion = node.AiImageRegion;
|
||
}
|
||
return draft;
|
||
}
|
||
|
||
private IReadOnlyList<SopAgentImageScope> CreateAgentImageScopes()
|
||
=> AgentDraftSteps.Select((row, index) =>
|
||
{
|
||
var existing = index < _agentAppliedNodes.Count ? _agentAppliedNodes[index] : null;
|
||
return new SopAgentImageScope(index + 1, existing?.AiImageMode ?? VisionImageMode.FixedRegion,
|
||
existing?.AiImageRegion ?? (row.Step.Method == ConditionMethod.HandMove ? row.Step.ToRegion : row.Step.Region),
|
||
existing?.AiHandPadding ?? 160, existing?.AiHandMinSize ?? 320, existing?.AiHandMemoryMs ?? 3000, existing?.AiEvidenceMode ?? VisionEvidenceMode.SingleFrame);
|
||
}).ToArray();
|
||
|
||
private void ClearAgentConversation() { _agentPromptSession = null; _agentConversation.Clear(); AgentChatMessages.Clear(); }
|
||
|
||
private void ClearAgentDraft(bool clearConversation = true, bool forgetApplied = true)
|
||
{
|
||
foreach (var row in AgentDraftSteps) { row.PropertyChanged -= DraftRowChanged; row.Dispose(); }
|
||
_agentVerifiedFingerprint = null;
|
||
_agentVerificationRequired = false;
|
||
_agentRegionAdjustments.Clear();
|
||
AgentVerificationSummary = "";
|
||
RaisePropertyChanged(nameof(AgentRegionAdjustmentsSummary));
|
||
AgentDraftSteps.Clear(); _agentSample = null; _draftApplied = false; AgentSummary = "";
|
||
if (clearConversation) ClearAgentConversation();
|
||
if (forgetApplied) _agentAppliedNodes.Clear();
|
||
RaisePropertyChanged(nameof(AgentApplyLabel));
|
||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||
ApplyAgentDraftCommand?.RaiseCanExecuteChanged();
|
||
VerifyAgentDraftCommand?.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
|
||
public sealed record AgentChatLine(string Speaker, string Text, bool IsPrompt = false, string Summary = "")
|
||
{
|
||
public bool IsRegular => !IsPrompt;
|
||
}
|
||
|
||
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 bool IsHandMove => Step.Method == ConditionMethod.HandMove;
|
||
public string RegionLabel => IsHandMove ? "终点区域" : "触发区域";
|
||
public string FromRegion { get => Step.FromRegion; set { Step.FromRegion = 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 + $" 触发:{Step.Method}/{Step.Hand};稳定 {Step.StableFrames?.ToString() ?? "沿用"} 帧;送检:{Step.ImageRegion ?? Region}"
|
||
+ (string.IsNullOrWhiteSpace(Region) ? " 触发区域未设置。" : "");
|
||
public BitmapSource EvidenceImage { get; }
|
||
public AgentDraftRow(SopDraftStep step, SopVideoFrame frame, SopDraftVerificationImage? actual = null)
|
||
{
|
||
Step = step; EvidenceLabel = actual is null ? $"参考画面 {frame.Seconds:F1}s" : $"回测送检 {actual.Seconds:F1}s · {actual.Confidence:P1}";
|
||
using var image = Cv2.ImDecode(actual?.Jpeg ?? 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();
|
||
}
|