4NK_IA_back/docs/ARCHITECTURE.md
ncantu e4b7dc8b58 docs: Nettoyage et finalisation de la documentation
- Suppression des fichiers de documentation temporaires
- Mise à jour des URLs pour rester en localhost uniquement
- Finalisation de la documentation complète
- Nettoyage du dépôt
2025-09-09 06:35:10 +02:00

15 KiB

Architecture du Système - 4NK_IA Notarial

🏗️ Vue d'ensemble de l'Architecture

Le système notarial 4NK_IA est conçu selon une architecture microservices moderne, utilisant des conteneurs Docker pour la scalabilité et la maintenabilité.

🎯 Principes Architecturaux

1. Séparation des Responsabilités

  • API : Gestion des requêtes et orchestration
  • Worker : Traitement asynchrone des documents
  • Storage : Persistance des données
  • UI : Interface utilisateur

2. Scalabilité Horizontale

  • Services conteneurisés
  • Load balancing avec Traefik
  • Queue de traitement avec Celery
  • Base de données distribuée

3. Résilience et Fiabilité

  • Health checks automatiques
  • Retry policies
  • Circuit breakers
  • Monitoring complet

🏛️ Architecture Logique

┌─────────────────────────────────────────────────────────────────┐
│                    COUCHE PRÉSENTATION                         │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │   Client    │  │   Notaire   │  │   Admin     │            │
│  │   Web       │  │   Mobile    │  │   Dashboard │            │
│  │   (React)   │  │   (API)     │  │   (Grafana) │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────┬───────────────────────────────────────────┘
                      │ HTTP/HTTPS
┌─────────────────────▼───────────────────────────────────────────┐
│                    COUCHE API GATEWAY                          │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                  TRAEFIK                                │   │
│  │            Load Balancer + SSL                          │   │
│  └─────────────────────────────────────────────────────────┘   │
└─────────────────────┬───────────────────────────────────────────┘
                      │
┌─────────────────────▼───────────────────────────────────────────┐
│                    COUCHE SERVICES                             │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │   API       │  │   Worker    │  │   Web UI    │            │
│  │  FastAPI    │  │   Celery    │  │   Static    │            │
│  │  (8000)     │  │  (Async)    │  │   (8081)    │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────┬───────────────────────────────────────────┘
                      │
┌─────────────────────▼───────────────────────────────────────────┐
│                    COUCHE TRAITEMENT                           │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │ Preprocess  │  │     OCR     │  │ Classify    │            │
│  │ Pipeline    │  │  Pipeline   │  │ Pipeline    │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │  Extract    │  │   Index     │  │   Checks    │            │
│  │  Pipeline   │  │  Pipeline   │  │  Pipeline   │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────┬───────────────────────────────────────────┘
                      │
┌─────────────────────▼───────────────────────────────────────────┐
│                    COUCHE DONNÉES                              │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │ PostgreSQL  │  │   Redis     │  │   MinIO     │            │
│  │ (Structured)│  │  (Cache)    │  │ (Objects)   │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │   Neo4j     │  │ OpenSearch  │  │ AnythingLLM │            │
│  │  (Graph)    │  │ (Search)    │  │   (RAG)     │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────────────────────────────────────────────────┘

🔄 Flux de Données

1. Upload et Traitement de Document

sequenceDiagram
    participant C as Client
    participant A as API
    participant W as Worker
    participant DB as Database
    participant S as Storage
    participant LLM as Ollama

    C->>A: POST /upload
    A->>DB: Save document metadata
    A->>W: Queue processing task
    A->>C: Return document ID

    W->>S: Download document
    W->>W: Preprocess
    W->>W: OCR extraction
    W->>LLM: Classify document
    W->>W: Extract entities
    W->>W: Run verifications
    W->>DB: Save results
    W->>A: Update status

2. Pipeline de Traitement

# Orchestration des pipelines
def process_document(doc_id: str):
    ctx = {"doc_id": doc_id}

    # 1. Pré-traitement
    preprocess.run(doc_id, ctx)

    # 2. OCR
    ocr.run(doc_id, ctx)

    # 3. Classification
    classify.run(doc_id, ctx)

    # 4. Extraction d'entités
    extract.run(doc_id, ctx)

    # 5. Indexation
    index.run(doc_id, ctx)

    # 6. Vérifications
    checks.run(doc_id, ctx)

    # 7. Finalisation
    finalize.run(doc_id, ctx)

🗄️ Architecture des Données

Modèle de Données Principal

