feat: complete local camera and operations acceptance
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
This commit is contained in:
1 parent
ae3203222b
commit
3208bc93fe
52 files changed
+1193
-106
No files matched your search
@@ -45,6 +45,12 @@ public static class DependencyInjection
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
services.AddScoped<IIdentityPersistenceContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
services.AddOptions<PlateOcrOptions>()
|
||||
.Bind(configuration.GetSection(PlateOcrOptions.SectionName))
|
||||
.Validate(options => options.IsValid(), "Plate OCR options are invalid")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<ILicensePlateOcr, TesseractPlateOcr>();
|
||||
services.AddScoped<ILicensePlateRecognitionService, LicensePlateRecognitionService>();
|
||||
|
||||
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
|
||||
// (storage.provider = Local | S3), factory scoped (lit la config à
|
||||
@@ -52,7 +58,6 @@ public static class DependencyInjection
|
||||
services.AddSingleton<StorageProviderFactory>();
|
||||
services.AddScoped<IStorageProvider>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
services.AddScoped<IStorageObjectDeletion>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
services.AddScoped<IRecordingStorage, RecordingStorageAdapter>();
|
||||
|
||||
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
|
||||
services.AddHealthChecks()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public sealed class LicensePlateRecognitionService(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ILicensePlateOcr ocr) : ILicensePlateRecognitionService
|
||||
{
|
||||
public async Task<ServiceResult<LicensePlateRecognitionResponse>> RecognizeAsync(
|
||||
Guid cameraId, ReadOnlyMemory<byte> image, CancellationToken ct)
|
||||
{
|
||||
var result = await ocr.RecognizeAsync(image, ct).ConfigureAwait(false);
|
||||
if (result is null) return ServiceResult<LicensePlateRecognitionResponse>.Failure("OCR could not read this plate crop", 422);
|
||||
var plateText = new string(result.Text.Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray())
|
||||
.ToUpperInvariant();
|
||||
if (plateText.Length is < 3 or > LicensePlate.MaxPlateTextLength)
|
||||
return ServiceResult<LicensePlateRecognitionResponse>.Failure("OCR output is not a valid plate candidate", 422);
|
||||
|
||||
await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
|
||||
var camera = await db.Cameras.AsNoTracking()
|
||||
.Where(c => c.Id == cameraId && !c.IsDeleted)
|
||||
.Select(c => new { c.Id, c.SiteId })
|
||||
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (camera is null) return ServiceResult<LicensePlateRecognitionResponse>.NotFound("Camera not found");
|
||||
|
||||
var normalized = plateText.Replace("-", string.Empty);
|
||||
var vehicles = await db.Vehicles.AsNoTracking()
|
||||
.Where(v => v.LicensePlate != null && v.LicensePlate.Replace("-", "") == normalized)
|
||||
.OrderBy(v => v.Id)
|
||||
.Take(2)
|
||||
.Select(v => new { v.Id, v.PersonId })
|
||||
.ToListAsync(ct).ConfigureAwait(false);
|
||||
// Suggest only. OCR output is not proof of identity: a human must verify it before linking.
|
||||
var vehicle = vehicles.Count == 1 ? vehicles[0] : null;
|
||||
var observation = new LicensePlate(plateText, confidence: result.Confidence);
|
||||
var ev = new CameraEvent(cameraId, EventType.LicensePlateDetected, result.Confidence);
|
||||
ev.SetMetadata(plateText, JsonSerializer.Serialize(new { source = "local-opt-in-ocr", plateId = observation.Id }));
|
||||
db.LicensePlates.Add(observation);
|
||||
db.CameraEvents.Add(ev);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
return ServiceResult<LicensePlateRecognitionResponse>.Success(
|
||||
new(observation.Id, ev.Id, plateText, result.Confidence, vehicle?.Id, vehicle?.PersonId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public sealed class PlateOcrOptions
|
||||
{
|
||||
public const string SectionName = "PlateOcr";
|
||||
public bool Enabled { get; set; }
|
||||
public string ExecutablePath { get; set; } = "/usr/bin/tesseract";
|
||||
public int MaxImageBytes { get; set; } = 512 * 1024;
|
||||
public int TimeoutSeconds { get; set; } = 10;
|
||||
|
||||
public bool IsValid() => !Enabled ||
|
||||
(!string.IsNullOrWhiteSpace(ExecutablePath) && MaxImageBytes is >= 1024 and <= 512 * 1024 &&
|
||||
TimeoutSeconds is >= 1 and <= 60);
|
||||
}
|
||||
|
||||
/// <summary>Invokes local Tesseract against a temporary, bounded image crop.</summary>
|
||||
public sealed class TesseractPlateOcr(IOptionsMonitor<PlateOcrOptions> options) : Application.Services.ILicensePlateOcr
|
||||
{
|
||||
public async Task<Application.Services.PlateOcrResult?> RecognizeAsync(ReadOnlyMemory<byte> image, CancellationToken ct)
|
||||
{
|
||||
var settings = options.CurrentValue;
|
||||
if (!settings.Enabled || !IsSafeImage(image.Span, settings.MaxImageBytes))
|
||||
return null;
|
||||
|
||||
var tempFile = Path.Combine(Path.GetTempPath(), $"heimdall-plate-{Guid.NewGuid():N}.img");
|
||||
try
|
||||
{
|
||||
var fileOptions = new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.CreateNew,
|
||||
Access = FileAccess.Write,
|
||||
Share = FileShare.None,
|
||||
BufferSize = 4096
|
||||
};
|
||||
if (!OperatingSystem.IsWindows())
|
||||
fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
await using (var output = new FileStream(tempFile, fileOptions))
|
||||
await output.WriteAsync(image, ct).ConfigureAwait(false);
|
||||
var start = new ProcessStartInfo(settings.ExecutablePath)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
start.ArgumentList.Add(tempFile);
|
||||
start.ArgumentList.Add("stdout");
|
||||
start.ArgumentList.Add("--oem"); start.ArgumentList.Add("1");
|
||||
start.ArgumentList.Add("--psm"); start.ArgumentList.Add("7");
|
||||
start.ArgumentList.Add("-l"); start.ArgumentList.Add("eng");
|
||||
start.ArgumentList.Add("tsv");
|
||||
start.ArgumentList.Add("-c"); start.ArgumentList.Add("tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
|
||||
|
||||
using var process = Process.Start(start);
|
||||
if (process is null) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(settings.TimeoutSeconds));
|
||||
try
|
||||
{
|
||||
var stdoutTask = process.StandardOutput.ReadToEndAsync(timeout.Token);
|
||||
var stderrTask = process.StandardError.ReadToEndAsync(timeout.Token);
|
||||
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(timeout.Token)).ConfigureAwait(false);
|
||||
var stdout = await stdoutTask.ConfigureAwait(false);
|
||||
if (process.ExitCode != 0 || stdout.Length > 32_768) return null;
|
||||
return ParseTsv(stdout);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { }
|
||||
if (ct.IsCancellationRequested) throw;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or IOException or
|
||||
UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(tempFile); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
|
||||
public static Application.Services.PlateOcrResult? ParseTsv(string tsv)
|
||||
{
|
||||
var text = new System.Text.StringBuilder();
|
||||
var confidenceSum = 0d;
|
||||
var words = 0;
|
||||
foreach (var line in tsv.Split('\n').Skip(1))
|
||||
{
|
||||
var fields = line.TrimEnd('\r').Split('\t');
|
||||
if (fields.Length < 12 || !double.TryParse(fields[10], NumberStyles.Float,
|
||||
CultureInfo.InvariantCulture, out var confidence) || !double.IsFinite(confidence) || confidence < 0 || string.IsNullOrWhiteSpace(fields[11]))
|
||||
continue;
|
||||
var token = new string(fields[11].Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray());
|
||||
if (token.Length == 0) continue;
|
||||
if (text.Length > 0) text.Append(' ');
|
||||
text.Append(token.ToUpperInvariant());
|
||||
confidenceSum += Math.Clamp(confidence / 100d, 0, 1);
|
||||
words++;
|
||||
}
|
||||
return words == 0 ? null : new Application.Services.PlateOcrResult(text.ToString(), confidenceSum / words);
|
||||
}
|
||||
|
||||
public static bool IsSafeImage(ReadOnlySpan<byte> image, int maxBytes = 512 * 1024) =>
|
||||
image.Length is >= 16 && image.Length <= maxBytes &&
|
||||
PlateImageHeader.TryGetDimensions(image, out var width, out var height) &&
|
||||
width is >= 32 and <= 4096 && height is >= 16 and <= 4096 && (long)width * height <= 4_000_000;
|
||||
}
|
||||
|
||||
internal static class PlateImageHeader
|
||||
{
|
||||
public static bool TryGetDimensions(ReadOnlySpan<byte> data, out int width, out int height)
|
||||
{
|
||||
width = height = 0;
|
||||
if (data.Length >= 24 && data[..8].SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }))
|
||||
{
|
||||
width = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(16, 4));
|
||||
height = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(20, 4));
|
||||
return width > 0 && height > 0;
|
||||
}
|
||||
|
||||
if (data.Length < 4 || data[0] != 0xff || data[1] != 0xd8) return false;
|
||||
var offset = 2;
|
||||
while (offset + 4 <= data.Length)
|
||||
{
|
||||
if (data[offset++] != 0xff) return false;
|
||||
while (offset < data.Length && data[offset] == 0xff) offset++;
|
||||
if (offset >= data.Length) return false;
|
||||
var marker = data[offset++];
|
||||
if (marker is 0xd8 or 0xd9 or 0x01 || marker is >= 0xd0 and <= 0xd7) continue;
|
||||
var segmentLength = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2));
|
||||
if (segmentLength < 2 || offset + segmentLength > data.Length) return false;
|
||||
if (marker is >= 0xc0 and <= 0xc3 or >= 0xc5 and <= 0xc7 or >= 0xc9 and <= 0xcb or >= 0xcd and <= 0xcf)
|
||||
{
|
||||
if (segmentLength < 7) return false;
|
||||
height = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 3, 2));
|
||||
width = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 5, 2));
|
||||
return width > 0 && height > 0;
|
||||
}
|
||||
offset += segmentLength;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Data;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Infrastructure.Storage;
|
||||
|
||||
/// <summary>Uses one PostgreSQL transaction advisory lock to make the global quota check atomic.</summary>
|
||||
public sealed class RecordingQuotaGuard(
|
||||
AppDbContext db,
|
||||
IOptions<RecordingStorageQuotaOptions> options) : IRecordingQuotaGuard
|
||||
{
|
||||
private const long QuotaLockKey = 0x4845494D44525155;
|
||||
|
||||
public long MaxStorageBytes => options.Value.MaxBytes;
|
||||
|
||||
public async Task<IRecordingQuotaLease> AcquireAsync(CancellationToken ct = default)
|
||||
{
|
||||
var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct)
|
||||
.ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// EF Core exception: PostgreSQL transaction advisory locks have no portable LINQ equivalent.
|
||||
// The lock serializes only the short metadata/quota check, after object upload has completed.
|
||||
await db.Database.ExecuteSqlInterpolatedAsync(
|
||||
$"SELECT pg_advisory_xact_lock({QuotaLockKey})", ct).ConfigureAwait(false);
|
||||
return new TransactionLease(transaction);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TransactionLease(IDbContextTransaction transaction) : IRecordingQuotaLease
|
||||
{
|
||||
public Task CommitAsync(CancellationToken ct = default) => transaction.CommitAsync(ct);
|
||||
public ValueTask DisposeAsync() => transaction.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Heimdall.Infrastructure.Storage;
|
||||
|
||||
/// <summary>Central-wide cap for bytes stored as camera recordings.</summary>
|
||||
public sealed class RecordingStorageQuotaOptions
|
||||
{
|
||||
public const string SectionName = "Recordings:StorageQuota";
|
||||
|
||||
/// <summary>Maximum persisted recording bytes; defaults to 1 TiB.</summary>
|
||||
[Range(1, long.MaxValue)]
|
||||
public long MaxBytes { get; set; } = 1L << 40;
|
||||
}
|
||||
Reference in new issue
Block a user