diff --git a/docs/MASTER_SPECIFICATION.md b/docs/MASTER_SPECIFICATION.md index 1bf202a..3c4271c 100644 --- a/docs/MASTER_SPECIFICATION.md +++ b/docs/MASTER_SPECIFICATION.md @@ -1,11 +1,11 @@ # Heimdall — Master Specification Technique > **Version :** 2.0 | **Date :** 2026-07-16 -> **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / CodeProject.AI / SIPSorcery / WebRTC +> **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC > **Status :** SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts > > **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`, -> `auth-roles.md`, `mobile-app.md`, `hangfire-usage.md`, `ui-pages.md`, `codeproject-ai.md` +> `auth-roles.md`, `mobile-app.md`, `hangfire-usage.md`, `ui-pages.md` > > **Correctifs intégrés :** 5 agents (council, security, db, ai, perf) ont analysé la spec originale > et identifié **36 issues critiques** résolues dans ce document. @@ -88,11 +88,11 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu | Principe | Application | |---|---| -| **Privacy First** | CodeProject.AI + Ollama en local, 0 envoi de données au cloud | +| **Privacy First** | IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud | | **Multi-site** | 1 serveur Central + N Agents distants (sites physiques séparés) | | **Clean Architecture / CQRS** | Domain → Application → Infrastructure → Api/Web | | **Temps réel** | SignalR (5 hubs), WebRTC P2P < 500ms (LAN) | -| **IA locale** | YOLOv8 nano (Agent CPU) + CodeProject.AI GPU (Central) | +| **IA locale** | YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker | ### 1.3 Architecture Logique @@ -101,7 +101,7 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu │ HEIMDALL CENTRAL (1 container) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │ -│ │ Api REST + │ │ Web Blazor │ │ Workers │ │ CodeProject│ │ +│ │ Api REST + │ │ Web Blazor │ │ Workers │ │ Broker IA │ │ │ │ SignalR Hubs │ │ MudBlazor │ │ Hangfire │ │ .AI Server │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ Ollama │ │ │ │ │ │ └────────────┘ │ @@ -138,7 +138,7 @@ services: heimdall-agent: # SIPSorcery + FFmpeg + YOLOv8 + Hangfire InMemory postgresql: # Base de données (app + hangfire) alarik: # Stockage S3 (enregistrements) - codeproject-ai: # IA lourde GPU (détection, visages, LPR) + # L'IA lourde (détection, visages, LPR) tourne sur les agents GPU (ONNX Runtime) — pas de service central ollama: # LLM local (résumés quotidiens) coturn: # TURN relay (OBLIGATOIRE, pas optionnel) redis: # Cache + SignalR backplane (optionnel, scaling) @@ -297,7 +297,7 @@ CREATE INDEX idx_license_plate ON license_plates USING GIN **Sans dédoublonnage** : une personne immobile 10 minutes génère : - 3000 snapshots (200ms × 600s) - 3000 inférences YOLOv8 nano -- 3000 appels CodeProject.AI +- 3000 analyses IA (ONNX local ou via broker) - 3000 événements en base - 3000 notifications (email + gotify + in-app) @@ -320,7 +320,7 @@ CREATE INDEX idx_license_plate ON license_plates USING GIN │ ├── IoU > 0.6 mais > DedupCooldownSec écoulé ? → NOUVEL événement │ │ └── IoU ≤ 0.6 → NOUVEL objet → envoyer au Central │ │ │ -│ NIVEAU 2 — Temporal Cooldown (Central, post-CPAI) │ +│ NIVEAU 2 — Temporal Cooldown (Central, post-analyse) │ │ ├── Cache IMemoryCache par (cameraId, trackId, objectType) │ │ ├── Si clé existe encore → événement SUPPRIMÉ (IsSuppressed=true) │ │ └── Si clé expirée → événement CRÉÉ, clé reset avec nouveau cooldown │ @@ -366,7 +366,7 @@ Agent : snapshot JPEG toutes les 200ms (adaptatif) Central reçoit snapshot │ ▼ - [NIVEAU 3] CodeProject.AI + [NIVEAU 3] Analyse IA (ONNX/broker) ├── Object Detection (YOLOv8, ~40ms GPU) ├── Face Recognition (si personne, ~40ms) └── ALPR (si véhicule + LPR, ~200ms) @@ -427,13 +427,13 @@ public class CameraDetectionProfile | Niveau | État | Action | |---|---|---| -| 0 | Normal | Pipeline complet : Agent YOLO → Central CPAI | -| 1 | CPAI lent (>1s) | Agent only (YOLOv8 nano, confidence baissée à 0.3) | -| 2 | CPAI down | Agent only + détection de mouvement seulement | +| 0 | Normal | Pipeline complet : Agent YOLO → analyse IA (locale ou broker) | +| 1 | Exécutant IA lent (>1s) | Agent only (YOLOv8 nano, confidence baissée à 0.3) | +| 2 | Exécutant IA down / broker injoignable | Agent only + détection de mouvement seulement | | 3 | Agent CPU >80% | Snapshots réduits de moitié, alert admin | | 4 | Queue overflow | Drop oldest snapshots, alert admin | -### 3.6 CodeProject.AI Gestion des Erreurs +### 3.6 Gestion des Erreurs IA (exécutant / broker) | Erreur | Comportement | Récupération | |---|---|---| @@ -505,7 +505,7 @@ public class CameraDetectionProfile | IDataProtector | Purposes isolées par type : `CameraCredentials`, `NotificationCredentials`, `SmtpConfig` | P0 | | Key ring partagé | Volume Docker monté : `/root/.aspnet/DataProtection-Keys` | P0 | | Audit logging | Table `AuditLog` append-only (login, admin actions, permissions) | P0 | -| HTTPS partout | Y compris CodeProject.AI interne (certificat CA auto) | P1 | +| HTTPS partout | Y compris AMQP TLS vers le broker (certificat CA auto) | P1 | | Docker secrets | `/run/secrets/` en production, env vars en dev | P1 | | Secrets dans logs | Sanitized : `password`, `token`, `secret`, `snapshotUrl` masqués dans Serilog et Sentry | P1 | | Mot de passe | Min 8 car, 1 maj, 1 chiffre. Check HaveIBeenPwned | P2 | @@ -1596,7 +1596,7 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ ├── IoU avec la frame précédente > 0.6 → même objet │ ├── TrackId persistant (Guid) pour chaque objet suivi │ └── Si même objet + cooldown actif → pas d'envoi au Central -├── [Central] CodeProject.AI +├── [Agents GPU] Analyse ONNX (local ou via broker) │ ├── Object Detection YOLOv8 (GPU, ~40ms) │ ├── Face Recognition (si personne, ~40ms) │ └── ALPR (si véhicule + LPR activé, ~200ms en async) @@ -1613,9 +1613,9 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ ├── LicensePlateDetected → ne PAS émettre VehicleDetected │ └── MotionDetected seul → événement silencieux (pas de notif) ├── Pipeline degradation : -│ ├── Normal : Agent YOLO → Central CPAI -│ ├── Degrade 1 : CPAI lent → Agent-only (confidence baissée 0.3) -│ ├── Degrade 2 : CPAI down → Motion-only (pas d'IA) +│ ├── Normal : Agent YOLO → analyse IA (locale ou via broker) +│ ├── Degrade 1 : exécutant IA lent → Agent-only (confidence baissée 0.3) +│ ├── Degrade 2 : exécutant IA down / broker injoignable → Motion-only (pas d'IA) │ └── Degrade 3 : CPU > 80% → snapshots réduits de moitié ├── Verify: détection + déduplication fonctionnelle │ @@ -1627,14 +1627,14 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ │ │ │ │ t+0ms → Motion détecté → YOLO → "person" (conf 0.85) │ │ │ TrackId = "A", IoU = nouveau │ -│ │ → Envoi au Central → CPAI → Face Rec → inconnu │ +│ │ → Envoi au Central → analyse IA → Face Rec → inconnu │ │ │ → Événement "UnknownPerson" créé │ │ │ → Cooldown personne=30s set pour Track "A" │ │ │ │ │ │ t+200ms → Motion → YOLO → "person" (conf 0.87) │ │ │ IoU avec Track "A" > 0.6 → MÊME objet │ │ │ Cooldown actif → PAS d'envoi au Central │ -│ │ ← ÉCONOMIE : pas de CPAI, pas d'événement │ +│ │ ← ÉCONOMIE : pas d'analyse IA, pas d'événement │ │ │ │ │ │ t+10s → Personne partie → plus de mouvement │ │ │ → Motion Gate stoppe YOLO │ @@ -1651,7 +1651,7 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ │ ┌─ SCÉNARIO VISAGE INCONNU ────────────────────────────────────┐ │ │ │ -│ │ t+0s → Visage détecté → CodeProject.AI Face Recognition │ +│ │ t+0s → Visage détecté → analyse IA (ONNX, agent GPU) │ │ │ → Aucun match connu → "UnknownPerson" │ │ │ → Embedding ajouté au cache LRU (TTL 5 min) │ │ │ → Notification "Visage inconnu" envoyée │ @@ -1669,12 +1669,12 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ │ ┌─ PIPELINE DEGRADATION ───────────────────────────────────────┐ │ │ │ -│ │ CodeProject.AI ne répond plus (down ou timeout) │ +│ │ Exécutant IA ne répond plus (down ou timeout) │ │ │ → Degrade Level 1 : Agent-only mode │ │ │ • YOLOv8 nano avec confidence abaissée à 0.3 │ │ │ • Résultats moins précis mais système continu │ -│ │ → Health check tente CPAI toutes les 30s │ -│ │ → CPAI revient → Degrade Level 0 (normal) │ +│ │ → Health check tente l'exécutant toutes les 30s │ +│ │ → Exécutant revient → Degrade Level 0 (normal) │ │ │ │ │ │ Si Agent CPU > 80% : Level 3 │ │ │ → Snapshots réduits de moitié (400ms au lieu de 200ms) │ @@ -1687,7 +1687,7 @@ Phase 16 — IA Pipeline (dédoublonnage 4 niveaux) │ • Dédoublonnage : pas d'event storm sur objets stationnaires │ • Visages inconnus : 1 notif toutes les 5 min max │ • Cooldowns configurables par caméra -│ • Pipeline degrade gracieusement si CPAI est down +│ • Pipeline degrade gracieusement si l'exécutant IA est down ═══════════════════════════════════════════════════════════════════════ @@ -1704,7 +1704,7 @@ Phase 17 — API Events + Persons + Vehicles ├── POST /api/persons (créer personne connue) │ Body: { "name", "notes", "photo" } → + face sample facultatif ├── POST /api/persons/{id}/face-sample (ajouter un visage) -│ → Enregistre le visage dans CodeProject.AI Face Register +│ → Enregistre le visage via l'analyse IA (ONNX) ├── PUT /api/persons/{id} ├── DELETE /api/persons/{id} (soft delete) ├── GET /api/vehicles (filtres : search par plaque, page) @@ -2087,18 +2087,18 @@ Phase 24 — Production Hardening ├── HTTPS forced (redirection HTTP→HTTPS) ├── Docker secrets (/run/secrets/) pour : │ ├── DB_PASSWORD, JWT_SIGNING_KEY -│ ├── COTURN_SECRET, CPAI_API_KEY, SMTP_PASSWORD +│ ├── COTURN_SECRET, BROKER_AMQP_PASSWORD, SMTP_PASSWORD │ └── ALARIK_ADMIN_USERNAME, ALARIK_ADMIN_PASSWORD, ALARIK_JWT ├── Serilog + Sentry/GlitchTip (PII stripping activé) │ ├── Sanitize : password, token, secret, snapshotUrl, ApiKey │ └── SendDefaultPii = false ├── OpenTelemetry metrics : │ ├── heimdall.events.created, heimdall.events.suppressed -│ ├── heimdall.ai.cpai.inference_ms, heimdall.ai.queue.depth +│ ├── heimdall.ai.inference_ms, heimdall.ai.queue.depth │ └── heimdall.signalr.connections, heimdall.streaming.viewers ├── Health checks : │ ├── GET /health (basique : API répond) -│ ├── GET /health/ready (DB, Alarik, CPAI, Redis OK) +│ ├── GET /health/ready (DB, Alarik, broker, Redis OK) │ └── GET /health/live (ready + pas de degradation active) ├── Backup automatisé (cron) : │ ├── PostgreSQL : pg_dump quotidien → Alarik backup/ @@ -2119,16 +2119,16 @@ Phase 24 — Production Hardening │ │ "name": "postgresql", │ │ │ "status": "Healthy" │ │ │ }, { │ -│ │ "name": "codeproject-ai", │ +│ │ "name": "broker-ia", │ │ │ "status": "Healthy" │ │ │ }] } │ │ │ GET /health/live → 200 { "status": "Healthy", │ │ │ "degradationLevel": 0 } │ │ │ │ -│ │ Si CodeProject.AI down : │ +│ │ Si broker/exécutant IA down : │ │ │ GET /health/live → 503 { "status": "Degraded", │ │ │ "degradationLevel": 2, │ -│ │ "message": "CodeProject.AI unavailable"}│ +│ │ "message": "Analyse IA unavailable"} │ │ └──────────────────────────────────────────────────────────────┘ │ │ ┌─ BACKUP ─────────────────────────────────────────────────────┐ @@ -2256,7 +2256,7 @@ services: - ConnectionStrings__Hangfire=Server=postgresql;Database=heimdall_hangfire;... - ConnectionStrings__Redis=redis:6379 - Alarik__Endpoint=http://alarik:8080 - - CPAI__Endpoint=http://codeproject-ai:32168 + # L'IA est exécutée par les agents (ONNX Runtime) — plus de service central - Ollama__Endpoint=http://ollama:11434 - Coturn__Url=turns:coturn:3478 - Coturn__Secret=${COTURN_SECRET} @@ -2328,28 +2328,6 @@ services: depends_on: - alarik - codeproject-ai: - image: codeproject/ai-server:2.9.5 - ports: - - "32168:32168" - environment: - - CPAI_PORT=32168 - - CPAI_API_KEY=${CPAI_API_KEY} # ← Authentification - - CPAI_LAUNCHER_GPU=GPU - - CPAI_MODULE_OBJECTDETECTION=true - - CPAI_MODULE_ALPR=true - - CPAI_MODULE_FACE=true - volumes: - - cpai_modules:/app/modules - - cpai_models:/app/../../../models - deploy: - resources: - reservations: - devices: - - driver: nvidia - count: all - capabilities: [gpu] - coturn: image: coturn/coturn:4.6 command: > @@ -2366,7 +2344,7 @@ services: | Conteneur | GPU | Docker Compose | |---|---|---| -| `codeproject-ai` | NVIDIA CUDA | `deploy.resources.reservations.devices` | +| agent GPU | NVIDIA/AMD/Intel | profiles compose GPU (nvidia/rocm/vaapi) — cf. docker | | `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `/dev/dri:/dev/dri` | | `ollama` | NVIDIA (optionnel) | `--gpus all` | @@ -2399,8 +2377,8 @@ EmbeddingDedup: same face embedding → no UnknownPerson EmbeddingDedup: different face embedding → UnknownPerson created HierarchicalSuppression: FaceRecognized suppresses PersonDetected HierarchicalSuppression: LicensePlateDetected suppresses VehicleDetected -AIPipelineDegradation: CPAI timeout → Agent-only mode -AIPipelineDegradation: CPAI down → motion-only mode +AIPipelineDegradation: exécutant IA timeout → Agent-only mode +AIPipelineDegradation: exécutant IA down → motion-only mode Backpressure: queue full → oldest snapshot dropped AdaptiveInterval: empty scene → 1000ms AdaptiveInterval: object detected → 200ms @@ -2418,7 +2396,7 @@ CameraStatusChange: debounce works when network flapping SignalR: disconnected user removed from groups SignalR: agent reconnects and rejoins site group Hangfire: queue isolation works (email doesn't block gotify) -CodeProjectAI: concurrent requests from multiple cameras +AnalysisWorker: concurrent requests from multiple cameras ``` --- @@ -2434,7 +2412,7 @@ CodeProjectAI: concurrent requests from multiple cameras | `heimdall.ai.pipeline.level` | Gauge | Niveau de dégradation actuel | | `heimdall.ai.snapshot.interval` | Gauge | Intervalle snapshot actuel | | `heimdall.ai.yolo.inference_ms` | Histogram | Temps inférence YOLO Agent | -| `heimdall.ai.cpai.inference_ms` | Histogram | Temps inférence CPAI | +| `heimdall.ai.inference_ms` | Histogram | Temps inférence IA (ONNX) | | `heimdall.ai.queue.depth` | Gauge | Profondeur queue snapshots | | `heimdall.signalr.connections` | Gauge | Connexions SignalR actives | | `heimdall.streaming.active_viewers` | Gauge | Viewers WebRTC actifs | @@ -2446,7 +2424,7 @@ CodeProjectAI: concurrent requests from multiple cameras | API | `/health` | 30s | | PostgreSQL | Ping DB | 30s | | Alarik | GET /health | 30s | -| CodeProject.AI | `/v1/status/ping` | 30s | +| Broker IA (RabbitMQ) | AMQP / healthcheck | 30s | | Ollama | `/api/tags` | 60s | | Agent | POST /api/agents/{id}/heartbeat | 30s | @@ -2489,7 +2467,7 @@ Les documents suivants contiennent des informations obsolètes ou erronées. | `auth-roles.md` | Mise à jour partielle | Site IDs retirés du JWT, audit log | | `mobile-app.md` | **À RÉÉCRIRE** (Avalonia, pas Kotlin) | Stack complet, architecture MVVM | | `ui-pages.md` | OK (inchangé) | — | -| `codeproject-ai.md` | Mise à jour partielle | Auth API key, erreurs, degradation | +| — | — | IA centralisée retirée (ONNX Runtime sur agents) | | `hangfire-usage.md` | Mise à jour partielle | Queue isolation, pagination, batch delete | --- @@ -2527,7 +2505,7 @@ Les documents suivants contiennent des informations obsolètes ou erronées. | A4 | Pas de backpressure (queue debordée) | ai-agent | Bounded Channel | | A5 | UnknownPerson event spam | ai-agent | Embedding cache LRU + 5min cooldown | | A6 | ALPR bloque le pipeline (200ms séquentiel) | ai-agent | ALPR async après commit | -| A7 | Pas de fallback si CodeProject.AI down | ai-agent | Degradation levels 0-4 | +| A7 | Pas de fallback si exécutant IA / broker down | ai-agent | Degradation levels 0-4 + file durable | | P1 | FFmpeg decode→re-encode ajoute 1-2s latence | perf-optimizer-agent | Mode PASSTHROUGH | | P2 | Pas de SignalR backplane | perf-optimizer-agent | Redis backplane (préparé) | | P3 | SendNotification queue non isolée | perf-optimizer-agent | Queues séparées (email, gotify, digest) | diff --git a/docs/README.md b/docs/README.md index 78c70ef..ef15e0b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,7 +30,7 @@ vidéosurveillance IA locale, multi-site, auto-hébergée. | Domaine | Document | Contenu | |---|---|---| | **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope | -| **CodeProject.AI** | `docs/codeproject-ai.md` | API endpoints, modules, modèles, performances, pipeline | +| **IA (ONNX)** | `docs/specs.md` | détection, face, ALPR — ONNX Runtime sur agents GPU | | **Hangfire (jobs)** | `docs/hangfire-usage.md` | Central PostgreSQL, Agent InMemory, tous les jobs | | **SignalR (temps réel)** | `docs/signalr-usage.md` | 5 hubs, events, streaming, monitoring, notifications | | **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose | diff --git a/docs/codeproject-ai.md b/docs/codeproject-ai.md deleted file mode 100644 index 8e13795..0000000 --- a/docs/codeproject-ai.md +++ /dev/null @@ -1,394 +0,0 @@ -# CodeProject.AI Server — Intégration Heimdall - -**Version :** 2.9.5 | **Repo :** [codeproject/CodeProject.AI-Server](https://github.com/codeproject/CodeProject.AI-Server) | **License :** SSPL - ---- - -## 1. Présentation - -CodeProject.AI Server est un microservice IA **auto-hébergé, gratuit et open-source**. -Il expose une API REST qui permet d'envoyer des images (snapshots) et de recevoir -des résultats de détection : objets, visages, plaques, scènes, etc. - -## 2. Modules disponibles - -### Computer Vision (utilisés par Heimdall) - -| Module | Version | Description | Backend | GPU | -|---|---|---|---|---| -| **Object Detection (YOLOv8)** | 1.6.2 | Détection 80 classes COCO | Python, PyTorch | NVIDIA CUDA | -| **Object Detection (YOLOv5 .NET)** | 1.14.0 | Détection objets (ONNX + DirectML) | C#, ONNX | DirectML (Windows) | -| **Object Detection (YOLOv5 6.2)** | 1.10.0 | Détection objets (PyTorch) | Python, PyTorch | NVIDIA CUDA 11.5+ | -| **Object Detection (Coral)** | 2.4.0 | Détection avec accélérateur Coral TPU | Python, TFLite | Coral TPU | -| **License Plate Reader** | 3.3.3 | Lecture plaques (ALPR) mono/multi-ligne | Python, PaddleOCR | NVIDIA CUDA | -| **Face Processing** | 1.12.3 | Détection, reconnaissance, comparaison visages | Python, PyTorch | NVIDIA CUDA | -| **Scene Classification** | 1.8.0 | Classification 365 scènes | Python, PyTorch | NVIDIA CUDA | -| **Optical Character Recognition** | 2.2.3 | OCR général (PaddleOCR) | Python, PaddlePaddle | NVIDIA CUDA | - -### Modules utiles (non utilisés directement par Heimdall) - -| Module | Description | -|---|---| -| **Background Remover** | Supprime l'arrière-plan d'une image | -| **Super Resolution** | Augmente la résolution d'une image par IA | -| **Portrait Filter** | Effet bokeh (profondeur de champ) | -| **Cartoonizer** | Transforme une photo en style anime | -| **Sound Classifier** | Classifie les sons (UrbanSound8K) | -| **Sentiment Analysis** | Analyse de sentiment d'un texte | -| **Text Summary** | Résumé automatique de texte | -| **LlamaChat** | LLM local (chat) | -| **MultiModeLLM** | LLM multimodal (texte + image) | -| **Text to Image** | Génération d'image par texte (Stable Diffusion) | - ---- - -## 3. API REST — Endpoints utilisés par Heimdall - -Base URL : `http://codeproject-ai:32168` - -### 3.1 Object Detection — `/v1/vision/detection` - -```http -POST http://codeproject-ai:32168/v1/vision/detection -Content-Type: multipart/form-data - -image: -min_confidence: 0.4 -``` - -Réponse : - -```json -{ - "success": true, - "predictions": [ - { "x_min": 100, "x_max": 200, "y_min": 50, "y_max": 200, - "confidence": 0.95, "label": "person" }, - { "x_min": 300, "x_max": 400, "y_min": 100, "y_max": 180, - "confidence": 0.87, "label": "car" } - ], - "count": 2, - "inferenceMs": 45, - "processMs": 120 -} -``` - -**Classes COCO détectables** (80) — les plus pertinentes pour Heimdall : - -``` -person, bicycle, car, motorcycle, bus, truck, train, boat -cat, dog, horse, sheep, cow, bear, deer -backpack, umbrella, handbag, suitcase, sports ball, bottle -chair, sofa, bench, potted plant, dining table, tv monitor, laptop -``` - -### 3.2 Custom Object Detection — `/v1/vision/custom/{model-name}` - -Modèles personnalisés disponibles par défaut : - -| Model | Classes détectées | -|---|---| -| `ipcam-animal` | bird, cat, dog, horse, sheep, cow, bear, deer, rabbit, raccoon, fox, skunk, squirrel, pig | -| `ipcam-dark` | bicycle, bus, car, cat, dog, motorcycle, person | -| `ipcam-general` | person, vehicle + ipcam-dark | -| `ipcam-combined` | person, bicycle, car, motorcycle, bus, truck, bird, cat, dog, horse, sheep, cow, bear, deer, rabbit, raccoon, fox, skunk, squirrel, pig | - -```http -POST http://codeproject-ai:32168/v1/vision/custom/ipcam-general -``` - -Lister les modèles disponibles : - -```http -POST http://codeproject-ai:32168/v1/vision/custom/list -``` - -### 3.3 License Plate Reader (ALPR) — `/v1/vision/alpr` - -```http -POST http://codeproject-ai:32168/v1/vision/alpr -Content-Type: multipart/form-data - -upload: -``` - -Réponse : - -```json -{ - "success": true, - "predictions": [ - { "x_min": 100, "x_max": 250, "y_min": 200, "y_max": 240, - "label": "AA-123-XX", "confidence": 0.92 } - ], - "count": 1, - "inferenceMs": 180, - "processMs": 250 -} -``` - -### 3.4 Face Detection — `/v1/vision/face` - -```http -POST http://codeproject-ai:32168/v1/vision/face -Content-Type: multipart/form-data - -image: -min_confidence: 0.5 -``` - -### 3.5 Face Recognition — `/v1/vision/face/recognize` - -Nécessite d'avoir enregistré des visages au préalable. - -```http -POST http://codeproject-ai:32168/v1/vision/face/recognize -Content-Type: multipart/form-data - -image: -min_confidence: 0.5 -``` - -Réponse : - -```json -{ - "success": true, - "predictions": [ - { "x_min": 100, "x_max": 200, "y_min": 50, "y_max": 200, - "confidence": 0.91, "label": "Jean Dupont", - "userid": "user_123" } - ] -} -``` - -### 3.6 Register Face — `/v1/vision/face/register` - -```http -POST http://codeproject-ai:32168/v1/vision/face/register -Content-Type: multipart/form-data - -image: -userid: "user_123" -username: "Jean Dupont" -``` - -### 3.7 Scene Classification — `/v1/vision/scene` - -365 scènes disponibles (conference_room, parking, kitchen, forest...). - -```http -POST http://codeproject-ai:32168/v1/vision/scene -Content-Type: multipart/form-data - -image: -``` - -### 3.8 Health Check - -```http -GET http://codeproject-ai:32168/v1/status/ping -→ { "success": true, "message": "pong" } -``` - ---- - -## 4. — Pipeline Heimdall → CodeProject.AI - -```text -Agent envoie snapshot (toutes les 200ms) - │ - ▼ -Pré-détection CPU (YOLOv8 nano) - │ - ├─ Rien détecté → ignore - │ - └─ Personne/Véhicule/Animal → envoie snapshot au Central - │ - ▼ - Heimdall API → POST /v1/vision/detection - ──────────────────────────────────────────── - │ │ │ - ▼ ▼ ▼ - CodeProject.AI CodeProject.AI CodeProject.AI - Object Detection ALPR (si plaque Face Rec (si - (YOLOv5/v8) activée + véhicule) visage + activée) - │ │ │ - └────────────────────┴──────────────────────┘ - │ - ▼ - Création événement - + Notification (Hangfire) -``` - -### Filtrage par DetectionProfile - -Avant d'appeler CodeProject.AI, l'API vérifie le profil de détection -de la caméra : - -```csharp -// Heimdall.Api → AiController.cs -[HttpPost("detect/{cameraId}")] -public async Task DetectAsync(Guid cameraId, IFormFile snapshot) -{ - var profile = await _db.CameraDetectionProfiles - .FirstOrDefaultAsync(p => p.CameraId == cameraId); - - var tasks = new List(); - - // Object detection (toujours si au moins un objet activé) - if (profile.DetectPerson || profile.DetectVehicle || profile.DetectAnimal) - { - tasks.Add(CallObjectDetectionAsync(snapshot, profile)); - } - - // License plate (uniquement si véhicule activé) - if (profile.DetectVehicle && profile.LicensePlateRecognition) - { - tasks.Add(CallAlprAsync(snapshot)); - } - - // Face recognition (uniquement si personne activée) - if (profile.DetectPerson && profile.FaceRecognition) - { - tasks.Add(CallFaceRecognitionAsync(snapshot)); - } - - await Task.WhenAll(tasks); - // ... -} -``` - ---- - -## 5. Docker — Configuration - -```yaml -services: - codeproject-ai: - image: codeproject/ai-server:2.9.5 - ports: - - "32168:32168" - volumes: - - codeproject_ai_modules:/app/modules - - codeproject_ai_models:/app/../../../models # modèles pré-téléchargés - environment: - - CPAI_LAUNCHER_GPU=GPU # auto-détection, ou CPU pour CPU only - deploy: - resources: - reservations: - devices: - - driver: nvidia - count: all - capabilities: [gpu] - restart: unless-stopped - -volumes: - codeproject_ai_modules: - codeproject_ai_models: -``` - -### Variables d'environnement - -| Variable | Valeur | Description | -|---|---|---| -| `CPAI_LAUNCHER_GPU` | `GPU` (défaut) ou `CPU` | Forcer CPU si pas de GPU | -| `CPAI_PORT` | `32168` | Port du serveur | -| `CPAI_MODULE_OBJECTDETECTION` | `true` / `false` | Activer/désactiver module | -| `CPAI_MODULE_ALPR` | `true` / `false` | Activer/désactiver ALPR | -| `CPAI_MODULE_FACE` | `true` / `false` | Activer/désactiver Face | - ---- - -## 6. Performances - -### Temps d'inférence moyens (CodeProject.AI v2.9.5) - -| Module | GPU (RTX 3060) | CPU (i5-10gen) | Raspberry Pi 4 | -|---|---|---|---| -| Object Detection YOLOv8 | 25-50ms | 150-300ms | 800-1500ms | -| Object Detection YOLOv5 .NET (DirectML) | 30-60ms | 200-400ms | — | -| License Plate Reader | 150-250ms | 500-1000ms | 3000-5000ms | -| Face Detection | 20-40ms | 100-200ms | 500-1000ms | -| Face Recognition (1 visage) | 30-50ms | 200-400ms | — | -| Scene Classification | 15-30ms | 80-150ms | — | - -### Impact sur le pipeline Heimdall (1080p, GPU) - -| Étape | Durée | Cumulative | -|---|---|---| -| Capture snapshot FFmpeg | ~50ms | 50ms | -| Pré-détection YOLOv8 nano (Agent CPU) | ~30ms | 80ms | -| Envoi HTTPS snapshot au Central | ~20ms | 100ms | -| **CodeProject.AI Object Detection** | **~40ms** | **140ms** | -| **CodeProject.AI ALPR** (si véhicule) | **~200ms** | **340ms** | -| **CodeProject.AI Face Rec** (si personne) | **~40ms** | **180ms** | -| Sauvegarde événement DB | ~15ms | 195ms | -| Notification (Hangfire) | ~5ms | 200ms | - -**Total avec GPU : ~200-350ms par snapshot traité.** -Intervalle snapshot par défaut : 200ms → pas de backlog. - ---- - -## 7. Gestion des modèles - -Les modèles sont téléchargés automatiquement par CodeProject.AI au -premier démarrage. Ils sont stockés dans les volumes Docker : - -``` -/usr/share/codeproject.ai/modules/ -├── ObjectDetectionYOLOv8/ -│ ├── assets/ -│ │ └── yolov8m.onnx # ~40 Mo -│ └── models/ -├── ALPR/ -│ ├── assets/ -│ └── models/ -└── FaceProcessing/ - └── assets/ -``` - -### Modèles personnalisés (ipcam-*) - -Heimdall peut utiliser les modèles personnalisés `ipcam-general`, -`ipcam-animal`, `ipcam-dark`, `ipcam-combined` déjà inclus dans -CodeProject.AI. Ces modèles sont optimisés pour la vidéosurveillance -(meilleure détection des animaux, sombre, etc.). - ---- - -## 8. Déploiement multi-instances (Mesh) - -CodeProject.AI supporte le **Mesh** : plusieurs instances peuvent -être chaînées pour répartir la charge : - -```text -Heimdall Central → CodeProject.AI (GPU principal) - │ - ▼ - CodeProject.AI (GPU secondaire) → ALPR - │ - ▼ - CodeProject.AI (CPU) → Face Recognition -``` - -Non requis pour Heimdall v1, mais disponible pour montée en charge. - ---- - -## 9. Tests d'intégration - -``` -CodeProject.AI responds to ping at /v1/status/ping -Object detection returns predictions from snapshot -Object detection with min_confidence=0.9 returns fewer results -ALPR reads license plate from vehicle snapshot -Face detection finds faces in person snapshot -Face recognition matches registered person -Scene classification returns label for indoor scene -Custom model ipcam-general detects person in dark image -Custom model ipcam-animal detects dog in snapshot -Invalid image returns error with success=false -Module deselection (CPAI_MODULE_ALPR=false) disables ALPR -``` diff --git a/docs/signalr-usage.md b/docs/signalr-usage.md index 1f712a8..e3a45d8 100644 --- a/docs/signalr-usage.md +++ b/docs/signalr-usage.md @@ -215,7 +215,7 @@ public class MonitoringHub : Hub | `AgentStatusChanged` | `AgentStatusDto` | Groupe monitoring du site | Agent online/offline | | `CameraStatusChanged` | `CameraStatusDto` | Groupe monitoring du site | Caméra online/offline | | `StorageUsageUpdated` | `StorageDto` | Admin | Espace Alarik mis à jour | -| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU CodeProject.AI | +| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU agent (ONNX Runtime) | | `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue | | `SystemHealthChanged` | `HealthDto` | Admin | Health check global | diff --git a/docs/specs.md b/docs/specs.md index b4e8777..e9bb22e 100644 --- a/docs/specs.md +++ b/docs/specs.md @@ -11,7 +11,7 @@ Heimdall is a modern self-hosted intelligent video surveillance platform. ## Pourquoi Heimdall ? -- **Privacy first** — tout l'IA tourne en local (CodeProject.AI + Ollama) +- **Privacy first** — tout l'IA tourne en local (ONNX Runtime sur agents + Ollama) - **Multi-site** — un Central + N Agents distants - **Économique** — pas d'abonnement cloud, hardware standard - **Pérenne** — .NET 10, Clean Architecture, open source @@ -23,7 +23,7 @@ Heimdall is a modern self-hosted intelligent video surveillance platform. - Clean Architecture / CQRS / MédiatR - Multi-site : 1 serveur Central + N Agents Docker distants - Live vidéo : WebRTC P2P (SIPSorcery), latence < 500 ms -- IA locale : CodeProject.AI (GPU) + Ollama (LLM résumés) +- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés) - Espace utilisateur : Admin (global) + User (site-scope) - Stockage : Alarik/S3 centralisé - Temps réel : SignalR (5 hubs) @@ -40,7 +40,7 @@ Heimdall is a modern self-hosted intelligent video surveillance platform. │ HEIMDALL CENTRAL │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ -│ │ API │ │ Web │ │ Workers │ │ CodeProject.AI │ │ +│ │ API │ │ Web │ │ Workers │ │ Broker IA │ │ │ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama │ │ │ │ SignalR │ │ MudBlazor│ │ Jobs │ │ Alarik │ │ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │ @@ -127,7 +127,7 @@ Enum: GpuAcceleration, ThemeMode - ONVIF WS-Discovery (même VLAN) + discovery manuelle (IP) - Protocole Imou : activation RTSP manuelle requise - FFmpeg capture : RTSP → H264, GPU auto-détection (NVENC/QSV/VAAPI/CPU) -- AI Pipeline two-tier : Agent CPU (YOLOv8 nano) → Central GPU (CodeProject.AI) +- AI Pipeline : Agent CPU (YOLOv8 nano) → analyse IA sur agents GPU (ONNX Runtime, local ou via broker inter-sites) - Détection : objets, visages, plaques (LPR), véhicules - Stockage credentials caméras chiffré (IDataProtector) @@ -208,7 +208,7 @@ services: heimdall-agent: # SIPSorcery + FFmpeg (InMemory Hangfire) postgresql: # Base de données alarik: # Stockage S3 (enregistrements) - codeproject-ai: # IA lourde GPU (détection, visages, LPR) + # IA lourde (détection, visages, LPR) : agents GPU ONNX Runtime — pas de service central ollama: # LLM local (résumés) mediamtx: # SFU WebRTC (optionnel, multi-user) coturn: # TURN relay (optionnel, double NAT) @@ -218,7 +218,7 @@ services: | Conteneur | GPU | Docker | |---|---|---| -| `codeproject-ai` | NVIDIA CUDA | `--gpus all` ou `deploy.resources.reservations.devices` | +| `heimdall-agent` (GPU) | NVIDIA/AMD/Intel | profiles compose GPU : nvidia / rocm (/dev/kfd,/dev/dri) / vaapi (/dev/dri) | | `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `--device /dev/dri:/dev/dri` | | `ollama` | NVIDIA (opt) | `--gpus all` | @@ -239,7 +239,7 @@ Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU). - Serilog (structure logging) - OpenTelemetry ready - Sentry SDK compatible GlitchTip -- Healthchecks (API, Agent, DB, Alarik, CodeProject.AI, Ollama) +- Healthchecks (API, Agent, DB, Alarik, Broker IA, Ollama) - Tests : xUnit + Shouldly + NSubstitute + bUnit + Testcontainers --- diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs new file mode 100644 index 0000000..b882741 --- /dev/null +++ b/src/Heimdall.Application/Common/IStorageProvider.cs @@ -0,0 +1,31 @@ +namespace Heimdall.Application.Common; + +/// +/// Object storage abstraction (spec Phase 8). Implemented by the local +/// filesystem provider and the S3-compatible provider (Alarik/MinIO). +/// Uploads use a staging prefix for atomicity: write to staging, then +/// move to the final key (crash → no orphan visible). +/// +public interface IStorageProvider +{ + /// Provider identifier (Local / S3). + string Provider { get; } + + /// True when the provider is configured and usable. + bool IsConfigured { get; } + + /// Upload bytes to a key (staging → final move, atomic). + Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default); + + /// Open a stream for reading a stored object. Null when missing. + Task DownloadAsync(string key, CancellationToken ct = default); + + /// Delete a single object. No-op when missing. + Task DeleteAsync(string key, CancellationToken ct = default); + + /// Delete a batch of objects (S3: 1000/appel). + Task DeleteBatchAsync(IReadOnlyCollection keys, CancellationToken ct = default); + + /// Check reachability/health of the backend. + Task HealthCheckAsync(CancellationToken ct = default); +} diff --git a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj index 70fda0b..39769cb 100644 --- a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj +++ b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj @@ -6,6 +6,7 @@ +