## What Replace the stub `FrameAnalyzerService.RunInference` (returning `[]`) with a real ONNX Runtime inference pipeline for YOLOv8 object detection. ## Why The entire detection chain was non-functional — `FrameAnalyzerService` returned empty results, `Microsoft.ML.OnnxRuntime` was not referenced, and no object detection was produced. This is the core AI feature of the Heimdall platform (issue #2, etape-3). ## How - **Packages**: Added `Microsoft.ML.OnnxRuntime` 1.22.0 and `SixLabors.ImageSharp` 4.1.0 to `Heimdall.Agent.csproj` - **ONNX session**: `InferenceSession` loaded in constructor with graceful fallback to passthrough mode when model is absent - **Preprocessing**: JPEG → ImageSharp `Image<Rgb24>` → resize 640×640 → NCHW tensor normalized [0,1] - **Inference**: ONNX Runtime `Session.Run()` with the preprocessed tensor - **Post-processing**: YOLOv8 output parsing (`[1, 4+C, 8400]` tensor → bounding boxes + class scores) with class-aware Non-Maximum Suppression (IoU threshold 0.45, confidence threshold 0.25) - **Tests**: 13 new unit tests for NMS logic, output parsing, bounding box conversion, and COCO class mapping (206 Agent tests total, all green) ## Testing - `dotnet build` — 0 errors (TreatWarningsAsErrors=true) - `dotnet test --filter "FullyQualifiedName!~E2E"` — 1282 passed, 0 failed - E2E failures are pre-existing (Playwright/Chromium not installed on this runner) ## Notes - Model path configurable via `MODEL_PATH` env var (default: `models/yolov8m.onnx`) - Passthrough mode preserved when model file is absent — no crash - Thread-safe: `InferenceSession.Run()` is thread-safe; session created once in constructor Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/148
387 lines
14 KiB
C#
387 lines
14 KiB
C#
using System.Diagnostics;
|
||
using System.Threading.Channels;
|
||
using Microsoft.Extensions.Logging;
|
||
using Microsoft.ML.OnnxRuntime;
|
||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||
using SixLabors.ImageSharp;
|
||
using SixLabors.ImageSharp.PixelFormats;
|
||
using SixLabors.ImageSharp.Processing;
|
||
|
||
namespace Heimdall.Agent.Services;
|
||
|
||
/// <summary>Single detection result from a frame.</summary>
|
||
public sealed record DetectionResult(
|
||
string Label,
|
||
float Confidence,
|
||
float X, float Y, float Width, float Height,
|
||
int? ClassIndex = null);
|
||
|
||
/// <summary>Result of analyzing a single frame.</summary>
|
||
public sealed record FrameAnalysisResult(
|
||
string ImageBase64,
|
||
IReadOnlyList<DetectionResult> Detections,
|
||
long ProcessingMs);
|
||
|
||
/// <summary>
|
||
/// Analyzes video frames using YOLO ONNX models for object detection.
|
||
/// 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)
|
||
/// or configured via MODEL_PATH environment variable.
|
||
///
|
||
/// If no model file is found, runs in "passthrough" mode — returns
|
||
/// empty detections without crashing.
|
||
/// </summary>
|
||
public sealed class FrameAnalyzerService : IDisposable
|
||
{
|
||
private readonly ILogger<FrameAnalyzerService> _logger;
|
||
private readonly string _modelPath;
|
||
private readonly bool _modelLoaded;
|
||
private readonly InferenceSession? _session;
|
||
private readonly string _inputName = "";
|
||
private readonly int _numClasses;
|
||
|
||
// Bounded queue of pending frames to analyze
|
||
private readonly Channel<FrameJob> _frameQueue;
|
||
private readonly CancellationTokenSource _cts = new();
|
||
private readonly Task _processingLoop;
|
||
|
||
// YOLO class names (COCO dataset)
|
||
private static readonly string[] CocoClasses =
|
||
[
|
||
"person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat",
|
||
"traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
|
||
"dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack",
|
||
"umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball",
|
||
"kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket",
|
||
"bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
|
||
"sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake",
|
||
"chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop",
|
||
"mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink",
|
||
"refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier",
|
||
"toothbrush"
|
||
];
|
||
|
||
private const int MaxQueueSize = 16;
|
||
private const int InputSize = 640; // YOLOv8 input size
|
||
private const float ConfidenceThreshold = 0.25f;
|
||
private const float NmsIouThreshold = 0.45f;
|
||
|
||
private long _analyzedFrameCount;
|
||
|
||
/// <summary>Number of frames actually handed to the analyzer (real calls, including passthrough).</summary>
|
||
public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount);
|
||
|
||
public FrameAnalyzerService(ILogger<FrameAnalyzerService> logger)
|
||
{
|
||
_logger = logger;
|
||
_modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8m.onnx";
|
||
_modelLoaded = File.Exists(_modelPath);
|
||
|
||
if (_modelLoaded)
|
||
{
|
||
try
|
||
{
|
||
var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
|
||
{
|
||
InterOpNumThreads = 1,
|
||
IntraOpNumThreads = Environment.ProcessorCount,
|
||
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
|
||
};
|
||
_session = new InferenceSession(_modelPath, sessionOptions);
|
||
_inputName = _session.InputMetadata.Keys.ToArray()[0];
|
||
|
||
// Determine number of classes from output shape [1, 4+C, 8400]
|
||
var outputMeta = _session.OutputMetadata.Values.ToArray()[0];
|
||
_numClasses = outputMeta.Dimensions.Length >= 2 ? (int)outputMeta.Dimensions[1] - 4 : 80;
|
||
|
||
_logger.LogInformation(
|
||
"FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})",
|
||
_modelPath, _inputName, _numClasses);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Failed to load ONNX model from {ModelPath} — falling back to passthrough", _modelPath);
|
||
_session?.Dispose();
|
||
_session = null;
|
||
_modelLoaded = false;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
_logger.LogWarning("FrameAnalyzer in passthrough mode — model not found at {ModelPath}", _modelPath);
|
||
}
|
||
|
||
_frameQueue = Channel.CreateBounded<FrameJob>(new BoundedChannelOptions(MaxQueueSize)
|
||
{
|
||
// DropWrite rejects new writes when full with TryWrite=false,
|
||
// allowing the caller to gracefully complete the TCS with null.
|
||
// DropOldest would orphan the oldest job's TaskCompletionSource.
|
||
FullMode = BoundedChannelFullMode.DropWrite,
|
||
SingleReader = true,
|
||
SingleWriter = false
|
||
});
|
||
|
||
_processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Submit a JPEG frame for analysis. Returns a task that completes when
|
||
/// analysis is done. If the queue is full, drops the oldest frame.
|
||
/// Returns empty detections if model not loaded (passthrough mode).
|
||
/// </summary>
|
||
public async Task<FrameAnalysisResult?> AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default)
|
||
{
|
||
Interlocked.Increment(ref _analyzedFrameCount);
|
||
|
||
if (!_modelLoaded)
|
||
return null;
|
||
|
||
var tcs = new TaskCompletionSource<FrameAnalysisResult?>();
|
||
var job = new FrameJob(jpegData, tcs);
|
||
|
||
// If queue is full (DropWrite rejected our write), complete TCS with fallback
|
||
if (!_frameQueue.Writer.TryWrite(job))
|
||
{
|
||
tcs.TrySetResult(null);
|
||
return null;
|
||
}
|
||
|
||
return await tcs.Task.WaitAsync(ct);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Synchronous frame analysis (for fire-and-forget pipelines that
|
||
/// don't need the result immediately). Returns null in passthrough.
|
||
/// </summary>
|
||
public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData)
|
||
{
|
||
Interlocked.Increment(ref _analyzedFrameCount);
|
||
if (!_modelLoaded) return null;
|
||
|
||
var sw = Stopwatch.StartNew();
|
||
var detections = RunInference(jpegData);
|
||
sw.Stop();
|
||
|
||
return new FrameAnalysisResult(
|
||
Convert.ToBase64String(jpegData),
|
||
detections,
|
||
sw.ElapsedMilliseconds);
|
||
}
|
||
|
||
private async Task ProcessingLoopAsync(CancellationToken ct)
|
||
{
|
||
await foreach (var job in _frameQueue.Reader.ReadAllAsync(ct))
|
||
{
|
||
try
|
||
{
|
||
var sw = Stopwatch.StartNew();
|
||
var detections = RunInference(job.ImageData);
|
||
sw.Stop();
|
||
|
||
var result = new FrameAnalysisResult(
|
||
Convert.ToBase64String(job.ImageData),
|
||
detections,
|
||
sw.ElapsedMilliseconds);
|
||
|
||
job.Tcs.TrySetResult(result);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(ex, "Frame analysis failed");
|
||
job.Tcs.TrySetResult(null);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Run YOLOv8 ONNX inference on a JPEG frame.
|
||
/// Pipeline: JPEG decode → resize 640×640 → normalize → ONNX inference → NMS.
|
||
/// </summary>
|
||
internal DetectionResult[] RunInference(byte[] jpegData)
|
||
{
|
||
if (_session is null)
|
||
return [];
|
||
|
||
using var image = Image.Load<Rgb24>(jpegData);
|
||
|
||
// Resize to model input size (640×640)
|
||
image.Mutate(x => x.Resize(InputSize, InputSize));
|
||
|
||
var inputTensor = PreprocessImage(image);
|
||
|
||
var inputs = new List<NamedOnnxValue>
|
||
{
|
||
NamedOnnxValue.CreateFromTensor(_inputName, inputTensor)
|
||
};
|
||
|
||
using var results = _session.Run(inputs);
|
||
var output = results[0].AsTensor<float>().ToArray();
|
||
|
||
return ParseYoloOutput(output, image.Width, image.Height);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Convert ImageSharp image to a normalized NCHW tensor [1, 3, 640, 640].
|
||
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
|
||
/// </summary>
|
||
private static DenseTensor<float> PreprocessImage(Image<Rgb24> image)
|
||
{
|
||
var tensor = new DenseTensor<float>([1, 3, InputSize, InputSize]);
|
||
var width = image.Width;
|
||
|
||
image.ProcessPixelRows(accessor =>
|
||
{
|
||
for (var y = 0; y < accessor.Height; y++)
|
||
{
|
||
var pixelRow = accessor.GetRowSpan(y);
|
||
for (var x = 0; x < pixelRow.Length; x++)
|
||
{
|
||
var pixel = pixelRow[x];
|
||
tensor[0, 0, y, x] = pixel.R / 255f;
|
||
tensor[0, 1, y, x] = pixel.G / 255f;
|
||
tensor[0, 2, y, x] = pixel.B / 255f;
|
||
}
|
||
}
|
||
});
|
||
|
||
return tensor;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Parse YOLOv8 raw output tensor [1, 4+C, 8400] into DetectionResult list.
|
||
/// First 4 values per column are (cx, cy, w, h) in pixel space (scaled to input size).
|
||
/// Remaining C values are class confidence scores.
|
||
/// Applies confidence thresholding and Non-Maximum Suppression.
|
||
/// </summary>
|
||
internal DetectionResult[] ParseYoloOutput(float[] output, int imageWidth, int imageHeight)
|
||
{
|
||
// YOLOv8 output shape: [1, 4+numClasses, numAnchors] → flatten to [4+numClasses, numAnchors]
|
||
var numFeatures = 4 + _numClasses;
|
||
var numAnchors = output.Length / numFeatures;
|
||
|
||
// Scale factors from model input size to original image size
|
||
var scaleX = (float)imageWidth / InputSize;
|
||
var scaleY = (float)imageHeight / InputSize;
|
||
|
||
var candidates = new List<RawDetection>();
|
||
|
||
for (var i = 0; i < numAnchors; i++)
|
||
{
|
||
// Find best class score
|
||
var maxScore = 0f;
|
||
var maxClassIdx = 0;
|
||
for (var c = 0; c < _numClasses; c++)
|
||
{
|
||
var score = output[(4 + c) * numAnchors + i];
|
||
if (score > maxScore)
|
||
{
|
||
maxScore = score;
|
||
maxClassIdx = c;
|
||
}
|
||
}
|
||
|
||
if (maxScore < ConfidenceThreshold)
|
||
continue;
|
||
|
||
// Decode bounding box: (cx, cy, w, h) → scale to original image
|
||
var cx = output[0 * numAnchors + i] * scaleX;
|
||
var cy = output[1 * numAnchors + i] * scaleY;
|
||
var w = output[2 * numAnchors + i] * scaleX;
|
||
var h = output[3 * numAnchors + i] * scaleY;
|
||
|
||
// Convert to (x1, y1, x2, y2) for NMS
|
||
var x1 = cx - w / 2;
|
||
var y1 = cy - h / 2;
|
||
var x2 = cx + w / 2;
|
||
var y2 = cy + h / 2;
|
||
|
||
candidates.Add(new RawDetection(x1, y1, x2, y2, maxScore, maxClassIdx));
|
||
}
|
||
|
||
return ApplyNms(candidates);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Non-Maximum Suppression: suppress overlapping boxes of the same class.
|
||
/// Returns the surviving detections as DetectionResult records.
|
||
/// </summary>
|
||
internal static DetectionResult[] ApplyNms(List<RawDetection> candidates)
|
||
{
|
||
// Sort by confidence descending
|
||
candidates.Sort((a, b) => b.Score.CompareTo(a.Score));
|
||
|
||
var results = new List<DetectionResult>();
|
||
var suppressed = new bool[candidates.Count];
|
||
|
||
for (var i = 0; i < candidates.Count; i++)
|
||
{
|
||
if (suppressed[i]) continue;
|
||
|
||
var best = candidates[i];
|
||
results.Add(new DetectionResult(
|
||
Label: best.ClassIdx < CocoClasses.Length ? CocoClasses[best.ClassIdx] : $"class_{best.ClassIdx}",
|
||
Confidence: best.Score,
|
||
X: best.X1,
|
||
Y: best.Y1,
|
||
Width: best.X2 - best.X1,
|
||
Height: best.Y2 - best.Y1,
|
||
ClassIndex: best.ClassIdx));
|
||
|
||
// Suppress overlapping boxes of the same class
|
||
for (var j = i + 1; j < candidates.Count; j++)
|
||
{
|
||
if (suppressed[j]) continue;
|
||
if (candidates[j].ClassIdx != best.ClassIdx) continue;
|
||
|
||
var iou = ComputeIoU(best, candidates[j]);
|
||
if (iou >= NmsIouThreshold)
|
||
suppressed[j] = true;
|
||
}
|
||
}
|
||
|
||
return results.ToArray();
|
||
}
|
||
|
||
private static float ComputeIoU(RawDetection a, RawDetection b)
|
||
{
|
||
var interX1 = Math.Max(a.X1, b.X1);
|
||
var interY1 = Math.Max(a.Y1, b.Y1);
|
||
var interX2 = Math.Min(a.X2, b.X2);
|
||
var interY2 = Math.Min(a.Y2, b.Y2);
|
||
|
||
var interArea = Math.Max(0, interX2 - interX1) * Math.Max(0, interY2 - interY1);
|
||
var areaA = (a.X2 - a.X1) * (a.Y2 - a.Y1);
|
||
var areaB = (b.X2 - b.X1) * (b.Y2 - b.Y1);
|
||
var unionArea = areaA + areaB - interArea;
|
||
|
||
return unionArea > 0 ? interArea / unionArea : 0;
|
||
}
|
||
|
||
internal readonly record struct RawDetection(
|
||
float X1, float Y1, float X2, float Y2,
|
||
float Score, int ClassIdx);
|
||
|
||
private bool _disposed;
|
||
|
||
public void Dispose()
|
||
{
|
||
if (_disposed) return;
|
||
_disposed = true;
|
||
_cts.Cancel();
|
||
_cts.Dispose();
|
||
_frameQueue.Writer.TryComplete();
|
||
_session?.Dispose();
|
||
|
||
// Log unobserved exceptions from the processing loop
|
||
_processingLoop.ContinueWith(t =>
|
||
{
|
||
if (t.IsFaulted)
|
||
_logger.LogCritical(t.Exception, "FrameAnalyzer processing loop crashed");
|
||
}, TaskContinuationOptions.OnlyOnFaulted);
|
||
}
|
||
|
||
private sealed record FrameJob(byte[] ImageData, TaskCompletionSource<FrameAnalysisResult?> Tcs);
|
||
}
|