-- Documents
CREATE TABLE documents (
    id UUID PRIMARY KEY,
    filename VARCHAR(255) NOT NULL,
    status VARCHAR(50) DEFAULT 'uploaded',
    document_type VARCHAR(100),
    ocr_text TEXT,
    confidence_score FLOAT,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Entités extraites
CREATE TABLE entities (
    id UUID PRIMARY KEY,
    document_id UUID REFERENCES documents(id),
    entity_type VARCHAR(50) NOT NULL,
    entity_value TEXT NOT NULL,
    confidence FLOAT,
    context TEXT,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Vérifications
CREATE TABLE verifications (
    id UUID PRIMARY KEY,
    document_id UUID REFERENCES documents(id),
    verification_type VARCHAR(100) NOT NULL,
    verification_status VARCHAR(50) NOT NULL,
    result_data JSONB,
    created_at TIMESTAMP DEFAULT NOW()
);

Stockage Multi-Modal

Type de Donnée Service Usage
Métadonnées PostgreSQL Données structurées
Documents MinIO Fichiers originaux
Cache Redis Sessions et cache
Graphe Neo4j Relations entre entités
Recherche OpenSearch Indexation full-text
RAG AnythingLLM Contexte LLM

🔧 Composants Techniques

1. API FastAPI

# Structure de l'API
app = FastAPI(
    title="API Notariale",
    version="1.0.0",
    description="API pour l'analyse de documents notariaux"
)

# Routes principales
@app.post("/api/notary/upload")
async def upload_document(file: UploadFile):
    # Upload et traitement
    pass

@app.get("/api/notary/documents/{doc_id}")
async def get_document(doc_id: str):
    # Récupération des résultats
    pass

2. Worker Celery

# Configuration Celery
app = Celery('worker', broker='redis://redis:6379')

@app.task
def process_document(doc_id: str, metadata: dict):
    # Orchestration des pipelines
    pass

3. Pipelines de Traitement

# Pipeline OCR
def run(doc_id: str, ctx: dict):
    # Extraction de texte avec Tesseract
    # Correction lexicale notariale
    # Sauvegarde des résultats
    pass

🌐 Architecture de Déploiement

Environnement de Développement

# docker-compose.dev.yml
version: '3.8'
services:
  api:
    build: ./services/host_api
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://notariat:notariat_pwd@postgres:5432/notariat
    depends_on:
      - postgres
      - redis

Environnement de Production

# docker-compose.yml
version: '3.8'
services:
  traefik:
    image: traefik:v3.0
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./letsencrypt:/letsencrypt

📊 Monitoring et Observabilité

Métriques Collectées

# Métriques API
- http_requests_total
- http_request_duration_seconds
- active_connections
- error_rate

# Métriques Worker
- tasks_completed_total
- tasks_failed_total
- task_duration_seconds
- queue_length

# Métriques Base de Données
- db_connections_active
- db_queries_per_second
- db_query_duration_seconds

Logs Structurés

# Format des logs
{
    "timestamp": "2025-09-09T04:58:07Z",
    "level": "INFO",
    "service": "api",
    "request_id": "req_123",
    "user_id": "user_456",
    "message": "Document processed successfully",
    "metadata": {
        "doc_id": "doc_789",
        "processing_time": 2.5,
        "document_type": "acte_vente"
    }
}

🔒 Sécurité

Authentification et Autorisation

# JWT Authentication
from fastapi_jwt_auth import AuthJWT

@AuthJWT.verify_token
def verify_token(token: str):
    # Vérification du token JWT
    pass

# RBAC (Role-Based Access Control)
ROLES = {
    "notaire": ["read", "write", "process"],
    "clerk": ["read", "write"],
    "admin": ["read", "write", "process", "admin"]
}

Chiffrement des Données

# Chiffrement des données sensibles
from cryptography.fernet import Fernet

def encrypt_sensitive_data(data: str) -> str:
    # Chiffrement AES-256
    pass

def decrypt_sensitive_data(encrypted_data: str) -> str:
    # Déchiffrement
    pass

🚀 Scalabilité

Scaling Horizontal

# Docker Swarm / Kubernetes
api:
  replicas: 3
  resources:
    limits:
      memory: "512Mi"
      cpu: "500m"
    requests:
      memory: "256Mi"
      cpu: "250m"

worker:
  replicas: 5
  resources:
    limits:
      memory: "1Gi"
      cpu: "1000m"

Cache Strategy

# Redis Cache Layers
CACHE_LAYERS = {
    "L1": "In-memory (FastAPI)",
    "L2": "Redis (Distributed)",
    "L3": "Database (Persistent)"
}

# Cache TTL
CACHE_TTL = {
    "document_analysis": 3600,  # 1 heure
    "user_sessions": 86400,     # 24 heures
    "api_responses": 300        # 5 minutes
}

🔄 CI/CD Pipeline

Pipeline de Déploiement

# .github/workflows/deploy.yml
name: Deploy
on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: pytest tests/

  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Build Docker images
        run: docker build -t api:latest ./services/host_api

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        run: docker-compose up -d

📋 Checklist Architecture

Design Patterns Implémentés

  • Repository Pattern : Abstraction de la couche données
  • Factory Pattern : Création des pipelines
  • Observer Pattern : Événements de traitement
  • Strategy Pattern : Différents types de classification
  • Circuit Breaker : Gestion des pannes
  • Retry Pattern : Gestion des erreurs temporaires

Qualités Non-Fonctionnelles

  • Performance : < 2s pour l'upload, < 30s pour le traitement
  • Disponibilité : 99.9% uptime
  • Scalabilité : Support 1000+ documents/jour
  • Sécurité : Chiffrement, authentification, audit
  • Maintenabilité : Code modulaire, tests, documentation
  • Observabilité : Logs, métriques, traces

🎯 Évolutions Futures

Roadmap Technique

  1. Q1 2025 : Migration vers Kubernetes
  2. Q2 2025 : Intégration IA avancée (GPT-4)
  3. Q3 2025 : API GraphQL
  4. Q4 2025 : Multi-tenant architecture

Optimisations Prévues

  • Edge Computing : Traitement local
  • Streaming : Traitement en temps réel
  • MLOps : Pipeline d'entraînement automatique
  • Blockchain : Traçabilité des documents