101 lines
7.3 KiB
C#
101 lines
7.3 KiB
C#
using System.Net.Http;
|
|
using OpenCvSharp;
|
|
using SopHelper.Engine.Sop;
|
|
using SopHelper.Engine.SopAgent;
|
|
|
|
namespace SopHelper.Training;
|
|
|
|
/// <summary>按草稿模式用同服务、同裁剪检查完成/前序参考;不替代手部触发及整轮回放。</summary>
|
|
public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = null)
|
|
{
|
|
private static readonly HttpClient Http = new() { Timeout = Timeout.InfiniteTimeSpan };
|
|
public async Task<IReadOnlyList<SopDraftReferenceCheck>> CheckAsync(SopConfig config, SopVideoDraft draft,
|
|
SopVideoSample video, int blockedId, CancellationToken token)
|
|
{
|
|
var checks = new List<SopDraftReferenceCheck>();
|
|
var client = vision ?? new ConfiguredVisionDecisionClient(Http);
|
|
foreach (var id in new[] { blockedId, blockedId + 1 }.Where(id => id > 0 && id <= draft.Steps.Count))
|
|
{
|
|
var step = config.Sop.Steps[id - 1]; var source = draft.Steps[id - 1];
|
|
var options = step.AiConfirmation ?? new(); var mode = VisionImageMode.Resolve(options);
|
|
var scope = mode == VisionImageMode.FixedRegion ? options.ImageRegion : mode;
|
|
foreach (var kind in new[] { "completion", "previous_state" })
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
var evidence = kind == "completion" ? source.EvidenceFrame : source.IncompleteEvidenceFrame ?? (id > 1 ? draft.Steps[id - 2].EvidenceFrame
|
|
: video.Frames.FirstOrDefault(f => f.Seconds == 0)?.Index ?? -1);
|
|
var seconds = evidence < 0 ? 0 : video.Frames[evidence].Seconds;
|
|
if (options.EvidenceMode == VisionEvidenceMode.Sequence && !client.SupportsSequences)
|
|
{
|
|
checks.Add(new(id, evidence, seconds, scope, null, null, "过程时序服务不可用,不能用单帧参考代判", [], kind, options.EvidenceMode, InfrastructureFailure: true));
|
|
continue;
|
|
}
|
|
if (mode == VisionImageMode.Hand)
|
|
{
|
|
checks.Add(new(id, evidence, seconds, scope, null, null, "跟随手部的范围依赖运行时跟踪,未用静态替代范围猜测参考结果", [], kind));
|
|
continue;
|
|
}
|
|
byte[] jpeg = [];
|
|
try
|
|
{
|
|
var decoded = await Task.Run(() =>
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
using var capture = new VideoCapture(video.Path);
|
|
if (!capture.IsOpened() || capture.Fps <= 0) throw new IOException("无法读取参考视频");
|
|
var index = Math.Clamp((long)Math.Round(seconds * capture.Fps), 0, capture.FrameCount - 1);
|
|
if (!capture.Set(VideoCaptureProperties.PosFrames, index)) throw new IOException("无法定位参考画面");
|
|
using var image = new Mat();
|
|
if (!capture.Read(image) || image.Empty()) throw new IOException("无法解码参考画面");
|
|
var region = mode == VisionImageMode.FixedRegion ? config.Sop.Regions.GetValueOrDefault(options.ImageRegion)
|
|
?? throw new IOException("参考送检区域不存在") : null;
|
|
var frames = new List<VisionEvidenceFrame>();
|
|
if (options.EvidenceMode == VisionEvidenceMode.Sequence)
|
|
{
|
|
var previousSeconds = id > 1 ? video.Frames[draft.Steps[id - 2].EvidenceFrame].Seconds : 0;
|
|
var startSeconds = Math.Max(kind == "completion" ? previousSeconds : 0,
|
|
seconds - options.ObservationMaxMs / 1000d);
|
|
var startIndex = Math.Clamp((long)Math.Round(startSeconds * capture.Fps), 0, index);
|
|
var stride = Math.Max(1, (long)Math.Round(options.ObservationSampleMs * capture.Fps / 1000d));
|
|
for (var f = startIndex; f <= index; f = Math.Min(f + stride, index))
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
if (!capture.Set(VideoCaptureProperties.PosFrames, f) || !capture.Read(image) || image.Empty())
|
|
throw new IOException("无法解码过程参考片段");
|
|
frames.Add(new(f, DateTime.UnixEpoch.AddSeconds(f / capture.Fps), VisionDecisionImage.Encode(image, region), f / capture.Fps));
|
|
if (frames.Count > options.ObservationMaxFrames)
|
|
frames = VisualEvidenceSampler.Select(frames, options.ObservationMaxFrames).ToList();
|
|
if (f == index) break;
|
|
}
|
|
frames = VisualEvidenceSampler.Select(frames, options.ObservationRequestMaxFrames).ToList();
|
|
}
|
|
return (Jpeg: frames.Count > 0 ? frames[^1].Jpeg : VisionDecisionImage.Encode(image, region), FrameId: index, Frames: frames);
|
|
}, token).ConfigureAwait(false);
|
|
jpeg = decoded.Jpeg;
|
|
if (options.EvidenceMode == VisionEvidenceMode.Sequence && decoded.Frames.Count < 3)
|
|
{
|
|
checks.Add(new(id, evidence, seconds, scope, kind == "completion" ? false : null, null,
|
|
"过程参考不足三张真实不同帧,未复制画面或用单帧代判", jpeg, kind, options.EvidenceMode, decoded.Frames));
|
|
continue;
|
|
}
|
|
using var budget = CancellationTokenSource.CreateLinkedTokenSource(token);
|
|
budget.CancelAfter(TimeSpan.FromSeconds(options.TimeoutSeconds));
|
|
var request = new VisionDecisionRequest(config.Sop.Name, id, step.Name, step.Description, step.Description,
|
|
decoded.FrameId, DateTime.Now, jpeg, options.EvidenceMode, decoded.Frames, seconds,
|
|
TimeoutMs: RealtimeDecisionPolicy.DeadlineFor(options));
|
|
var decision = await client.DecideAsync(request, budget.Token).ConfigureAwait(false);
|
|
var accepted = decision.EffectiveStatus == VisionDecisionStatus.Completed && decision.Completed
|
|
&& double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1
|
|
&& (options.EvidenceMode != VisionEvidenceMode.Sequence || VisionDecisionEvidence.SupportEnd(request, decision) is not null);
|
|
bool? known = decision.EffectiveStatus == VisionDecisionStatus.Unsupported ? null : accepted;
|
|
checks.Add(new(id, evidence, seconds, scope, known, decision.Confidence, decision.Reason, jpeg, kind, options.EvidenceMode, decoded.Frames,
|
|
decision.EffectiveStatus == VisionDecisionStatus.Unsupported));
|
|
}
|
|
catch (Exception error) when (error is not OperationCanceledException || !token.IsCancellationRequested)
|
|
{ checks.Add(new(id, evidence, seconds, scope, null, null, "参考判据检查不可用:" + error.Message, jpeg, kind, options.EvidenceMode, InfrastructureFailure: true)); }
|
|
}
|
|
}
|
|
return checks;
|
|
}
|
|
}
|