134 lines
9.2 KiB
C#
134 lines
9.2 KiB
C#
// SOP 时序观察部分:维护过程窗口,校验多帧结果引用及前后步骤的证据时间顺序。
|
||
|
||
using SopHelper.Engine.Common;
|
||
|
||
namespace SopHelper.Engine.Sop;
|
||
|
||
public partial class SopEngine
|
||
{
|
||
private readonly Dictionary<int, ObservationState> _observationWindows = [];
|
||
private readonly Dictionary<int, double> _acceptedEvidenceTimes = [];
|
||
private sealed class ObservationState(StepDef step, CaptureGate gate)
|
||
{
|
||
public StepDef Step = step;
|
||
public CaptureGate Gate = gate;
|
||
public ObservationEvidenceWindow Window = new(step.AiConfirmation!);
|
||
public long LastObservedFrame = -1, NextRequestAt;
|
||
public bool FollowingArmed;
|
||
public VisionDecisionStatus LastStatus = VisionDecisionStatus.Insufficient;
|
||
public string LastReason = "尚未获得足够的过程证据";
|
||
}
|
||
/// <summary>为每个步骤保存独立门控与过程窗口,逐帧复用已有观察状态。</summary>
|
||
private ObservationState EnsureObservationWindow(int index, StepDef step, CaptureGate gate)
|
||
{
|
||
if (_observationWindows.TryGetValue(index, out var existing)) return existing;
|
||
var state = new ObservationState(step, gate); _observationWindows[index] = state; return state;
|
||
}
|
||
/// <summary>只在存在取图回调时采集;视频结束后的收尾调用仅消费既有证据。</summary>
|
||
private void UpdateObservationWindows(FrameResult frame, Func<byte[]>? captureJpeg, Func<RegionDef?, byte[]>? captureImage)
|
||
{
|
||
if (captureJpeg is null && captureImage is null) return; // EOF 只消费已有证据,不制造尾帧。
|
||
foreach (var pair in _observationWindows.ToArray())
|
||
{
|
||
if (pair.Key < _index) { _observationWindows.Remove(pair.Key); continue; }
|
||
ObserveWindow(pair.Key, pair.Value, frame, captureJpeg, captureImage);
|
||
}
|
||
}
|
||
/// <summary>防止重复帧进入窗口,动作触发后开始观察;证据准备充分时允许后续步骤继续采集。</summary>
|
||
private void ObserveWindow(int index, ObservationState state, FrameResult frame, Func<byte[]>? captureJpeg, Func<RegionDef?, byte[]>? captureImage)
|
||
{
|
||
if (state.LastObservedFrame == frame.FrameId || captureJpeg is null && captureImage is null) return;
|
||
state.LastObservedFrame = frame.FrameId;
|
||
var time = frame.SourceSeconds ?? (frame.Timestamp - DateTime.UnixEpoch).TotalSeconds;
|
||
var trigger = EvaluateCaptureGate(state.Step, frame, state.Gate, "observation");
|
||
if (state.Window.Expired && !state.Window.HasFreshEvidence && _pendingDecision is null && trigger.RawMatched == false)
|
||
{
|
||
var evaluator = new ConditionEvaluator(_config.Sop.Settings, _regions);
|
||
evaluator.NoteStepEntered(state.Step.Id, frame.Timestamp);
|
||
state.Gate = new(evaluator, new()); state.Window = new(state.Step.AiConfirmation!);
|
||
state.LastStatus = VisionDecisionStatus.Insufficient; state.LastReason = "已重新开始观察,等待新的操作触发";
|
||
return;
|
||
}
|
||
if (trigger.IsMet && !state.Window.Opened)
|
||
{
|
||
state.Window.Open(time);
|
||
Log("info", $"步骤 {state.Step.Id} 打开过程观察窗口(帧 {frame.FrameId}),尚未判定完成");
|
||
}
|
||
if (state.Window.WantsFrame(frame.FrameId, time))
|
||
{
|
||
var image = CaptureDecision(state.Step, frame, state.Gate.HandRegion, captureJpeg, captureImage, out var error, notify: false);
|
||
if (image is not null) state.Window.Add(new(frame.FrameId, frame.Timestamp, image.Request.Jpeg, frame.SourceSeconds));
|
||
else state.LastReason = error ?? "观察取图失败";
|
||
}
|
||
state.Window.Advance(time);
|
||
if (state.Window.Opened && state.Window.Ready && state.Window.Frames.Count >= 3 && !state.FollowingArmed && _nextCaptureIndex == index)
|
||
{
|
||
state.FollowingArmed = true;
|
||
ArmFollowingStep(frame, state.Step); // 后续动作继续采集,逻辑完成仍按 AI 证据顺序确认。
|
||
}
|
||
}
|
||
/// <summary>要求支持时序的客户端和真实过程证据;完成帧、支持帧、置信度及步骤时间顺序均需校验。</summary>
|
||
private ConditionResult EvaluateObservationStep(StepDef step, FrameResult frame, Func<byte[]>? captureJpeg,
|
||
Func<RegionDef?, byte[]>? captureImage, out byte[]? evidence)
|
||
{
|
||
evidence = null;
|
||
var client = VisionDecisionClient;
|
||
if (_pendingDecision is null && client is not { SupportsSequences: true })
|
||
return new() { Message = "过程时序服务未配置或不支持多图输入,未使用单帧代判" };
|
||
var gate = _nextCaptureIndex == _index && _followingGate is { } following ? following : new CaptureGate(_evaluator, _handImageRegion);
|
||
var state = EnsureObservationWindow(_index, step, gate);
|
||
ObserveWindow(_index, state, frame, captureJpeg, captureImage);
|
||
if (_pendingDecision is { } pending)
|
||
{
|
||
if (!pending.Task.IsCompleted) return new() { Message = $"正在判定 {pending.Request.Frames?.Count} 张过程画面,现场继续采集…" };
|
||
_pendingDecision = null; pending.Cancellation.Dispose();
|
||
var decision = pending.Task.GetAwaiter().GetResult();
|
||
state.NextRequestAt = Environment.TickCount64 + Math.Max(500, step.AiConfirmation!.RetryDelayMs);
|
||
var source = pending.Request.Frames ?? [];
|
||
var completed = source.FirstOrDefault(f => f.FrameId == decision.CompletionFrameId);
|
||
var confirmation = VisionDecisionEvidence.SupportEnd(pending.Request, decision);
|
||
var met = decision.Completed && decision.EffectiveStatus == VisionDecisionStatus.Completed && completed is not null && confirmation is not null
|
||
&& decision.EvidenceFrameIds is { Count: >= 2 } ids && ids.Distinct().Count() >= 2
|
||
&& ids.All(id => source.Any(f => f.FrameId == id)) && ids.Contains(completed.FrameId)
|
||
&& double.IsFinite(decision.Confidence) && decision.Confidence >= step.AiConfirmation.MinConfidence && decision.Confidence <= 1;
|
||
state.LastStatus = met ? VisionDecisionStatus.Completed : decision.EffectiveStatus == VisionDecisionStatus.Completed
|
||
? VisionDecisionStatus.Insufficient : decision.EffectiveStatus;
|
||
state.LastReason = decision.Reason;
|
||
var evaluated = pending.Request;
|
||
if (met)
|
||
{
|
||
evidence = completed!.Jpeg;
|
||
evaluated = pending.Request with { FrameId = completed.FrameId, CapturedAt = completed.CapturedAt, Jpeg = completed.Jpeg,
|
||
SourceSeconds = completed.SourceSeconds, ConfirmationEvidence = confirmation };
|
||
_acceptedEvidenceTimes[_index] = ObservationEvidenceWindow.Time(completed);
|
||
_observationWindows.Remove(_index);
|
||
}
|
||
DecisionEvaluated?.Invoke(evaluated, decision, met);
|
||
return new() { IsMet = met, Message = $"过程判定{(met ? "完成" : state.LastStatus == VisionDecisionStatus.NotCompleted ? "未完成" : "证据不足")}:{decision.Reason}" };
|
||
}
|
||
var eof = captureJpeg is null && captureImage is null;
|
||
if (state.Window.Error is { } invalid) return new() { Message = "证据不足:" + invalid };
|
||
if (state.Window.HasFreshEvidence && (state.Window.Ready || state.Window.Expired || eof)
|
||
&& Environment.TickCount64 >= state.NextRequestAt)
|
||
{
|
||
var frames = state.Window.Frames.Where(f => !_acceptedEvidenceTimes.TryGetValue(_index - 1, out var prior)
|
||
|| ObservationEvidenceWindow.Time(f) >= prior).ToArray();
|
||
state.Window.LastSentVersion = state.Window.Version;
|
||
if (frames.Length < 3) return new() { Message = "证据不足:前序完成后没有三张有效过程画面,未放行" };
|
||
frames = VisualEvidenceSampler.Select(frames, step.AiConfirmation!.ObservationRequestMaxFrames);
|
||
var last = frames[^1];
|
||
var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, step.ResolveCompletionCriteria(),
|
||
last.FrameId, last.CapturedAt, last.Jpeg, VisionEvidenceMode.Sequence, frames, last.SourceSeconds,
|
||
TimeoutMs: RealtimeDecisionPolicy.DeadlineFor(_config.Sop.Settings));
|
||
var cancellation = new CancellationTokenSource();
|
||
_pendingDecision = new(RunDecisionAsync(client!, request, cancellation.Token), last.Jpeg, cancellation, request);
|
||
DecisionCaptured?.Invoke(request); DecisionSubmitted?.Invoke(request);
|
||
Log("info", $"步骤 {step.Id} 提交过程窗口:{frames.Length} 张,原始帧 {frames[0].FrameId}–{last.FrameId}");
|
||
return new() { Message = $"已发送 {frames.Length} 张过程证据,等待判定…" };
|
||
}
|
||
return new() { Message = !state.Window.Opened ? "等待操作触发,保留操作前画面…"
|
||
: state.Window.Expired ? $"观察窗口已结束,{(state.LastStatus == VisionDecisionStatus.NotCompleted ? "未完成" : "证据不足")}:{state.LastReason};等待新的操作或人工复核"
|
||
: $"观察中({state.Window.Frames.Count} 张);{state.LastReason}" };
|
||
}
|
||
}
|