From 4b3068e12ff8d7baeb3d588ce7752d97855fe6db Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 27 Aug 2026 00:36:03 +0200 Subject: [PATCH] =?UTF-8?q?feat(agent):=20align=20FrameAnalyzerService=20w?= =?UTF-8?q?ith=20spec=20=C2=A716=20=E2=80=94=20IntraOpNumThreads,=20MinCon?= =?UTF-8?q?fidence,=20model=20path=20(#169)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker/Dockerfile.agent | 8 +++- .../Services/FrameAnalyzerService.cs | 47 +++++++++++++------ .../FrameAnalyzerServiceTests.cs | 34 ++++++++++++++ 3 files changed, 74 insertions(+), 15 deletions(-) diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index 70c1eec..c12da8d 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -21,13 +21,19 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release -o /app - FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime WORKDIR /app -RUN apk add --no-cache icu-libs libstdc++ ffmpeg krb5 +RUN apk add --no-cache icu-libs libstdc++ ffmpeg krb5 wget ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /app . +# Download YOLOv8n ONNX model (spec §16: yolov8n, ~6MB) +ARG YOLO_MODEL_URL=https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8n.onnx +RUN mkdir -p models && \ + wget -q -O models/yolov8n.onnx "$YOLO_MODEL_URL" && \ + echo "YOLOv8n model downloaded: $(du -sh models/yolov8n.onnx | cut -f1)" + HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:8080/healthz || exit 1 diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index ef20176..65e9772 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -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; + /// Default minimum confidence per spec §16 — CameraDetectionProfile.MinConfidence. + 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. /// - public async Task AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default) + /// Raw JPEG frame bytes. + /// + /// Minimum confidence threshold for detections. Defaults to 0.4 (spec §16). + /// Override with per camera. + /// + /// Cancellation token. + public async Task 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(); - 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. /// - 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. /// - internal DetectionResult[] RunInference(byte[] jpegData) + /// Raw JPEG frame bytes. + /// Minimum confidence threshold (default 0.4 per spec §16). + 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().ToArray(); - return ParseYoloOutput(output, (int)image.Width, (int)image.Height); + return ParseYoloOutput(output, (int)image.Width, (int)image.Height, minConfidence); } /// @@ -337,7 +351,12 @@ public sealed class FrameAnalyzerService : IDisposable /// Remaining C values are class confidence scores. /// Applies confidence thresholding and Non-Maximum Suppression. /// - internal DetectionResult[] ParseYoloOutput(float[] output, int imageWidth, int imageHeight) + /// Flattened output tensor from ONNX Runtime. + /// Original image width (for scaling back). + /// Original image height (for scaling back). + /// Minimum class confidence to keep a detection. + 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 Tcs); + private sealed record FrameJob(byte[] ImageData, TaskCompletionSource Tcs, float MinConfidence); } diff --git a/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs index 4c65c4f..7389526 100644 --- a/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs @@ -190,4 +190,38 @@ public class FrameAnalyzerServiceTests result.Length.ShouldBe(1); result[0].Label.ShouldBe("class_999"); } + + // ── Spec compliance tests ───────────────────────────────────── + + [Fact] + public void DefaultMinConfidence_MatchesSpec() + { + // Spec §16: CameraDetectionProfile.MinConfidence defaults to 0.4 + FrameAnalyzerService.DefaultMinConfidence.ShouldBe(0.4f); + } + + [Fact] + public async Task AnalyzeFrameAsync_WithCustomMinConfidence_Passthrough_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = await service.AnalyzeFrameAsync([1, 2, 3], minConfidence: 0.6f); + result.ShouldBeNull(); + } + + [Fact] + public void AnalyzeFrame_WithCustomMinConfidence_Passthrough_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = service.AnalyzeFrame([1, 2, 3], minConfidence: 0.6f); + result.ShouldBeNull(); + } + + [Fact] + public async Task AnalyzeFrameAsync_DefaultMinConfidence_Passthrough_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + // Default 0.4 threshold should work identically in passthrough + var result = await service.AnalyzeFrameAsync([1, 2, 3]); + result.ShouldBeNull(); + } }