aisop/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ContinuousChecks.cs

254 lines
18 KiB
C#

// SOP 限时检查部分:持续采集候选、按间隔送检;预算到期未通过则记录异常并跳过。
using SopHelper.Engine.Common;
namespace SopHelper.Engine.Sop;
public readonly record struct StepCheckWindowProgress(double RemainingMs, double TotalMs);
public partial class SopEngine
{
/// <summary>读取当前步骤真实检查窗口的剩余时间,不触发检查或改变重试规则。</summary>
public StepCheckWindowProgress? GetCheckWindowProgress(int stepId)
{
if (State != EngineState.Running || StepAt(_index)?.Id != stepId
|| !_continuousChecks.TryGetValue(_index, out var state) || !state.BudgetStarted
|| state.Step.AiConfirmation?.CheckWindowMs is not > 0) return null;
var total = state.Step.AiConfirmation.CheckWindowMs;
return new(Math.Clamp(total - state.ElapsedMs, 0, total), total);
}
private const int HandSettleMs = 100;
private readonly Dictionary<int, ContinuousCheck> _continuousChecks = [];
public event Action<int, IReadOnlyList<VisionEvidenceFrame>>? DecisionCandidatesObserved;
private double PriorCompletedEvidenceTime() => _acceptedEvidenceTimes.Where(p => p.Key < _index)
.Select(p => p.Value).DefaultIfEmpty(double.NegativeInfinity).Max();
private sealed class ContinuousCheck(StepDef step, CaptureGate gate)
{
public StepDef Step = step;
public CaptureGate Gate = gate;
public ObservationEvidenceWindow Window = new(new AiConfirmation
{
ObservationPreRollMs = step.AiConfirmation!.ObservationPreRollMs,
ObservationSampleMs = step.AiConfirmation.ObservationSampleMs,
ObservationMinMs = step.AiConfirmation.ObservationMinMs,
// 候选证据可能早于前序判定;采集上限独立于本步检查预算,仍受帧数和字节预算约束。
ObservationMaxMs = 60000,
ObservationMaxFrames = step.AiConfirmation.ObservationMaxFrames,
});
public bool Triggered, SawQuiet, BudgetStarted, StoredBoundary, StoredOutside, FollowCurrentResult, GateWasMet;
public double? OutsideSince;
public List<VisionEvidenceFrame> Boundaries = [];
public Dictionary<long, double> Inspected = [];
public long LastFrame = -1, SentFrame = -1, StartedAt, LastSubmittedAt, FinishedAt;
public double BudgetSeconds, LatestSeconds, LastMotionSeconds;
public double LatestTriggerSeconds = double.NegativeInfinity, LastSubmittedSourceSeconds = double.NegativeInfinity;
public VisionTriggerObservation? TriggerObservation;
public int Attempts, SentVersion;
public Dictionary<HandType, (double X, double Y)> Anchors = [];
public string Reason = "尚未获得检查结果";
public double ElapsedMs => BudgetStarted ? Math.Max((LatestSeconds - BudgetSeconds) * 1000, Environment.TickCount64 - StartedAt) : 0;
}
/// <summary>按步骤索引复用检查状态,避免逐帧重新创建窗口而丢失证据与预算。</summary>
private ContinuousCheck EnsureContinuousStep(int index, StepDef step, CaptureGate gate)
{
if (_continuousChecks.TryGetValue(index, out var existing)) return existing;
return _continuousChecks[index] = new(step, gate);
}
/// <summary>逐帧更新当前及后续已创建的检查窗口,使 AI 等待期间仍能记录现场动作。</summary>
private void UpdateContinuousChecks(FrameResult frame, Func<byte[]>? capture, Func<RegionDef?, byte[]>? crop)
{
foreach (var pair in _continuousChecks.ToArray())
if (pair.Key >= _index) ObserveContinuousStep(pair.Key, pair.Value, frame, capture, crop);
}
/// <summary>记录指定手别的动作、停稳及边界图像;以来源时间驱动采样,同一帧只观察一次。</summary>
private void ObserveContinuousStep(int index, ContinuousCheck state, FrameResult frame,
Func<byte[]>? capture, Func<RegionDef?, byte[]>? crop)
{
if (capture is null && crop is null || state.LastFrame == frame.FrameId) return;
var firstObservation = state.LastFrame == -1;
state.LastFrame = frame.FrameId;
var seconds = frame.SourceSeconds ?? (frame.Timestamp - DateTime.UnixEpoch).TotalSeconds;
state.LatestSeconds = seconds;
var mode = DetectionHands.Normalize(state.Step.Detection?.Hand);
var selected = DetectionHands.Select(frame.Hands, mode).GroupBy(h => h.HandType).ToDictionary(g => g.Key, g => ((double)g.First().Center.Cx, (double)g.First().Center.Cy));
var movement = Math.Max(1, Math.Sqrt((double)frame.Size.W * frame.Size.W + (double)frame.Size.H * frame.Size.H) * .01);
var moved = selected.Count != state.Anchors.Count || selected.Any(h => !state.Anchors.TryGetValue(h.Key, out var prior)
|| Math.Sqrt(Math.Pow(h.Value.Item1 - prior.X, 2) + Math.Pow(h.Value.Item2 - prior.Y, 2)) > movement);
if (!state.Triggered && state.Gate.RequireRelease && state.SawQuiet && moved && selected.Count > 0)
{
// 连续工序可以始终位于同一操作区;“停稳后重新运动”也是新动作边界。
state.Gate.RequireRelease = false; state.Gate.Evaluator.Reset();
Log("info", $"步骤 {state.Step.Id} 检测到停稳后的新运动,重新启用区域触发");
}
if (firstObservation || moved)
{
state.LastMotionSeconds = seconds; state.Anchors = selected;
state.StoredBoundary = false;
}
else if ((seconds - state.LastMotionSeconds) * 1000 >= HandSettleMs)
state.SawQuiet = true;
var trigger = EvaluateCaptureGate(state.Step, frame, state.Gate, "continuous");
if (trigger.IsMet && !state.GateWasMet)
{
state.LatestTriggerSeconds = seconds;
state.TriggerObservation = new(frame.FrameId, frame.Timestamp, frame.SourceSeconds, state.Step.Detection!.Method);
}
state.GateWasMet = trigger.IsMet;
if (!state.Triggered && trigger.IsMet)
{
state.Triggered = true;
state.LastMotionSeconds = seconds; state.Window.Open(seconds);
Log("info", $"步骤 {state.Step.Id} 操作事件触发,开始采集候选证据;轮到本步后限时检查");
// 跟踪立即向后推进,不等检查结束或模型返回;同一次区域停留仍受 RequireRelease 保护。
if (_nextCaptureIndex == index) ArmFollowingStep(frame, state.Step);
}
if (state.Triggered && state.ElapsedMs >= state.Step.AiConfirmation!.CheckWindowMs) return;
if (IsHandInside(state.Step, frame)) { state.OutsideSince = null; state.StoredOutside = false; }
else state.OutsideSince ??= seconds;
var quietBoundary = !state.StoredBoundary && (seconds - state.LastMotionSeconds) * 1000 >= HandSettleMs;
var outsideBoundary = !state.StoredOutside && state.OutsideSince is { } outside
&& (seconds - outside) * 1000 >= HandSettleMs;
if (state.Triggered && (quietBoundary || outsideBoundary) && state.Step.AiConfirmation!.EvidenceMode == VisionEvidenceMode.SingleFrame)
{
var boundary = CaptureDecision(state.Step, frame, state.Gate.HandRegion, capture, crop, out _, notify: false);
if (boundary is not null)
{
state.Boundaries.Add(new(frame.FrameId, frame.Timestamp, boundary.Request.Jpeg, frame.SourceSeconds, boundary.Request.StartedTimestamp));
while (state.Boundaries.Count > 6 || state.Boundaries.Sum(f => f.Jpeg.LongLength) > 1024 * 1024) state.Boundaries.RemoveAt(0);
if (quietBoundary) state.StoredBoundary = true;
if (outsideBoundary) state.StoredOutside = true;
}
}
if (state.Window.WantsFrame(frame.FrameId, seconds))
{
var image = CaptureDecision(state.Step, frame, state.Gate.HandRegion, capture, crop, out var error, notify: false);
if (image is not null) state.Window.Add(new(frame.FrameId, frame.Timestamp, image.Request.Jpeg, frame.SourceSeconds, image.Request.StartedTimestamp));
else state.Reason = error ?? "取图失败";
}
state.Window.Advance(seconds);
}
/// <summary>触发后启动本步预算;优先消费已完成响应,再处理到期跳过,并仅在间隔与新证据满足时送检。</summary>
private ConditionResult EvaluateContinuousStep(StepDef step, FrameResult frame, Func<byte[]>? capture,
Func<RegionDef?, byte[]>? crop, out byte[]? evidence)
{
evidence = null;
var options = step.AiConfirmation!;
var gate = _nextCaptureIndex == _index && _followingGate is { } following ? following : new CaptureGate(_evaluator, _handImageRegion);
var state = EnsureContinuousStep(_index, step, gate);
ObserveContinuousStep(_index, state, frame, capture, crop);
if (!state.Triggered) return new() { Message = "等待操作事件,保留触发前画面" };
var prior = PriorCompletedEvidenceTime();
if (!state.BudgetStarted)
{
state.BudgetStarted = true; state.BudgetSeconds = state.LatestSeconds; state.StartedAt = Environment.TickCount64;
Log("info", $"步骤 {step.Id} 开始 {options.CheckWindowMs}ms 限时检查,已保留先前连续操作证据");
}
var expired = state.ElapsedMs >= options.CheckWindowMs;
if (_pendingDecision is { } pending && pending.Task.IsCompleted)
{
_pendingDecision = null; pending.Cancellation.Dispose();
var result = RealtimeDecisionPolicy.AtPublication(pending.Request, pending.Task.GetAwaiter().GetResult());
var source = pending.Request.Frames ?? [];
var completed = source.FirstOrDefault(f => f.FrameId == result.CompletionFrameId);
var confirmation = VisionDecisionEvidence.SupportEnd(pending.Request, result);
var met = result.Completed && result.EffectiveStatus == VisionDecisionStatus.Completed
&& double.IsFinite(result.Confidence) && result.Confidence >= options.MinConfidence && result.Confidence <= 1
&& Volatile.Read(ref state.FinishedAt) - state.StartedAt <= options.CheckWindowMs
&& (options.EvidenceMode == VisionEvidenceMode.SingleFrame || completed is not null && confirmation is not null
&& result.EvidenceFrameIds is { Count: >= 2 } ids && ids.Distinct().Count() >= 2
&& ids.Contains(completed.FrameId) && ids.All(id => source.Any(f => f.FrameId == id)));
state.Reason = result.Reason;
var evaluated = completed is not null && met ? pending.Request with
{ FrameId = completed.FrameId, CapturedAt = completed.CapturedAt, Jpeg = completed.Jpeg, SourceSeconds = completed.SourceSeconds,
ConfirmationEvidence = confirmation } : pending.Request;
DecisionEvaluated?.Invoke(evaluated, result, met);
if (met)
{
evidence = evaluated.Jpeg;
// 工序结果帧与“获得后续支持证据”是不同时间;不能用后者丢掉已经发生的下一步动作。
_acceptedEvidenceTimes[_index] = evaluated.SourceSeconds ?? (evaluated.CapturedAt - DateTime.UnixEpoch).TotalSeconds;
return new() { IsMet = true, Message = $"窗口内第 {state.Attempts} 次检查通过:{result.Reason}" };
}
// 已识别到结果但未达放行门槛时,继续观察新结果,不把下一次机会用于无关旧图。
state.FollowCurrentResult = options.EvidenceMode == VisionEvidenceMode.SingleFrame
&& result.Completed && result.EffectiveStatus == VisionDecisionStatus.Completed;
}
if (expired)
{
if (_pendingDecision is { } unfinished)
{
state.Reason = "检查窗口超时或已取消,未获得模型结果";
DecisionEvaluated?.Invoke(unfinished.Request, new(false, 0, state.Reason, VisionDecisionStatus.Insufficient), false);
}
InvalidateDecision(discardBuffered: false);
return new() { IsSkipped = true, Message = $"检查窗口到期,{state.Attempts} 次送检未确认通过,已跳过并继续后续步骤:{state.Reason}" };
}
if (_pendingDecision is not null) return new() { Message = $"第 {state.Attempts} 次检查中,后续操作持续采集;到期自动继续" };
var discrete = step.Detection?.Method.ToLowerInvariant() is ConditionMethod.HandLeaveRegion or ConditionMethod.HandMove;
if (discrete && state.LatestTriggerSeconds < prior)
{
state.Reason = "已有离开或跨区事件早于前序结果,等待本步新的操作事件";
return new() { Message = state.Reason };
}
var client = VisionDecisionClient;
if (client is null || options.EvidenceMode == VisionEvidenceMode.Sequence && !client.SupportsSequences)
{ state.Reason = "检查服务未配置或不支持所需证据"; return new() { Message = state.Reason + ";窗口到期后记录未通过并继续" }; }
if (state.Window.Error is { } error) { state.Reason = error; return new() { Message = error }; }
var quiet = (state.LatestSeconds - state.LastMotionSeconds) * 1000 >= HandSettleMs;
// 按配置间隔检查当前新图,不能为历史补判扩大等待时间。
var interval = Math.Max(50, options.RetryDelayMs);
var sinceRequest = state.Attempts == 0 ? state.ElapsedMs : Environment.TickCount64 - state.LastSubmittedAt;
var firstWait = Math.Min(interval, Math.Max(50, HandSettleMs));
var freshEvent = discrete && state.LatestTriggerSeconds > state.LastSubmittedSourceSeconds
&& sinceRequest >= Math.Max(50, options.RetryDelayMs);
var timeToCheck = state.Attempts == 0 ? quiet || sinceRequest >= firstWait : sinceRequest >= interval || freshEvent;
if (discrete && options.EvidenceMode == VisionEvidenceMode.SingleFrame)
prior = Math.Max(prior, state.LatestTriggerSeconds);
var frames = state.Window.Frames.Where(f => ObservationEvidenceWindow.Time(f) >= prior).ToArray();
if (!timeToCheck) return new() { Message = $"等待下一次检查时机(已送检 {state.Attempts} 次)" };
if (options.EvidenceMode == VisionEvidenceMode.SingleFrame)
{
var candidates = frames.Concat(state.Boundaries);
if (capture is not null || crop is not null)
{
var current = CaptureDecision(step, frame, state.Gate.HandRegion, capture, crop, out _, notify: false);
if (current is not null) candidates = candidates.Append(new(frame.FrameId, frame.Timestamp, current.Request.Jpeg, frame.SourceSeconds, current.Request.StartedTimestamp));
}
var valid = candidates.Where(f => ObservationEvidenceWindow.Time(f) >= prior).ToArray();
DecisionCandidatesObserved?.Invoke(step.Id, valid);
var selected = valid.Where(f => !state.Inspected.ContainsKey(f.FrameId)).MaxBy(ObservationEvidenceWindow.Time);
frames = selected is null ? [] : [selected];
}
var eof = capture is null && crop is null;
var processReady = frames.Length >= 3 && (eof || state.Window.Ready
&& ObservationEvidenceWindow.Time(frames[^1]) - ObservationEvidenceWindow.Time(frames[0]) >= options.ObservationMinMs / 1000d);
if (frames.Length == 0 || state.Inspected.ContainsKey(frames[^1].FrameId)
|| options.EvidenceMode == VisionEvidenceMode.Sequence && state.Window.Version <= state.SentVersion
|| options.EvidenceMode == VisionEvidenceMode.Sequence && !processReady)
return new() { Message = $"窗口内观察,优先在手部停稳或离开后检查(已送检 {state.Attempts} 次)" };
if (options.EvidenceMode == VisionEvidenceMode.Sequence)
frames = VisualEvidenceSampler.Select(frames, options.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, options.EvidenceMode,
options.EvidenceMode == VisionEvidenceMode.Sequence ? frames : null, last.SourceSeconds, TriggerObservation: state.TriggerObservation, StartedTimestamp: last.StartedTimestamp,
TimeoutMs: RealtimeDecisionPolicy.DeadlineFor(_config.Sop.Settings));
var remaining = Math.Max(1, options.CheckWindowMs - state.ElapsedMs);
var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(remaining));
state.Attempts++; state.SentVersion = state.Window.Version; state.SentFrame = last.FrameId; state.LastSubmittedAt = Environment.TickCount64;
state.LastSubmittedSourceSeconds = state.LatestSeconds;
state.Inspected[last.FrameId] = ObservationEvidenceWindow.Time(last);
state.FinishedAt = long.MaxValue;
async Task<VisionDecisionResult> CheckAsync()
{
var decision = await RunDecisionAsync(client, request, cancellation.Token).ConfigureAwait(false);
Volatile.Write(ref state.FinishedAt, Environment.TickCount64);
return decision;
}
_pendingDecision = new(CheckAsync(), last.Jpeg, cancellation, request);
DecisionCaptured?.Invoke(request); DecisionSubmitted?.Invoke(request);
return new() { Message = $"已发送第 {state.Attempts} 次检查,后续动作持续采集" };
}
}