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
@@ -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
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<ILogger<FrameAnalyzerService>>());
|
||||
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<ILogger<FrameAnalyzerService>>());
|
||||
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<ILogger<FrameAnalyzerService>>());
|
||||
// Default 0.4 threshold should work identically in passthrough
|
||||
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user