feat(agent): align FrameAnalyzerService with spec §16 — IntraOpNumThreads, MinConfidence, model path (#169)
This commit is contained in:
1 parent
e0290c8a1b
commit
4b3068e12f
3 files changed
+74
-15
No files matched your search
@@ -26,7 +26,7 @@ public sealed record FrameAnalysisResult(
|
||||
/// Runs inference in a background thread pool, supports concurrent
|
||||
/// frame processing with a bounded queue.
|
||||
///
|
||||
/// Model file expected at: models/yolov8m.onnx (relative to app root)
|
||||
/// Model file expected at: models/yolov8n.onnx (relative to app root)
|
||||
/// or configured via MODEL_PATH environment variable.
|
||||
///
|
||||
/// If no model file is found, runs in "passthrough" mode — returns
|
||||
@@ -72,7 +72,8 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
|
||||
private const int MaxQueueSize = 16;
|
||||
private const int InputSize = 640; // YOLOv8 input size
|
||||
private const float DefaultConfidenceThreshold = 0.25f;
|
||||
/// <summary>Default minimum confidence per spec §16 — CameraDetectionProfile.MinConfidence.</summary>
|
||||
internal const float DefaultMinConfidence = 0.4f;
|
||||
private const float NmsIouThreshold = 0.45f;
|
||||
private const long SlowInferenceThresholdMs = 500;
|
||||
|
||||
@@ -102,7 +103,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
_logger = logger;
|
||||
_circuitBreaker = circuitBreaker;
|
||||
_degradationManager = degradationManager;
|
||||
_modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8m.onnx";
|
||||
_modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx";
|
||||
_modelLoaded = File.Exists(_modelPath);
|
||||
|
||||
if (_modelLoaded)
|
||||
@@ -112,7 +113,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
|
||||
{
|
||||
InterOpNumThreads = 1,
|
||||
IntraOpNumThreads = Environment.ProcessorCount,
|
||||
IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent
|
||||
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
|
||||
};
|
||||
_session = new InferenceSession(_modelPath, sessionOptions);
|
||||
@@ -158,7 +159,16 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
/// Returns empty detections if model not loaded (passthrough mode).
|
||||
/// Respects circuit breaker and degradation level.
|
||||
/// </summary>
|
||||
public async Task<FrameAnalysisResult?> AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default)
|
||||
/// <param name="jpegData">Raw JPEG frame bytes.</param>
|
||||
/// <param name="minConfidence">
|
||||
/// Minimum confidence threshold for detections. Defaults to 0.4 (spec §16).
|
||||
/// Override with <see cref="CameraDetectionProfile.MinConfidence"/> per camera.
|
||||
/// </param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
public async Task<FrameAnalysisResult?> AnalyzeFrameAsync(
|
||||
byte[] jpegData,
|
||||
float minConfidence = DefaultMinConfidence,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
Interlocked.Increment(ref _analyzedFrameCount);
|
||||
|
||||
@@ -180,7 +190,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
return null;
|
||||
|
||||
var tcs = new TaskCompletionSource<FrameAnalysisResult?>();
|
||||
var job = new FrameJob(jpegData, tcs);
|
||||
var job = new FrameJob(jpegData, tcs, minConfidence);
|
||||
|
||||
// If queue is full (DropWrite rejected our write), complete TCS with fallback
|
||||
if (!_frameQueue.Writer.TryWrite(job))
|
||||
@@ -197,7 +207,9 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
/// don't need the result immediately). Returns null in passthrough.
|
||||
/// Respects circuit breaker and degradation level.
|
||||
/// </summary>
|
||||
public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData)
|
||||
public FrameAnalysisResult? AnalyzeFrame(
|
||||
byte[] jpegData,
|
||||
float minConfidence = DefaultMinConfidence)
|
||||
{
|
||||
Interlocked.Increment(ref _analyzedFrameCount);
|
||||
if (!_modelLoaded) return null;
|
||||
@@ -217,7 +229,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var detections = RunInference(jpegData);
|
||||
var detections = RunInference(jpegData, minConfidence);
|
||||
sw.Stop();
|
||||
|
||||
ReportInferenceResult(sw.ElapsedMilliseconds);
|
||||
@@ -235,7 +247,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
try
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var detections = RunInference(job.ImageData);
|
||||
var detections = RunInference(job.ImageData, job.MinConfidence);
|
||||
sw.Stop();
|
||||
|
||||
ReportInferenceResult(sw.ElapsedMilliseconds);
|
||||
@@ -283,7 +295,9 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
/// Run YOLOv8 ONNX inference on a JPEG frame.
|
||||
/// Pipeline: JPEG decode → resize 640×640 → normalize → ONNX inference → NMS.
|
||||
/// </summary>
|
||||
internal DetectionResult[] RunInference(byte[] jpegData)
|
||||
/// <param name="jpegData">Raw JPEG frame bytes.</param>
|
||||
/// <param name="minConfidence">Minimum confidence threshold (default 0.4 per spec §16).</param>
|
||||
internal DetectionResult[] RunInference(byte[] jpegData, float minConfidence = DefaultMinConfidence)
|
||||
{
|
||||
if (_session is null)
|
||||
return [];
|
||||
@@ -304,7 +318,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
using var results = _session.Run(inputs);
|
||||
var output = results[0].AsTensor<float>().ToArray();
|
||||
|
||||
return ParseYoloOutput(output, (int)image.Width, (int)image.Height);
|
||||
return ParseYoloOutput(output, (int)image.Width, (int)image.Height, minConfidence);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -337,7 +351,12 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
/// Remaining C values are class confidence scores.
|
||||
/// Applies confidence thresholding and Non-Maximum Suppression.
|
||||
/// </summary>
|
||||
internal DetectionResult[] ParseYoloOutput(float[] output, int imageWidth, int imageHeight)
|
||||
/// <param name="output">Flattened output tensor from ONNX Runtime.</param>
|
||||
/// <param name="imageWidth">Original image width (for scaling back).</param>
|
||||
/// <param name="imageHeight">Original image height (for scaling back).</param>
|
||||
/// <param name="minConfidence">Minimum class confidence to keep a detection.</param>
|
||||
internal DetectionResult[] ParseYoloOutput(
|
||||
float[] output, int imageWidth, int imageHeight, float minConfidence = DefaultMinConfidence)
|
||||
{
|
||||
// YOLOv8 output shape: [1, 4+numClasses, numAnchors] → flatten to [4+numClasses, numAnchors]
|
||||
var numFeatures = 4 + _numClasses;
|
||||
@@ -364,7 +383,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (maxScore < DefaultConfidenceThreshold)
|
||||
if (maxScore < minConfidence)
|
||||
continue;
|
||||
|
||||
// Decode bounding box: (cx, cy, w, h) → scale to original image
|
||||
@@ -473,5 +492,5 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
}, TaskContinuationOptions.OnlyOnFaulted);
|
||||
}
|
||||
|
||||
private sealed record FrameJob(byte[] ImageData, TaskCompletionSource<FrameAnalysisResult?> Tcs);
|
||||
private sealed record FrameJob(byte[] ImageData, TaskCompletionSource<FrameAnalysisResult?> Tcs, float MinConfidence);
|
||||
}
|
||||
Reference in new issue
Block a user