augustin.podvin před 1 rokem
revize
395f7b923e

+ 153 - 0
.gitignore

@@ -0,0 +1,153 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# pipenv
+#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+#   However, in case of collaboration, if having platform-specific dependencies or dependencies
+#   having no cross-platform support, pipenv may install dependencies that don't work, or not
+#   install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# Project specific
+uploads/
+data/
+*.log
+cache_context.json
+page_hashes.json
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Docker
+.dockerignore
+
+# Temporary files
+*.tmp
+*.temp 

+ 238 - 0
DEPLOYMENT.md

@@ -0,0 +1,238 @@
+# Guide de Déploiement - Assistant AI
+
+## 🎯 Différences entre les options
+
+### Option 1 : Docker Compose (Local)
+- **Environnement** : Votre machine locale
+- **Usage** : Développement, test, démonstration
+- **Avantages** : Simple, rapide, pas de coût
+- **Limitations** : Pas accessible depuis l'extérieur
+- **Prérequis** : Docker Desktop
+
+### Option 2 : Render.com
+- **Environnement** : Cloud géré
+- **Usage** : Production simple, accessible publiquement
+- **Avantages** : Déploiement automatique, SSL gratuit
+- **Limitations** : Moins de contrôle, coût mensuel
+- **Prérequis** : Compte GitHub connecté
+
+### Option 3 : VPS Privé
+- **Environnement** : Serveur distant (AWS, OVH, DigitalOcean)
+- **Usage** : Production professionnelle, contrôle total
+- **Avantages** : Performance, sécurité, personnalisation
+- **Coût** : ~5-50€/mois selon le serveur
+- **Prérequis** : Option 1 + serveur VPS
+
+## 🚀 Déploiement Local (Option 1)
+
+### 1. Installation de Docker Desktop
+
+**Windows :**
+```bash
+# Via winget (recommandé)
+winget install Docker.DockerDesktop
+
+# Ou téléchargement manuel
+# https://www.docker.com/products/docker-desktop
+```
+
+**Linux :**
+```bash
+curl -fsSL https://get.docker.com -o get-docker.sh
+sh get-docker.sh
+```
+
+### 2. Configuration des variables d'environnement
+
+```bash
+# Copier le fichier d'exemple
+cp env.example .env
+
+# Éditer avec vos vraies valeurs
+notepad .env  # Windows
+nano .env     # Linux
+```
+
+**Variables obligatoires :**
+```bash
+SERPAPI_KEY=your_serpapi_key_here
+WIKI_USERNAME=your_wiki_username
+WIKI_PASSWORD=your_wiki_password
+```
+
+### 3. Déploiement automatique
+
+```bash
+# Script automatique (Linux/Mac)
+chmod +x scripts/setup.sh
+./scripts/setup.sh
+
+# Ou manuellement
+docker-compose up -d
+```
+
+### 4. Vérification
+
+```bash
+# Vérifier les services
+docker-compose ps
+
+# Voir les logs
+docker-compose logs -f
+
+# Tester l'application
+curl http://localhost:5000/
+```
+
+## 🌐 Déploiement VPS (Option 3)
+
+### 1. Préparation du VPS
+
+**Choisir un VPS :**
+- **OVH** : VPS SSD 2 (4€/mois) - Recommandé pour débuter
+- **DigitalOcean** : Droplet Basic (5$/mois)
+- **AWS EC2** : t3.small (~15$/mois)
+
+**Spécifications minimales :**
+- 2 vCPU
+- 4 GB RAM
+- 20 GB SSD
+- Ubuntu 20.04+
+
+### 2. Déploiement automatique
+
+```bash
+# Script de déploiement
+chmod +x scripts/deploy-vps.sh
+./scripts/deploy-vps.sh <vps-ip> <user> <ssh-key>
+
+# Exemple
+./scripts/deploy-vps.sh 192.168.1.100 root ~/.ssh/id_rsa
+```
+
+### 3. Configuration manuelle
+
+```bash
+# Connexion au VPS
+ssh user@vps-ip
+
+# Installation de Docker
+curl -fsSL https://get.docker.com -o get-docker.sh
+sh get-docker.sh
+
+# Installation de Docker Compose
+sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
+sudo chmod +x /usr/local/bin/docker-compose
+
+# Cloner le projet
+git clone <your-repo>
+cd assistant-ai
+
+# Configurer les variables
+cp env.example .env
+nano .env
+
+# Déployer
+docker-compose up -d
+```
+
+## 🧪 Tests et Monitoring
+
+### Tests automatiques
+
+```bash
+# Exécuter les tests de déploiement
+python tests/test_deployment.py
+```
+
+### Monitoring
+
+```bash
+# Logs en temps réel
+docker-compose logs -f
+
+# Statut des services
+docker-compose ps
+
+# Utilisation des ressources
+docker stats
+```
+
+### Healthchecks
+
+Les services incluent des healthchecks automatiques :
+- **Flask App** : `http://localhost:5000/`
+- **Ollama** : `http://localhost:11434/api/tags`
+
+## 🔧 Améliorations recommandées
+
+### 1. Sécurité
+- [ ] Ajouter un reverse proxy (Nginx)
+- [ ] Configurer SSL/TLS
+- [ ] Implémenter l'authentification
+- [ ] Limiter les accès par IP
+
+### 2. Performance
+- [ ] Optimiser les modèles ML
+- [ ] Ajouter du caching Redis
+- [ ] Implémenter la compression
+- [ ] Optimiser les images Docker
+
+### 3. Monitoring
+- [ ] Ajouter Prometheus/Grafana
+- [ ] Implémenter des alertes
+- [ ] Logs centralisés
+- [ ] Métriques d'utilisation
+
+### 4. CI/CD
+- [ ] GitHub Actions
+- [ ] Tests automatisés
+- [ ] Déploiement automatique
+- [ ] Rollback automatique
+
+## 🆘 Dépannage
+
+### Problèmes courants
+
+**1. Docker ne démarre pas**
+```bash
+# Redémarrer Docker Desktop
+# Ou sur Linux
+sudo systemctl restart docker
+```
+
+**2. Ports déjà utilisés**
+```bash
+# Vérifier les ports
+netstat -tulpn | grep :5000
+# Changer les ports dans docker-compose.yml
+```
+
+**3. Variables d'environnement manquantes**
+```bash
+# Vérifier le fichier .env
+cat .env
+# S'assurer que toutes les variables sont définies
+```
+
+**4. Modèles Ollama non téléchargés**
+```bash
+# Télécharger le modèle
+docker exec -it assistant-ai-ollama-1 ollama pull llama3
+```
+
+## 📊 Comparaison des options
+
+| Critère | Local | Render | VPS |
+|---------|-------|--------|-----|
+| **Coût** | Gratuit | 7$/mois | 5-50€/mois |
+| **Complexité** | Simple | Très simple | Moyenne |
+| **Contrôle** | Total | Limité | Total |
+| **Performance** | Moyenne | Bonne | Excellente |
+| **Sécurité** | Basique | Bonne | Excellente |
+| **Maintenance** | Manuelle | Automatique | Manuelle |
+
+## 🎯 Recommandation
+
+**Pour débuter :** Option 1 (Local) → Option 2 (Render)
+**Pour production :** Option 3 (VPS) avec les améliorations de sécurité 

+ 43 - 0
Dockerfile

@@ -0,0 +1,43 @@
+# Utiliser une image Python officielle
+FROM python:3.11-slim
+
+# Définir le répertoire de travail
+WORKDIR /app
+
+# Installer les dépendances système nécessaires
+RUN apt-get update && apt-get install -y \
+    build-essential \
+    curl \
+    software-properties-common \
+    git \
+    libgl1-mesa-glx \
+    libglib2.0-0 \
+    libsm6 \
+    libxext6 \
+    libxrender-dev \
+    libgomp1 \
+    libgcc-s1 \
+    && rm -rf /var/lib/apt/lists/*
+
+# Copier les fichiers de dépendances
+COPY requirements-prod.txt requirements.txt
+
+# Installer les dépendances Python
+RUN pip install --no-cache-dir -r requirements.txt
+
+# Copier le code de l'application
+COPY . .
+
+# Créer les dossiers nécessaires
+RUN mkdir -p uploads data
+
+# Exposer le port
+EXPOSE 5000
+
+# Variables d'environnement par défaut
+ENV FLASK_APP=src.app
+ENV FLASK_ENV=production
+ENV PYTHONPATH=/app
+
+# Commande par défaut avec Gunicorn
+CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "2", "--timeout", "120", "--preload", "wsgi:app"] 

+ 95 - 0
PROJECT_STRUCTURE.md

@@ -0,0 +1,95 @@
+# Structure du Projet Assistant AI
+
+## 📁 Organisation des dossiers
+
+```
+assistant_ai/
+├── 📁 src/                          # Code source principal
+│   ├── 📁 api/                      # Routes API
+│   ├── 📁 models/                   # Modèles ML
+│   │   └── VLM.py                  # Vision Language Model
+│   ├── 📁 static/                   # Assets statiques (CSS, JS, images)
+│   ├── 📁 templates/                # Templates HTML
+│   │   └── index.html              # Interface utilisateur
+│   ├── 📁 utils/                    # Utilitaires
+│   │   ├── ocr.py                  # OCR des documents
+│   │   └── processing.py           # Traitement des données
+│   ├── 📁 agent_ai/                # Module d'authentification
+│   │   └── auth.py                 # Authentification Wiki
+│   └── app.py                      # Application Flask principale
+├── 📁 tests/                        # Tests automatisés
+│   └── test_deployment.py          # Tests de déploiement
+├── 📁 scripts/                      # Scripts de déploiement
+│   ├── setup.sh                    # Installation locale
+│   └── deploy-vps.sh               # Déploiement VPS
+├── 📁 uploads/                      # Fichiers uploadés (généré)
+├── 📁 data/                         # Données persistantes (généré)
+├── 📄 config.py                     # Configuration centralisée
+├── 📄 wsgi.py                       # Point d'entrée WSGI
+├── 📄 requirements.txt              # Dépendances complètes
+├── 📄 requirements-prod.txt         # Dépendances production
+├── 📄 Dockerfile                    # Configuration Docker
+├── 📄 docker-compose.yml           # Orchestration Docker
+├── 📄 render.yaml                   # Configuration Render.com
+├── 📄 env.example                   # Variables d'environnement
+├── 📄 .gitignore                    # Fichiers ignorés Git
+├── 📄 README.md                     # Documentation principale
+├── 📄 DEPLOYMENT.md                 # Guide de déploiement
+└── 📄 PROJECT_STRUCTURE.md          # Ce fichier
+```
+
+## 🔧 Fichiers de configuration
+
+### `config.py`
+Configuration centralisée de l'application avec :
+- Variables d'environnement
+- Configuration Flask
+- Paramètres des modèles ML
+- Configuration des API
+
+### `wsgi.py`
+Point d'entrée pour le déploiement avec Gunicorn
+
+### `requirements-prod.txt`
+Dépendances optimisées pour la production
+
+## 🚀 Déploiement
+
+### Local (Docker Compose)
+```bash
+docker-compose up -d
+```
+
+### VPS
+```bash
+./scripts/deploy-vps.sh <vps-ip> <user> <ssh-key>
+```
+
+### Render.com
+Configuration automatique via `render.yaml`
+
+## 🧪 Tests
+
+```bash
+python tests/test_deployment.py
+```
+
+## 📊 Monitoring
+
+- **Healthchecks** : Intégrés dans Docker Compose
+- **Logs** : `docker-compose logs -f`
+- **Statut** : `docker-compose ps`
+
+## 🔒 Sécurité
+
+- Variables d'environnement pour les secrets
+- Limite de taille de fichiers
+- Validation des extensions
+- Configuration production sécurisée
+
+## 📈 Évolutions recommandées
+
+1. **Sécurité** : Nginx + SSL
+2. **Performance** : Redis cache
+3. **Monitoring** : Prometheus + Grafana
+4. **CI/CD** : GitHub Actions 

+ 110 - 0
README.md

@@ -0,0 +1,110 @@
+# Assistant AI - Déploiement
+
+## Problèmes identifiés et corrigés
+
+### 1. **Clés API hardcodées** ✅
+- **Problème** : Clé SerpAPI hardcodée dans le code
+- **Solution** : Utilisation des variables d'environnement
+
+### 2. **Configuration de développement** ✅
+- **Problème** : `debug=True` et `localhost` en production
+- **Solution** : Configuration conditionnelle basée sur les variables d'environnement
+
+### 3. **Dépendances lourdes** ✅
+- **Problème** : Toutes les dépendances de développement incluses
+- **Solution** : `requirements-prod.txt` optimisé
+
+### 4. **Pas de configuration Docker** ✅
+- **Problème** : Aucun fichier de déploiement
+- **Solution** : Dockerfile et docker-compose.yml créés
+
+## 🚀 Déploiement Manuel
+
+### Option 1 : Docker Compose (Recommandé)
+
+1. **Vérifier Docker**
+```bash
+docker --version
+docker-compose --version
+```
+
+2. **Configurer les variables d'environnement**
+```bash
+cp env.example .env
+# Éditer .env avec vos vraies valeurs
+```
+
+3. **Créer les dossiers nécessaires**
+```bash
+mkdir uploads data
+```
+
+4. **Lancer avec Docker Compose**
+```bash
+docker-compose up -d
+```
+
+### Option 2 : Render.com
+
+1. **Connecter votre repo GitHub à Render**
+2. **Configurer les variables d'environnement** dans l'interface Render
+3. **Déployer automatiquement**
+
+### Option 3 : VPS Privé
+
+1. **Installer Docker sur votre VPS**
+```bash
+curl -fsSL https://get.docker.com -o get-docker.sh
+sh get-docker.sh
+```
+
+2. **Cloner et déployer**
+```bash
+git clone <votre-repo>
+cd assistant_ai
+docker-compose up -d
+```
+
+## Variables d'environnement requises
+
+```bash
+# Obligatoires
+SERPAPI_KEY=your_serpapi_key_here
+WIKI_USERNAME=your_wiki_username
+WIKI_PASSWORD=your_wiki_password
+
+# Optionnelles (valeurs par défaut)
+FLASK_ENV=production
+FLASK_DEBUG=false
+FLASK_HOST=0.0.0.0
+FLASK_PORT=5000
+OLLAMA_HOST=http://ollama:11434
+UPLOAD_FOLDER=uploads
+MAX_CONTENT_LENGTH=16777216
+```
+
+## Architecture
+
+- **Flask App** : Port 5000
+- **Ollama** : Port 11434 (pour les modèles LLM)
+- **Volumes persistants** : uploads/, data/, ollama_data
+
+## Sécurité
+
+- ✅ Clés API externalisées
+- ✅ Mode debug désactivé en production
+- ✅ Limite de taille de fichier configurée
+- ✅ Variables d'environnement pour les secrets
+
+## Monitoring
+
+- Logs disponibles via `docker-compose logs -f`
+- Métriques d'application dans les logs Flask
+- Scheduler APScheduler pour les mises à jour automatiques
+
+## 📋 Instructions détaillées
+
+Pour des instructions complètes, consultez :
+- `SETUP_MANUAL.md` - Guide de setup manuel
+- `DEPLOYMENT.md` - Guide de déploiement complet
+- `PROJECT_STRUCTURE.md` - Structure du projet 

+ 147 - 0
SETUP_MANUAL.md

@@ -0,0 +1,147 @@
+# Setup Manuel - Assistant AI
+
+## 📁 Création de la structure des dossiers
+
+Exécutez ces commandes **manuellement** dans votre terminal :
+
+### 1. Créer les dossiers src
+```bash
+mkdir src\api
+mkdir src\static
+mkdir src\templates
+mkdir src\models
+mkdir src\utils
+```
+
+### 2. Créer les dossiers de données
+```bash
+mkdir uploads
+mkdir data
+```
+
+### 3. Créer les dossiers de scripts et tests
+```bash
+mkdir scripts
+mkdir tests
+```
+
+## 📄 Déplacer les fichiers
+
+### 4. Déplacer les fichiers principaux
+```bash
+move app.py src\
+move index.html src\templates\
+move ocr.py src\utils\
+move processing.py src\utils\
+move VLM.py src\models\
+move agent_ai src\
+```
+
+### 5. Créer les fichiers __init__.py
+```bash
+echo # Package src pour l'application Assistant AI > src\__init__.py
+echo # Utilitaires pour l'application > src\utils\__init__.py
+echo # Modèles ML pour l'application > src\models\__init__.py
+echo # API routes pour l'application > src\api\__init__.py
+```
+
+## ⚙️ Configuration
+
+### 6. Copier le fichier d'environnement
+```bash
+copy env.example .env
+```
+
+### 7. Éditer le fichier .env
+Ouvrez le fichier `.env` et configurez vos variables :
+```bash
+notepad .env
+```
+
+**Variables obligatoires :**
+```bash
+SERPAPI_KEY=your_serpapi_key_here
+WIKI_USERNAME=your_wiki_username
+WIKI_PASSWORD=your_wiki_password
+```
+
+## 🚀 Déploiement
+
+### 8. Vérifier Docker
+```bash
+docker --version
+docker-compose --version
+```
+
+### 9. Lancer l'application
+```bash
+docker-compose up -d
+```
+
+### 10. Vérifier le statut
+```bash
+docker-compose ps
+```
+
+### 11. Voir les logs
+```bash
+docker-compose logs -f
+```
+
+## 🧪 Tests
+
+### 12. Tester l'application
+```bash
+python tests/test_deployment.py
+```
+
+## 📊 Monitoring
+
+### 13. Vérifier les services
+```bash
+# Statut des conteneurs
+docker-compose ps
+
+# Logs en temps réel
+docker-compose logs -f
+
+# Utilisation des ressources
+docker stats
+```
+
+## 🆘 En cas de problème
+
+### Docker ne démarre pas
+```bash
+# Redémarrer Docker Desktop
+# Ou sur Linux
+sudo systemctl restart docker
+```
+
+### Ports déjà utilisés
+```bash
+# Vérifier les ports
+netstat -tulpn | grep :5000
+```
+
+### Variables d'environnement manquantes
+```bash
+# Vérifier le fichier .env
+type .env
+```
+
+## ✅ Vérification finale
+
+Une fois tout configuré, votre application devrait être accessible sur :
+- **Local** : http://localhost:5000
+- **Interface** : Interface web pour uploader des fichiers
+- **API** : Endpoints pour l'authentification et les questions
+
+## 📝 Notes importantes
+
+- Tous les fichiers de configuration sont déjà créés
+- Les scripts de déploiement sont prêts
+- La structure est optimisée pour la production
+- Les tests sont inclus
+
+Votre projet est maintenant **prêt pour le déploiement** ! 🎉 

+ 0 - 0
__init__.py


+ 1 - 0
app.py

@@ -0,0 +1 @@
+ 

+ 61 - 0
config.py

@@ -0,0 +1,61 @@
+import os
+
+class Config:
+    """Configuration de base pour l'application"""
+    
+    # Configuration Flask
+    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-in-production'
+    FLASK_ENV = os.environ.get('FLASK_ENV', 'production')
+    FLASK_DEBUG = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
+    FLASK_HOST = os.environ.get('FLASK_HOST', '0.0.0.0')
+    FLASK_PORT = int(os.environ.get('FLASK_PORT', 5000))
+    
+    # Configuration des fichiers
+    UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', 'uploads')
+    MAX_CONTENT_LENGTH = int(os.environ.get('MAX_CONTENT_LENGTH', 16 * 1024 * 1024))  # 16MB
+    
+    # Configuration des API
+    SERPAPI_KEY = os.environ.get('SERPAPI_KEY')
+    WIKI_USERNAME = os.environ.get('WIKI_USERNAME')
+    WIKI_PASSWORD = os.environ.get('WIKI_PASSWORD')
+    
+    # Configuration Ollama
+    OLLAMA_HOST = os.environ.get('OLLAMA_HOST', 'http://localhost:11434')
+    OLLAMA_MODEL = os.environ.get('OLLAMA_MODEL', 'llama3')
+    
+    # Configuration des modèles ML
+    EMBEDDING_MODEL = 'all-MiniLM-L6-v2'
+    CROSS_ENCODER_MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
+    
+    # Configuration du scheduler
+    SCHEDULER_INTERVAL_MINUTES = int(os.environ.get('SCHEDULER_INTERVAL_MINUTES', 30))
+    
+    # Extensions de fichiers autorisées
+    ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
+    
+    @staticmethod
+    def init_app(app):
+        """Initialiser la configuration pour l'application Flask"""
+        pass
+
+class DevelopmentConfig(Config):
+    """Configuration pour le développement"""
+    FLASK_DEBUG = True
+    FLASK_ENV = 'development'
+
+class ProductionConfig(Config):
+    """Configuration pour la production"""
+    FLASK_DEBUG = False
+    FLASK_ENV = 'production'
+
+class TestingConfig(Config):
+    """Configuration pour les tests"""
+    TESTING = True
+    FLASK_DEBUG = True
+
+config = {
+    'development': DevelopmentConfig,
+    'production': ProductionConfig,
+    'testing': TestingConfig,
+    'default': DevelopmentConfig
+} 

+ 46 - 0
docker-compose.yml

@@ -0,0 +1,46 @@
+version: '3.8'
+
+services:
+  app:
+    build: .
+    ports:
+      - "5000:5000"
+    environment:
+      - FLASK_ENV=production
+      - FLASK_DEBUG=false
+      - FLASK_HOST=0.0.0.0
+      - FLASK_PORT=5000
+      - FLASK_APP=src.app
+      - SERPAPI_KEY=${SERPAPI_KEY}
+      - WIKI_USERNAME=${WIKI_USERNAME}
+      - WIKI_PASSWORD=${WIKI_PASSWORD}
+      - OLLAMA_HOST=http://ollama:11434
+      - UPLOAD_FOLDER=uploads
+      - MAX_CONTENT_LENGTH=16777216
+    volumes:
+      - ./uploads:/app/uploads
+      - ./data:/app/data
+    depends_on:
+      - ollama
+    restart: unless-stopped
+    healthcheck:
+      test: ["CMD", "curl", "-f", "http://localhost:5000/"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+
+  ollama:
+    image: ollama/ollama:latest
+    ports:
+      - "11434:11434"
+    volumes:
+      - ollama_data:/root/.ollama
+    restart: unless-stopped
+    healthcheck:
+      test: ["CMD", "curl", "-f", "http://localhost:11434/api/tags"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+
+volumes:
+  ollama_data: 

+ 17 - 0
env.example

@@ -0,0 +1,17 @@
+# Configuration de l'application
+FLASK_ENV=production
+FLASK_DEBUG=False
+
+# Clés API
+SERPAPI_KEY=your_serpapi_key_here
+
+# Credentials Wiki
+WIKI_USERNAME=your_wiki_username
+WIKI_PASSWORD=your_wiki_password
+
+# Configuration Ollama
+OLLAMA_HOST=http://ollama:11434
+
+# Configuration de l'application
+UPLOAD_FOLDER=uploads
+MAX_CONTENT_LENGTH=16777216 

+ 29 - 0
render.yaml

@@ -0,0 +1,29 @@
+services:
+  - type: web
+    name: assistant-ai
+    env: python
+    buildCommand: pip install -r requirements.txt
+    startCommand: python wsgi.py
+    envVars:
+      - key: FLASK_ENV
+        value: production
+      - key: FLASK_DEBUG
+        value: false
+      - key: FLASK_HOST
+        value: 0.0.0.0
+      - key: FLASK_PORT
+        value: 10000
+      - key: FLASK_APP
+        value: src.app
+      - key: SERPAPI_KEY
+        sync: false
+      - key: WIKI_USERNAME
+        sync: false
+      - key: WIKI_PASSWORD
+        sync: false
+      - key: OLLAMA_HOST
+        value: http://ollama:11434
+      - key: UPLOAD_FOLDER
+        value: uploads
+      - key: MAX_CONTENT_LENGTH
+        value: 16777216 

+ 23 - 0
requirements-prod.txt

@@ -0,0 +1,23 @@
+Flask==3.1.1
+APScheduler==3.11.0
+sentence-transformers==5.0.0
+langchain-ollama==0.3.6
+faiss-cpu==1.11.0.post1
+scikit-learn==1.2.2
+numpy==1.24.4
+requests==2.32.4
+beautifulsoup4==4.13.4
+google_search_results==2.4.2
+Werkzeug==3.1.3
+PyPDF2==3.0.1
+Pillow==10.4.0
+transformers==4.54.0
+tiktoken==0.7.0
+tabulate==0.9.0
+python-multipart==0.0.20
+gunicorn==21.2.0
+# OCR et Vision
+python-doctr==1.0.0
+opencv-python-headless==4.5.5.64
+torch==2.1.2
+torchvision==0.16.2 

+ 210 - 0
requirements.txt

@@ -0,0 +1,210 @@
+accelerate==1.9.0
+aiofiles==23.2.1
+altair==5.5.0
+annotated-types==0.7.0
+antlr4-python3-runtime==4.9.3
+anyascii==0.3.3
+anyio==4.9.0
+APScheduler==3.11.0
+asttokens==3.0.0
+attrs==25.3.0
+beautifulsoup4==4.13.4
+bitsandbytes==0.45.5
+bleach==6.2.0
+blinker==1.9.0
+blis==1.3.0
+braceexpand==0.1.7
+cachetools==6.1.0
+catalogue==2.0.10
+certifi==2025.7.14
+cffi==1.17.1
+cfgv==3.4.0
+charset-normalizer==3.4.2
+click==8.2.1
+cloudpathlib==0.21.1
+colorama==0.4.6
+confection==0.1.5
+contexttimer==0.3.3
+contourpy==1.3.2
+cryptography==45.0.5
+cycler==0.12.1
+cymem==2.0.11
+decorator==5.2.1
+decord==0.6.0
+defusedxml==0.7.1
+distlib==0.4.0
+doctr==1.9.0
+einops==0.6.1
+einops-exts==0.0.4
+exceptiongroup==1.3.0
+executing==2.2.0
+fairscale==0.4.4
+faiss-cpu==1.11.0.post1
+fastapi==0.116.1
+ffmpy==0.6.1
+filelock==3.18.0
+Flask==3.1.1
+fonttools==4.59.0
+fsspec==2025.7.0
+ftfy==6.3.1
+gitdb==4.0.12
+GitPython==3.1.45
+google_search_results==2.4.2
+gradio==4.16.0
+gradio_client==0.8.1
+h11==0.14.0
+h5py==3.14.0
+httpcore==0.17.3
+httpx==0.24.0
+huggingface-hub==0.34.3
+identify==2.6.12
+idna==3.10
+imageio==2.37.0
+importlib_resources==6.5.2
+iopath==0.1.10
+ipython==8.37.0
+itsdangerous==2.2.0
+jedi==0.19.2
+Jinja2==3.1.6
+joblib==1.5.1
+jsonpatch==1.33
+jsonpointer==3.0.0
+jsonschema==4.25.0
+jsonschema-specifications==2025.4.1
+kaggle==1.7.4.5
+kiwisolver==1.4.8
+langchain-core==0.3.72
+langchain-ollama==0.3.6
+langcodes==3.5.0
+langdetect==1.0.9
+langsmith==0.4.8
+language_data==1.3.0
+latex2mathml==3.78.0
+lazy_loader==0.4
+-e git+https://github.com/haotian-liu/LLaVA.git@c121f0432da27facab705978f83c4ada465e46fd#egg=llava
+marisa-trie==1.2.1
+markdown-it-py==3.0.0
+markdown2==2.5.4
+MarkupSafe==2.1.5
+matplotlib==3.10.3
+matplotlib-inline==0.1.7
+mdurl==0.1.2
+mpmath==1.3.0
+murmurhash==1.0.13
+narwhals==2.0.1
+networkx==3.4.2
+nltk==3.9.1
+nodeenv==1.9.1
+numpy==1.24.4
+ollama==0.5.1
+omegaconf==2.3.0
+onnx==1.18.0
+opencv-python==4.7.0.72
+opencv-python-headless==4.5.5.64
+opendatasets==0.1.22
+orjson==3.11.1
+packaging==25.0
+pandas==2.3.1
+parso==0.8.4
+peft==0.16.0
+pillow==10.4.0
+platformdirs==4.3.8
+plotly==6.2.0
+portalocker==3.2.0
+pre_commit==4.2.0
+preshed==3.0.10
+prompt_toolkit==3.0.51
+protobuf==6.31.1
+psutil==7.0.0
+pure_eval==0.2.3
+pyarrow==21.0.0
+pyclipper==1.3.0.post6
+pycocoevalcap==1.2
+pycocotools==2.0.10
+pycparser==2.22
+pydantic==2.11.7
+pydantic_core==2.33.2
+pydeck==0.9.1
+pydub==0.25.1
+Pygments==2.19.2
+pyparsing==3.2.3
+PyPDF2==3.0.1
+pypdfium2==4.30.0
+python-dateutil==2.9.0.post0
+python-doctr==1.0.0
+python-magic==0.4.27
+python-multipart==0.0.20
+python-slugify==8.0.4
+pytz==2025.2
+pywin32==311
+PyYAML==6.0.2
+RapidFuzz==3.13.0
+referencing==0.36.2
+regex==2024.11.6
+requests==2.32.4
+requests-toolbelt==1.0.0
+rich==14.1.0
+rpds-py==0.26.0
+ruff==0.12.5
+safetensors==0.5.3
+salesforce-lavis==1.0.2
+scikit-image==0.25.2
+scikit-learn==1.2.2
+scipy==1.15.3
+semantic-version==2.10.0
+sentence-transformers==5.0.0
+sentencepiece==0.1.99
+serpapi==0.1.5
+shapely==2.1.1
+shellingham==1.5.4
+shortuuid==1.0.13
+six==1.17.0
+smart_open==7.3.0.post1
+smmap==5.0.2
+sniffio==1.3.1
+soupsieve==2.7
+spacy==3.8.7
+spacy-legacy==3.0.12
+spacy-loggers==1.0.5
+srsly==2.5.1
+stack-data==0.6.3
+starlette==0.47.2
+streamlit==1.47.1
+svgwrite==1.4.3
+sympy==1.14.0
+tabulate==0.9.0
+tenacity==9.1.2
+text-unidecode==1.3
+thinc==8.3.6
+threadpoolctl==3.6.0
+tifffile==2025.5.10
+timm==0.6.12
+tokenizers==0.21.4
+toml==0.10.2
+tomlkit==0.12.0
+torch==2.1.2
+torchvision==0.16.2
+tornado==6.5.1
+tqdm==4.67.1
+traitlets==5.14.3
+transformers==4.54.0
+typer==0.16.0
+typing-inspection==0.4.1
+typing_extensions==4.14.1
+tzdata==2025.2
+tzlocal==5.3.1
+urllib3==2.5.0
+uvicorn==0.35.0
+validators==0.35.0
+virtualenv==20.32.0
+wasabi==1.1.3
+watchdog==6.0.0
+wavedrom==2.0.3.post3
+wcwidth==0.2.13
+weasel==0.4.1
+webdataset==1.0.2
+webencodings==0.5.1
+websockets==11.0.3
+Werkzeug==3.1.3
+wrapt==1.17.2
+zstandard==0.23.0

+ 77 - 0
scripts/deploy-vps.sh

@@ -0,0 +1,77 @@
+#!/bin/bash
+
+echo "🚀 Assistant AI - Déploiement VPS"
+echo "=================================="
+
+# Variables configurables
+VPS_HOST=${1:-"your-vps-ip"}
+VPS_USER=${2:-"root"}
+SSH_KEY=${3:-"~/.ssh/id_rsa"}
+
+if [ "$VPS_HOST" = "your-vps-ip" ]; then
+    echo "❌ Usage: $0 <vps-ip> [user] [ssh-key]"
+    echo "   Exemple: $0 192.168.1.100 root ~/.ssh/id_rsa"
+    exit 1
+fi
+
+echo "📡 Connexion au VPS: $VPS_USER@$VPS_HOST"
+
+# Vérifier la connexion SSH
+if ! ssh -o ConnectTimeout=10 -i "$SSH_KEY" "$VPS_USER@$VPS_HOST" "echo 'Connexion SSH OK'" 2>/dev/null; then
+    echo "❌ Impossible de se connecter au VPS"
+    exit 1
+fi
+
+echo "✅ Connexion SSH établie"
+
+# Installer Docker sur le VPS
+echo "🔧 Installation de Docker sur le VPS..."
+ssh -i "$SSH_KEY" "$VPS_USER@$VPS_HOST" << 'EOF'
+    if ! command -v docker &> /dev/null; then
+        curl -fsSL https://get.docker.com -o get-docker.sh
+        sh get-docker.sh
+        sudo usermod -aG docker $USER
+        echo "✅ Docker installé"
+    else
+        echo "✅ Docker déjà installé"
+    fi
+
+    if ! command -v docker-compose &> /dev/null; then
+        sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
+        sudo chmod +x /usr/local/bin/docker-compose
+        echo "✅ Docker Compose installé"
+    else
+        echo "✅ Docker Compose déjà installé"
+    fi
+EOF
+
+# Créer le dossier de déploiement
+echo "📁 Création du dossier de déploiement..."
+ssh -i "$SSH_KEY" "$VPS_USER@$VPS_HOST" "mkdir -p ~/assistant-ai"
+
+# Copier les fichiers
+echo "📤 Copie des fichiers..."
+scp -i "$SSH_KEY" -r . "$VPS_USER@$VPS_HOST:~/assistant-ai/"
+
+# Configurer les variables d'environnement
+echo "⚙️  Configuration des variables d'environnement..."
+ssh -i "$SSH_KEY" "$VPS_USER@$VPS_HOST" << 'EOF'
+    cd ~/assistant-ai
+    if [ ! -f .env ]; then
+        cp env.example .env
+        echo "⚠️  Veuillez configurer le fichier .env sur le VPS"
+        echo "   nano .env"
+    fi
+EOF
+
+# Démarrer les services
+echo "🚀 Démarrage des services..."
+ssh -i "$SSH_KEY" "$VPS_USER@$VPS_HOST" << 'EOF'
+    cd ~/assistant-ai
+    docker-compose build
+    docker-compose up -d
+EOF
+
+echo "✅ Déploiement terminé!"
+echo "🌐 Application accessible sur: http://$VPS_HOST:5000"
+echo "📝 Logs: ssh $VPS_USER@$VPS_HOST 'cd ~/assistant-ai && docker-compose logs -f'" 

+ 42 - 0
scripts/setup.sh

@@ -0,0 +1,42 @@
+#!/bin/bash
+
+echo "🚀 Assistant AI - Instructions de déploiement"
+echo "=============================================="
+echo ""
+echo "Ce script affiche les instructions pour déployer l'application."
+echo "Exécutez les commandes manuellement selon vos besoins."
+echo ""
+
+echo "📋 Étapes de déploiement :"
+echo ""
+
+echo "1. Vérifier Docker :"
+echo "   docker --version"
+echo "   docker-compose --version"
+echo ""
+
+echo "2. Configurer les variables d'environnement :"
+echo "   cp env.example .env"
+echo "   # Éditer .env avec vos vraies valeurs"
+echo ""
+
+echo "3. Créer les dossiers nécessaires :"
+echo "   mkdir -p uploads data"
+echo ""
+
+echo "4. Construire et démarrer les conteneurs :"
+echo "   docker-compose build"
+echo "   docker-compose up -d"
+echo ""
+
+echo "5. Vérifier le statut :"
+echo "   docker-compose ps"
+echo ""
+
+echo "6. Voir les logs :"
+echo "   docker-compose logs -f"
+echo ""
+
+echo "✅ Application accessible sur : http://localhost:5000"
+echo ""
+echo "📝 Pour plus de détails, consultez SETUP_MANUAL.md" 

+ 4 - 0
src/__init__.py

@@ -0,0 +1,4 @@
+# Package src pour l'application Assistant AI
+from .app import app
+
+__all__ = ['app'] 

+ 43 - 0
src/agent_ai/auth.py

@@ -0,0 +1,43 @@
+"""
+auth.py 
+
+Gestion de l’authentification sur le wiki Intersel
+
+Ce module permet de se connecter au wiki en utilisant une session HTTP persistante et il récupère tout seul un code spécial (le token CSRF) nécessaire pour se connecter en toute sécurité
+"""
+
+import requests
+from bs4 import BeautifulSoup
+
+session = requests.Session()
+
+def login_to_wiki(username, password):
+    login_url = "https://wiki.intersel.fr/doku.php?id=start&do=login"
+    resp = session.get(login_url)
+    soup = BeautifulSoup(resp.text, "html.parser")
+    sectok_input = soup.find("input", {"name": "sectok"})
+
+    if not sectok_input:
+        print("❌ Impossible de trouver le token CSRF.")
+        return False
+
+    login_data = {
+        "u": username,
+        "p": password,
+        "do": "login",
+        "sectok": sectok_input.get("value")
+    }
+
+    headers = {
+        "User-Agent": "Mozilla/5.0",
+        "Referer": login_url
+    }
+
+    login_resp = session.post(login_url, data=login_data, headers=headers)
+
+    if "logout" in login_resp.text.lower():
+        print("✅ Connexion réussie.")
+        return True
+    else:
+        print("❌ Échec de la connexion.")
+        return False

+ 65 - 0
src/agent_ai/chunking.py

@@ -0,0 +1,65 @@
+import nltk
+from sklearn.metrics.pairwise import cosine_similarity
+from sentence_transformers import SentenceTransformer
+import numpy as np
+import re
+from typing import List
+
+nltk.download('punkt')
+model = SentenceTransformer('all-MiniLM-L6-v2')
+
+MIN_WORDS_PER_CHUNK = 10
+
+def semantic_chunking(sentences, similarity_threshold=0.8, max_words_per_chunk=200):
+    #initialisation des listes
+    chunks = []
+    current_chunk = []
+    current_embeddings = []
+
+    # encoder toutes les phrases en vecteurs avec le modèle SentenceTransformer
+    sentence_embeddings = model.encode(sentences)
+
+    # parcourir chaque phrase et son embedding associé
+    for i, (sentence, embedding) in enumerate(zip(sentences, sentence_embeddings)):
+        sentence = sentence.strip() 
+        if not sentence:
+            continue  # ignorer les phrases vides
+
+        word_count = len(sentence.split())
+
+        # Cas de phrase courte qui pourrait être un titre ("Gérant", "Responsable", etc.)
+        if word_count <= 3 and i > 0:
+            # Ajoute à la phrase précédente (cas comme "Gérante")
+            current_chunk.append(sentence)
+            current_embeddings.append(embedding)
+            continue
+
+        # Si le chunk actuel est vide, on l'initialise avec la phrase actuelle
+        if not current_embeddings:
+            current_chunk.append(sentence)
+            current_embeddings.append(embedding)
+        else:
+            # calculer la similarité entre la phrase courante et le chunk en cours (moyenne des embeddings)
+            mean_embedding = np.mean(current_embeddings, axis=0)
+            sim = cosine_similarity([embedding], [mean_embedding])[0][0]
+
+            if sim > similarity_threshold and len(" ".join(current_chunk).split()) < max_words_per_chunk:
+                current_chunk.append(sentence)
+                current_embeddings.append(embedding)
+            else:
+                chunk_text = " ".join(current_chunk)
+                if len(chunk_text.split()) >= MIN_WORDS_PER_CHUNK:
+                    chunks.append(chunk_text)
+                current_chunk = [sentence]
+                current_embeddings = [embedding]
+
+    if current_chunk:
+         # Sinon on ferme le chunk en cours
+        chunk_text = " ".join(current_chunk)
+        if len(chunk_text.split()) >= MIN_WORDS_PER_CHUNK:
+            chunks.append(chunk_text)
+
+    if not chunks:
+        print("⚠️ Aucun chunk généré. Vérifie la structure ou le contenu des phrases.")
+
+    return chunks

+ 32 - 0
src/agent_ai/embedding_index.py

@@ -0,0 +1,32 @@
+import numpy as np
+import faiss
+import json
+
+"""
+Construire un index FAISS à partir d'une matrice d'embeddings pour pouvoir faire des recherches rapides par similarité
+"""
+
+def build_faiss_index(embeddings):
+    try:
+        dimension = embeddings.shape[1]
+        index = faiss.IndexFlatL2(dimension)
+        index.add(embeddings)
+        return index
+    except Exception as e:
+        print("Erreur lors de la création de l'index FAISS :", e)
+        raise
+
+
+"""
+Trouver les top_k vecteurs les plus similaires à un vecteur de requête en utilisant la similarité cosinus
+"""
+def search_faiss(index, query_embeddings, top_k=10):
+    query_embeddings = np.asarray(query_embeddings)
+
+    # Assurer la bonne forme
+    if query_embeddings.ndim == 1:
+        query_embeddings = np.expand_dims(query_embeddings, axis=0)
+
+    faiss.normalize_L2(query_embeddings)
+    distances, indices = index.search(query_embeddings, top_k)
+    return distances, indices  

+ 32 - 0
src/agent_ai/qa_chain.py

@@ -0,0 +1,32 @@
+from langchain_ollama import OllamaLLM
+from langchain.prompts import PromptTemplate
+from langchain.chains import LLMChain
+
+prompt_template = PromptTemplate(
+    input_variables=["context", "question"],
+  template="""
+Tu es un assistant francophone très rigoureux. Tu ne dois **répondre qu’à partir du contexte fourni** ci-dessous.
+
+Contexte :
+{context}
+
+Question :
+{question}
+
+Si la réponse ne peut pas être déduite **mot pour mot** du contexte, dis : "Je ne sais pas."
+
+Réponse :
+"""
+
+
+)
+
+
+def get_qa_chain():
+    llm = OllamaLLM(
+        model="llama3",
+        temperature=0.7,
+        top_p=0.9,
+        max_tokens=256
+    )
+    return LLMChain(llm=llm, prompt=prompt_template)

+ 183 - 0
src/agent_ai/scraping.py

@@ -0,0 +1,183 @@
+from bs4 import BeautifulSoup
+from agent_ai.auth import session
+from urllib.parse import urljoin, urlparse
+import time
+import hashlib
+import json
+import random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+import os
+
+BASE_URL = "https://wiki.intersel.fr/"
+VISITED = set()
+
+USER_AGENTS = [
+    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
+]
+
+def random_headers():
+    return {
+        "User-Agent": random.choice(USER_AGENTS)
+    }
+
+def hash_text(text):
+    return hashlib.md5(text.encode("utf-8")).hexdigest()
+
+def fetch_single_page(url, old_hashes):
+    try:
+        headers = random_headers()
+        edit_url = url + "&do=edit" if "?" in url else url + "?do=edit"
+        response = session.get(edit_url, headers=headers, timeout=10)
+
+        if response.status_code != 200:
+            return url, None, None
+
+        # 🔥 Forcer l'encodage UTF-8 pour éviter les caractères bizarres
+        response.encoding = 'utf-8'
+
+        if "text/html" not in response.headers.get("Content-Type", ""):
+            return url, None, None
+
+        soup = BeautifulSoup(response.text, "html.parser")
+        textarea = soup.find("textarea", {"name": "wikitext"})
+
+        if textarea:
+            raw_text = textarea.get_text(separator="\n").strip()
+            current_hash = hash_text(raw_text)
+
+            if old_hashes.get(url) != current_hash:
+                print(f"🆕 Modifiée : {url}")
+                return url, raw_text, current_hash
+            else:
+                print(f"✅ Inchangée : {url}")
+        else:
+            print(f"⚠️ Pas de <textarea> pour {url}")
+    except Exception as e:
+        print(f"❌ Erreur pour {url}: {e}")
+
+    # 💡 Petite pause aléatoire
+    time.sleep(random.uniform(0.5, 2))
+    return url, None, None
+
+
+def fetch_all_pages_content(urls, old_hashes):
+    url_texts = {}
+    new_hashes = {}
+
+    with ThreadPoolExecutor(max_workers=5) as executor:
+        futures = [executor.submit(fetch_single_page, url, old_hashes) for url in urls]
+
+        for future in as_completed(futures):
+            url, text, current_hash = future.result()
+            if text:
+                url_texts[url] = text
+                new_hashes[url] = current_hash
+            elif current_hash:
+                new_hashes[url] = current_hash
+
+    return url_texts, new_hashes
+
+def is_valid_wiki_url(url):
+    parsed = urlparse(url)
+    return (
+        parsed.netloc == "wiki.intersel.fr"
+        and "do=" not in parsed.query
+        and not url.endswith((".jpg", ".png", ".pdf", ".docx", ".xlsx"))
+        and "#" not in url
+    )
+
+def crawl_wiki(start_url, existing_urls, max_pages=500):
+    visited = set(existing_urls)
+    to_visit = [start_url]
+
+    while to_visit and len(visited) < max_pages:
+        current_url = to_visit.pop(0)
+        if current_url in visited:
+            continue
+
+        print(f"🔎 Visiting: {current_url}")
+        visited.add(current_url)
+
+        try:
+            headers = random_headers()
+            response = session.get(current_url, headers=headers, timeout=10)
+            if response.status_code != 200:
+                continue
+
+            soup = BeautifulSoup(response.text, "html.parser")
+
+            for link in soup.find_all("a", href=True):
+                absolute_url = urljoin(current_url, link["href"])
+                if is_valid_wiki_url(absolute_url) and absolute_url not in visited and absolute_url not in to_visit:
+                    to_visit.append(absolute_url)
+
+            time.sleep(random.uniform(1, 2))
+        except Exception as e:
+            print(f"❌ Error with {current_url}: {e}")
+
+    return list(visited)
+
+def scrape_pages():
+    start_url = "https://wiki.intersel.fr/"
+    urls_path = os.path.join("data", "urls.json")
+    raw_pages_path = "data/raw_pages.json"
+    hashes_path = "data/page_hashes.json"
+
+    # Charger anciens hashs
+    try:
+        with open(hashes_path, "r", encoding="utf-8") as f:
+            old_hashes = json.load(f)
+    except FileNotFoundError:
+        old_hashes = {}
+
+    # Charger anciennes URLs
+    try:
+        with open(urls_path, "r", encoding="utf-8") as f:
+            urls = json.load(f)
+        print("✅ URLs chargées depuis urls.json")
+    except FileNotFoundError:
+        print("🚀 Crawling initial du wiki")
+        urls = []
+
+    # Nouveau crawl
+    crawled_urls = crawl_wiki(start_url, urls, max_pages=500)
+    all_urls = sorted(set(urls + crawled_urls))
+
+    print(f"🌐 Total URLs à vérifier : {len(all_urls)}")
+
+    # Scraping des pages
+    pages, new_hashes = fetch_all_pages_content(all_urls, old_hashes)
+
+    # Charger anciens raw_pages
+    try:
+        with open(raw_pages_path, "r", encoding="utf-8") as f:
+            old_raw_pages = {p["url"]: p["text"] for p in json.load(f)}
+    except FileNotFoundError:
+        old_raw_pages = {}
+
+    # Mettre à jour uniquement les pages modifiées
+    for url, text in pages.items():
+        old_raw_pages[url] = text
+
+    # Enlever les URLs qui n’existent plus (optionnel)
+    cleaned_raw_pages = {url: text for url, text in old_raw_pages.items() if url in all_urls}
+
+    # Sauvegarder le nouveau contenu
+    with open(raw_pages_path, "w", encoding="utf-8") as f:
+        json.dump(
+            [{"url": url, "text": text} for url, text in cleaned_raw_pages.items()],
+            f, ensure_ascii=False, indent=2
+        )
+
+    with open(hashes_path, "w", encoding="utf-8") as f:
+        json.dump(new_hashes, f, ensure_ascii=False, indent=2)
+
+    with open(urls_path, "w", encoding="utf-8") as f:
+        json.dump(all_urls, f, ensure_ascii=False, indent=2)
+
+    print("📄 Pages modifiées sauvegardées")
+    print("📄 Contenu brut mis à jour enregistré dans 'raw_pages.json'")
+    print("🔗 URLs enregistrées dans 'data/urls.json'")
+    print("🔐 Hashes des pages enregistrés dans 'page_hashes.json'")
+
+    return [{"url": url, "text": text} for url, text in cleaned_raw_pages.items()]

+ 1 - 0
src/api/__init__.py

@@ -0,0 +1 @@
+# API routes pour l'application 

+ 404 - 0
src/app.py

@@ -0,0 +1,404 @@
+from flask import Flask, request, jsonify, send_from_directory
+from apscheduler.schedulers.background import BackgroundScheduler
+from sentence_transformers import CrossEncoder, SentenceTransformer
+from langchain_ollama import OllamaLLM
+from .utils.processing import full_update_pipeline, load_index_from_disk
+from .agent_ai.auth import login_to_wiki
+import faiss 
+import json
+import numpy as np
+import textwrap
+from sklearn.metrics.pairwise import cosine_similarity
+from tabulate import tabulate
+import os
+import threading
+from serpapi import GoogleSearch
+from werkzeug.utils import secure_filename
+import PyPDF2
+from PIL import Image
+from transformers import AutoTokenizer
+from .utils.ocr import run_ocr, generate_html , generate_word_level_html  
+import tiktoken
+from .models.VLM import ask_blip
+
+app = Flask(__name__)
+
+# Configuration pour la production
+app.config['MAX_CONTENT_LENGTH'] = int(os.environ.get('MAX_CONTENT_LENGTH', 16 * 1024 * 1024))  # 16MB par défaut
+
+state = {
+    "index": None,
+    "all_chunks": [],
+    "chunk_urls": [],
+    "all_embeddings": None,
+    "embedding_model": SentenceTransformer('all-MiniLM-L6-v2'),
+    "cross_encoder": CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2"),
+    "is_updating": False,
+    "llm": OllamaLLM(
+        model="llama3", 
+        temperature=0.3, 
+        top_p=0.9, 
+        max_tokens=600,
+        base_url=os.environ.get('OLLAMA_HOST', 'http://localhost:11434')
+    ),
+    "chat_history": []
+   
+}
+
+tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
+
+def chunk_text(text, chunk_size=400, overlap=100):
+    tokens = tokenizer.encode(text)
+    chunks = []
+    for i in range(0, len(tokens), chunk_size - overlap):
+        chunk = tokens[i:i + chunk_size]
+        chunks.append(tokenizer.decode(chunk))
+    return chunks
+
+
+UPLOAD_FOLDER = os.environ.get("UPLOAD_FOLDER", "uploads")
+os.makedirs(UPLOAD_FOLDER, exist_ok=True)  # Crée le dossier s'il n'existe pas
+app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
+
+ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
+
+def allowed_file(filename):
+    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
+
+@app.route("/upload_file", methods=["POST"])
+def upload_file():
+    if 'file' not in request.files:
+        return jsonify({"error": "Aucun fichier détecté."}), 400
+
+    file = request.files['file']
+    if file.filename == '':
+        return jsonify({"error": "Nom de fichier vide."}), 400
+
+    if file and allowed_file(file.filename):
+        filename = secure_filename(file.filename)
+        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+        file.save(filepath)
+
+        question = request.form.get("question", "")
+        if not question:
+            return jsonify({"error": "Veuillez poser une question liée au fichier."}), 400
+
+        try:
+            # ✅ 1. Exécuter l'OCR
+            document, ocr_output = run_ocr(filepath)
+
+            # ✅ 2. Sauvegarder le JSON OCR
+            json_path = os.path.join(app.config['UPLOAD_FOLDER'], "ocr_output.json")
+            with open(json_path, "w", encoding="utf-8") as fjson:
+                json.dump(ocr_output, fjson, ensure_ascii=False, indent=2)
+
+            # ✅ 3. Générer le HTML avec bounding boxes par mot
+            html_path = os.path.join(app.config['UPLOAD_FOLDER'], "ocr_output_words.html")
+            generate_word_level_html(ocr_output, output_html_path=html_path)
+
+            # ✅ 4. Extraire le texte brut pour le traitement RAG
+            text = ""
+            for page in ocr_output['pages']:
+                for block in page['blocks']:
+                    for line in block['lines']:
+                        for word in line['words']:
+                            text += word['value'] + " "
+                        text += "\n"
+                    text += "\n"
+                text += "\n"
+
+        except Exception as e:
+            return jsonify({"error": f"OCR échoué : {str(e)}"}), 500
+
+        if text.strip():
+            chunks = chunk_text(text)
+            embeddings = state["embedding_model"].encode(chunks)
+            question_embedding = state["embedding_model"].encode([question])[0]
+            similarities = cosine_similarity([question_embedding], embeddings)[0]
+            top_indices = np.argsort(similarities)[::-1][:5]
+            top_chunks = [chunks[i] for i in top_indices]
+            top_context = "\n\n".join(top_chunks)
+
+            prompt = (
+                "Réponds en français à la question suivante en utilisant uniquement le contenu fourni. "
+                "Si la réponse est absente, dis-le clairement.\n\n"
+                f"{top_context}\n\nQuestion : {question}"
+            )
+
+            answer = state["llm"](prompt).strip()
+            return jsonify({
+                "answer": answer,
+                "html_file": f"uploads/ocr_output_words.html"
+            })
+
+        else:
+            try:
+                answer = ask_blip(filepath, question)
+                return jsonify({"answer": answer})
+            except Exception as e:
+                return jsonify({"error": f"LLaVA échoué : {str(e)}"}), 500
+
+    return jsonify({"error": "Format de fichier non supporté."}), 400
+
+@app.route("/delete_file", methods=["POST"])
+def delete_file():
+    data = request.get_json()
+    filename = data.get("filename")
+
+    if not filename:
+        return jsonify({"error": "Nom de fichier manquant."}), 400
+
+    filepath = os.path.join(app.config["UPLOAD_FOLDER"], secure_filename(filename))
+
+    if os.path.exists(filepath):
+        os.remove(filepath)
+        return jsonify({"message": "Fichier supprimé avec succès."})
+    else:
+        return jsonify({"error": "Fichier introuvable."}), 404
+
+def load_or_update_index():
+    print("🚀 App starting up...")
+    index, texts, urls = load_index_from_disk()
+    if index:
+        state["index"] = index
+        state["all_chunks"] = texts
+        state["chunk_urls"] = urls
+        print("✅ Index loaded from disk.")
+    else:
+        print("❌ No index found. Launching full update in background...")
+        threading.Thread(target=run_full_update, daemon=True).start()
+
+def run_full_update():
+    state["is_updating"] = True
+    try:
+        index, texts, urls = full_update_pipeline()
+        if index:
+            state["index"] = index
+            state["all_chunks"] = texts
+            state["chunk_urls"] = urls
+            state["all_embeddings"] = state["embedding_model"].encode(texts)
+            print("✅ Background update finished.")
+    except Exception as e:
+        print(f"❌ Failed to update index: {e}")
+    finally:
+        state["is_updating"] = False
+
+@app.route('/')
+def index():
+    return send_from_directory('templates', 'index.html')
+
+@app.route("/login", methods=["POST"])
+def login():
+    data = request.json
+    username = data.get("username")
+    password = data.get("password")
+
+    if not username or not password:
+        return jsonify({"error": "username and password required"}), 400
+
+    if not login_to_wiki(username, password):
+        return jsonify({"error": "Authentication failed"}), 401
+
+    return jsonify({"message": "Login successful"})
+
+@app.route("/chat_history", methods=["GET"])
+def chat_history():
+    return jsonify(state["chat_history"])
+
+@app.route("/qa_chain", methods=["POST"])
+def qa_chain_route():
+    if state.get("llm") is None:
+        return jsonify({"error": "Le modèle LLM n'est pas initialisé."}), 500
+
+    if state["index"] is None or not state["all_chunks"]:
+        if state["is_updating"]:
+            return jsonify({"error": "Le système est encore en train d’indexer les documents. Réessayez dans quelques instants."}), 503
+        else:
+            return jsonify({"error": "L’index est vide. Veuillez attendre la mise à jour ou réinitialiser le système."}), 500
+
+    data = request.get_json()
+    question = data.get("question", "")
+
+    if not question:
+        return jsonify({"error": "Question vide."}), 400
+
+    #  ÉTAPE 1 : Tentative de réponse avec le Wiki local 
+    try:
+        query_embedding = state["embedding_model"].encode([question])[0]
+
+        if state["all_embeddings"] is None:
+            state["all_embeddings"] = state["embedding_model"].encode(state["all_chunks"])
+
+        similarities = cosine_similarity([query_embedding], state["all_embeddings"])[0]
+        top_indices = np.argsort(similarities)[::-1][:1500]
+
+        rerank_data = [(question, state["all_chunks"][i]) for i in top_indices]
+        rerank_scores = state["cross_encoder"].predict(rerank_data)
+        reranked = sorted(
+            zip([state["all_chunks"][i] for i in top_indices], top_indices, rerank_scores),
+            key=lambda x: x[2], reverse=True
+        )
+    
+
+        #  Sauvegarde du contexte dans un fichier de cache 
+        enc = tiktoken.encoding_for_model("gpt-3.5-turbo")
+        cache_data = []
+
+        for rank, (chunk, idx, score) in enumerate(reranked[:1500], start=1): 
+            url = state["chunk_urls"][idx] if idx < len(state["chunk_urls"]) else "URL inconnue"
+            token_count = len(enc.encode(chunk))
+
+            cache_data.append({
+                "rank": rank,
+                "url": url,
+                "chunk": chunk,
+                "tokens": token_count
+            })
+
+        with open("cache_context.json", "w", encoding="utf-8") as f:
+            json.dump(cache_data, f, indent=2, ensure_ascii=False)
+
+
+       #  Affichage en terminal
+        table = []
+        top_chunks = []
+        for rank, (chunk, idx, score) in enumerate(reranked, start=1):
+            url = state["chunk_urls"][idx] if idx < len(state["chunk_urls"]) else "URL inconnue"
+            wrapped_chunk = "\n".join(textwrap.wrap(chunk.strip(), width=80))[:1000] + "..."
+            wrapped_url = "\n".join(textwrap.wrap(url, width=80))
+            table.append([rank, round(score, 4), wrapped_chunk, wrapped_url])
+            top_chunks.append(chunk)
+
+        print("\n================== RÉSULTATS CLASSÉS PAR PERTINENCE ==================")
+        print(tabulate(table, headers=["Rank", "Score", "Chunk", "URL"], tablefmt="fancy_grid"))
+        print("=======================================================================\n")
+
+        max_chars = 15000
+        top_chunks = []
+        current_length = 0
+        for chunk, _, _ in reranked:
+            if current_length + len(chunk) > max_chars:
+                break
+            top_chunks.append(chunk)
+            current_length += len(chunk)
+
+        top_context = "\n\n".join(top_chunks)
+
+
+        prompt = (
+    "Réponds uniquement à la question en utilisant les informations contenues dans le contexte ci-dessous. "
+    "Ta réponse doit être factuelle, concise et précise. "
+    "N’ajoute aucune information extérieure. "
+    "Si la réponse n’est pas présente dans le contexte, dis simplement : 'Information non disponible.'\n\n"
+    f"Contexte :\n{top_context}\n\n"
+    f"Question : {question}"
+)
+
+
+        local_answer = state["llm"](prompt).strip()
+        print("\n====================== PROMPT UTILISÉ ======================")
+        print(f"CONTEXTE :\n{top_context}\nQUESTION :\n{question}\nRÉPONSE :\n{local_answer}")
+        print("============================================================\n")
+
+        # Vérifie si la réponse est valable
+        phrases_non_reponse = [
+    "n'est pas disponible",
+    "je ne sais pas",
+    "je ne trouve pas",
+    "aucune information",
+    "information non disponible",
+    "pas d'information",
+    "je ne suis pas en mesure",
+    "le contexte ne contient pas",
+    "https://localhost:8080"
+        ]
+
+        if local_answer and not any(phrase in local_answer.lower() for phrase in phrases_non_reponse):
+            source_urls = [state["chunk_urls"][idx] for _, idx, _ in reranked[:5]]
+            state["chat_history"].append({
+                "question": question,
+                "answer": local_answer,
+                "sources": list(set(source_urls))
+            })
+            return jsonify({
+                "answer": local_answer,
+                "sources": list(set(source_urls))
+            })
+
+
+    except Exception as e:
+        print(f"[Erreur Wiki] : {e}")
+
+
+    #  ÉTAPE 2 : Fallback vers recherche web (SerpAPI) 
+    try:
+        serpapi_key = os.environ.get('SERPAPI_KEY')
+        if not serpapi_key:
+            return jsonify({"error": "Clé SerpAPI non configurée"}), 500
+            
+        params = {
+            "engine": "google",
+            "q": question,
+            "api_key": serpapi_key,
+            "gl": "fr",
+            "hl": "fr"
+        }
+        search = GoogleSearch(params)
+        results = search.get_dict()
+
+        answer = "Je n'ai pas trouvé de réponse précise."
+        if "answer_box" in results and "answer" in results["answer_box"]:
+            answer = results["answer_box"]["answer"]
+        elif "organic_results" in results and results["organic_results"]:
+            answer = results["organic_results"][0].get("snippet", answer)
+
+        #  Résumer ou filtrer la réponse via le LLM 
+        if state.get("llm"):
+            prompt = (
+    "Réponds uniquement à la question de manière directe et concise.\n"
+    "Sans reformuler la question, sans phrase d'introduction, sans politesse et sans contenu promotionnel. "
+    "Utilise uniquement les faits du texte ci-dessous. "
+    "Si l'information n'est pas présente, réponds : 'Information non disponible.'\n\n"
+    f"Texte : {answer}\n\n"
+    f"Question : {question}"
+)
+
+            try:
+                answer = state["llm"](prompt).strip()
+            except Exception as llm_error:
+                print("[Erreur LLM sur reformulation] :", llm_error)
+
+        # Historique
+        state["chat_history"].append({
+            "question": question,
+            "answer": answer,
+            "sources": ["Google Search"]
+        })
+
+        return jsonify({
+            "answer": answer,
+            "sources": ["Google Search"]
+        })
+
+    except Exception as e:
+        return jsonify({"error": f"Erreur SerpAPI : {str(e)}"}), 500
+
+
+
+# Scheduler
+scheduler = BackgroundScheduler()
+scheduler.add_job(run_full_update, 'interval', minutes=30)
+print("🔁 Scheduler activé pour mises à jour toutes les 30 min")
+
+  
+if __name__ == "__main__":
+    
+    load_or_update_index()
+    scheduler.start()
+    
+    # Configuration pour la production
+    debug_mode = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
+    host = os.environ.get('FLASK_HOST', '0.0.0.0')
+    port = int(os.environ.get('FLASK_PORT', 5000))
+    
+    app.run(debug=debug_mode, host=host, port=port, use_reloader=False)

+ 1 - 0
src/llava

@@ -0,0 +1 @@
+Subproject commit c121f0432da27facab705978f83c4ada465e46fd

+ 24 - 0
src/models/VLM.py

@@ -0,0 +1,24 @@
+from transformers import BlipProcessor, BlipForQuestionAnswering
+import torch
+from PIL import Image
+
+device = "cuda" if torch.cuda.is_available() else "cpu"
+
+# Chargement du modèle BLIP pré-entraîné (VQA)
+processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base", use_fast=True)
+model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(device)
+model.eval()
+
+def ask_blip(image_path, question):
+    image = Image.open(image_path).convert("RGB")
+
+    # Préparer les inputs (image + question)
+    inputs = processor(image, question, return_tensors="pt").to(device)
+
+    # Générer la réponse
+    with torch.no_grad():
+        outputs = model.generate(**inputs)
+        answer = processor.tokenizer.decode(outputs[0], skip_special_tokens=True)
+
+    return answer
+

+ 4 - 0
src/models/__init__.py

@@ -0,0 +1,4 @@
+# Modèles ML pour l'application
+from .VLM import ask_blip
+
+__all__ = ['ask_blip'] 

+ 403 - 0
src/templates/index.html

@@ -0,0 +1,403 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8" />
+  <title>Smart File Chatbot</title>
+  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet" />
+  <style>
+    body {
+      font-family: 'Inter', sans-serif;
+      background-color: #f4f6f8;
+      margin: 0;
+      padding: 2rem;
+      display: flex;
+      justify-content: center;
+      flex-direction: column;
+      align-items: center;
+      min-height: 100vh;
+    }
+    .container {
+      background: white;
+      padding: 2rem;
+      border-radius: 12px;
+      box-shadow: 0 0 10px rgba(0,0,0,0.05);
+      max-width: 600px;
+      width: 100%;
+      /* display none until login */
+      display: none;
+      flex-direction: column;
+    }
+    h2 {
+      margin-top: 0;
+      color: #333;
+    }
+    /* Login popup overlay */
+    #loginPopup {
+      position: fixed;
+      top: 0; left: 0; right: 0; bottom: 0;
+      background: rgba(0,0,0,0.5);
+      display: flex;
+      justify-content: center;
+      align-items: center;
+      z-index: 9999;
+    }
+    #loginForm {
+      background: white;
+      padding: 2rem;
+      border-radius: 12px;
+      width: 320px;
+      box-shadow: 0 0 15px rgba(0,0,0,0.2);
+    }
+    #loginForm h3 {
+      margin-top: 0;
+      margin-bottom: 1rem;
+      text-align: center;
+    }
+    #loginForm input {
+      width: 100%;
+      padding: 0.75rem;
+      margin-bottom: 1rem;
+      border: 1px solid #ccc;
+      border-radius: 6px;
+      font-size: 1rem;
+    }
+    #loginForm button {
+      width: 100%;
+      padding: 0.75rem;
+      background: #0066cc;
+      color: white;
+      border: none;
+      border-radius: 6px;
+      font-size: 1rem;
+      font-weight: 600;
+      cursor: pointer;
+    }
+    #loginForm button:hover {
+      background: #0051a8;
+    }
+    #loginError {
+      color: red;
+      margin-bottom: 1rem;
+      text-align: center;
+    }
+    /* Upload area styles */
+    .upload-area {
+      display: flex;
+      align-items: center;
+      gap: 10px;
+      border: 2px dashed #aaa;
+      padding: 1rem;
+      border-radius: 8px;
+      background-color: #fafafa;
+      cursor: pointer;
+      user-select: none;
+    }
+    .file-info {
+      display: flex;
+      justify-content: space-between;
+      align-items: center;
+      margin-top: 1rem;
+      background: #eef3f7;
+      padding: 0.5rem 1rem;
+      border-radius: 6px;
+    }
+    .remove-btn {
+      background: none;
+      border: 1px solid rgb(191, 221, 220);
+      color: rgb(168, 224, 224);
+      width: 24px;
+      height: 24px;
+      font-size: 1rem;
+      line-height: 1rem;
+      padding: 0;
+      border-radius: 4px;
+      cursor: pointer;
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      transition: background 0.2s;
+    }
+    .remove-btn:hover {
+      background: #cceeff;
+      color: #0066cc;
+      border-color: #0066cc;
+    }
+    input[type="file"] {
+      display: none;
+    }
+    textarea, input[type="text"] {
+      width: 100%;
+      padding: 0.75rem;
+      border: 1px solid #ccc;
+      border-radius: 6px;
+      font-size: 1rem;
+      margin-top: 1rem;
+      box-sizing: border-box;
+    }
+    button {
+      margin-top: 1rem;
+      width: 100%;
+      padding: 0.75rem;
+      background: #0066cc;
+      color: white;
+      border: none;
+      border-radius: 6px;
+      font-size: 1rem;
+      font-weight: 600;
+      cursor: pointer;
+    }
+    button:hover {
+      background: #0051a8;
+    }
+    .answer-box {
+      margin-top: 1.5rem;
+      background: #f0f7ff;
+      padding: 1rem;
+      border-radius: 6px;
+      color: #333;
+      white-space: pre-wrap;
+      min-height: 50px;
+    }
+    .source-box {
+      font-size: 0.9rem;
+      color: #555;
+      margin-top: 0.5rem;
+      min-height: 20px;
+    }
+    #chat-history {
+      white-space: pre-wrap;
+      border: 1px solid #ccc;
+      padding: 10px;
+      max-height: 300px;
+      overflow-y: auto;
+      margin-bottom: 1rem;
+      width: 100%;
+      max-width: 600px;
+      background: white;
+      border-radius: 12px;
+      box-shadow: 0 0 10px rgba(0,0,0,0.05);
+      color: #333;
+    }
+    /* Make questions in chat history appear in blue */
+    #chat-history span.question {
+      color: blue;
+      font-weight: 600;
+      display: block;
+      margin-bottom: 4px;
+    }
+    #chat-history span.answer {
+      color: #333;
+      display: block;
+      margin-bottom: 12px;
+      white-space: pre-wrap;
+    }
+  </style>
+</head>
+<body>
+
+<!-- Login popup -->
+<div id="loginPopup">
+  <form id="loginForm">
+    <h3>Connexion Wiki Intersel</h3>
+    <div id="loginError"></div>
+    <input type="text" id="username" placeholder="Nom d'utilisateur" required />
+    <input type="password" id="password" placeholder="Mot de passe" required />
+    <button type="submit">Se connecter</button>
+  </form>
+</div>
+
+<!-- Chatbot container (hidden until login) -->
+<div class="container" id="chatbotContainer">
+  <h2>📎 Chatbot Documentaire</h2>
+
+  <!-- Historique de chat -->
+  <div id="chat-history"></div>
+
+  <form id="questionForm">
+    <label class="upload-area" for="file">
+      📁 Cliquez ici pour ajouter un fichier
+    </label>
+    <input type="file" id="file" accept=".pdf,.txt,image/*" />
+
+    <div class="file-info" id="filePreview" style="display:none;">
+      <span id="fileName"></span>
+      <button type="button" class="remove-btn" id="clearFileBtn" title="Supprimer le fichier">❌</button>
+    </div>
+
+    <input type="text" id="question" placeholder="Posez votre question…" autocomplete="off" />
+
+    <button type="submit">Envoyer</button>
+  </form>
+
+  <div class="answer-box" id="answer" style="display:none;"></div>
+  <div class="source-box" id="source"></div>
+</div>
+
+<script>
+  // Elements for login
+  const loginPopup = document.getElementById("loginPopup");
+  const loginForm = document.getElementById("loginForm");
+  const loginError = document.getElementById("loginError");
+  const chatbotContainer = document.getElementById("chatbotContainer");
+
+  // Show login popup on page load, hide chatbot until login success
+  window.onload = () => {
+    loginPopup.style.display = "flex";
+    chatbotContainer.style.display = "none";
+  };
+
+  loginForm.addEventListener("submit", async (e) => {
+    e.preventDefault();
+
+    loginError.textContent = ""; // Clear previous errors
+
+    const username = document.getElementById("username").value.trim();
+    const password = document.getElementById("password").value.trim();
+
+    if (!username || !password) {
+      loginError.textContent = "Veuillez remplir tous les champs.";
+      return;
+    }
+
+    try {
+      const response = await fetch("/login", {
+        method: "POST",
+        headers: { "Content-Type": "application/json" },
+        body: JSON.stringify({ username, password }),
+      });
+
+      if (response.ok) {
+        // Login success
+        loginPopup.style.display = "none";
+        chatbotContainer.style.display = "flex";
+        loadChatHistory();
+      } else {
+        const errorData = await response.json();
+        loginError.textContent = errorData.error || "Erreur d'authentification";
+      }
+    } catch (err) {
+      loginError.textContent = "Erreur réseau ou serveur.";
+    }
+  });
+
+  // File upload preview and clear
+  const fileInput = document.getElementById("file");
+  const filePreview = document.getElementById("filePreview");
+  const fileNameDisplay = document.getElementById("fileName");
+
+  fileInput.addEventListener("change", () => {
+    if (fileInput.files.length > 0) {
+      fileNameDisplay.textContent = fileInput.files[0].name;
+      filePreview.style.display = "flex";
+    }
+  });
+
+  document.getElementById("clearFileBtn").onclick = () => {
+    fileInput.value = "";
+    filePreview.style.display = "none";
+  };
+
+  // Handle question submission
+  document.getElementById("questionForm").onsubmit = async (e) => {
+    e.preventDefault();
+
+    const questionInput = document.getElementById("question");
+    const question = questionInput.value.trim();
+    const answerBox = document.getElementById("answer");
+    const sourceBox = document.getElementById("source");
+
+    if (!question) {
+      answerBox.style.display = "block";
+      answerBox.textContent = "❗ Veuillez entrer une question.";
+      sourceBox.textContent = "";
+      return;
+    }
+
+    answerBox.style.display = "block";
+    answerBox.textContent = "⏳ Recherche de la réponse...";
+    sourceBox.textContent = "";
+
+    try {
+      let response;
+
+      if (fileInput.files.length > 0) {
+        const formData = new FormData();
+        formData.append("file", fileInput.files[0]);
+        formData.append("question", question);
+
+        response = await fetch("/upload_file", {
+          method: "POST",
+          body: formData,
+        });
+      } else {
+        response = await fetch("/qa_chain", {
+          method: "POST",
+          headers: {
+            "Content-Type": "application/json",
+          },
+          body: JSON.stringify({ question }),
+        });
+      }
+
+      if (response.ok) {
+        const data = await response.json();
+        answerBox.textContent = data.answer || "Pas de réponse reçue.";
+        if (data.source) {
+          sourceBox.textContent = "Source: " + data.source;
+        } else {
+          sourceBox.textContent = "";
+        }
+        questionInput.value = "";
+        fileInput.value = "";
+        filePreview.style.display = "none";
+        loadChatHistory();
+      } else {
+        answerBox.textContent = "❌ Erreur lors de la récupération de la réponse.";
+        sourceBox.textContent = "";
+      }
+    } catch (error) {
+      answerBox.textContent = "❌ Erreur réseau ou serveur.";
+      sourceBox.textContent = "";
+    }
+  };
+
+  // Chat history display
+  const chatHistoryDiv = document.getElementById("chat-history");
+
+  async function loadChatHistory() {
+  try {
+    const response = await fetch("/chat_history");
+    if (response.ok) {
+      const chatHistory = await response.json();
+      chatHistoryDiv.innerHTML = "";
+      chatHistory.forEach(({ question, answer, sources }) => {
+        const questionSpan = document.createElement("span");
+        questionSpan.className = "question";
+        questionSpan.textContent = "Q: " + question;
+
+        const sourceSpan = document.createElement("span");
+        sourceSpan.style.fontSize = "0.9rem";
+        sourceSpan.style.color = "#777";
+        sourceSpan.textContent = sources && sources.length
+          ? "🔗 Source: " + sources.join(", ")
+          : "🔗 Source: inconnue";
+
+        const answerSpan = document.createElement("span");
+        answerSpan.className = "answer";
+        answerSpan.textContent = "A: " + answer;
+
+        chatHistoryDiv.appendChild(questionSpan);
+        chatHistoryDiv.appendChild(sourceSpan);
+        chatHistoryDiv.appendChild(answerSpan);
+      });
+      chatHistoryDiv.scrollTop = chatHistoryDiv.scrollHeight;
+    }
+  } catch (e) {
+    // silent fail
+  }
+}
+
+</script>
+
+</body>
+</html>

+ 6 - 0
src/utils/__init__.py

@@ -0,0 +1,6 @@
+# Utilitaires pour l'application
+from .ocr import run_ocr, generate_html, generate_word_level_html
+from .processing import full_update_pipeline, load_index_from_disk
+
+__all__ = ['run_ocr', 'generate_html', 'generate_word_level_html', 
+           'full_update_pipeline', 'load_index_from_disk'] 

+ 162 - 0
src/utils/ocr.py

@@ -0,0 +1,162 @@
+import os
+import json
+from doctr.io import DocumentFile
+from doctr.models import ocr_predictor
+
+
+def load_document(file_path: str):
+    ext = os.path.splitext(file_path)[-1].lower()
+    if ext == ".pdf":
+        return DocumentFile.from_pdf(file_path)
+    elif ext in [".png", ".jpg", ".jpeg"]:
+        return DocumentFile.from_images(file_path)
+    else:
+        raise ValueError(f"Type de fichier non supporté: {ext}")
+
+
+def run_ocr(file_path: str):
+    doc = load_document(file_path)
+    model = ocr_predictor(pretrained=True)
+    result = model(doc)
+    output = result.export()
+    return doc, output
+
+
+def generate_html(output, output_html_path="ocr_output.html"):
+    html_head = """
+    <html><head><meta charset="utf-8"><title>Résultat OCR Organisé</title>
+    <style>
+      body { font-family: Arial, sans-serif; background: #f0f0f0; }
+      .page {
+        position: relative;
+        width: 800px; height: 1120px; /* ratio approx A4 */
+        margin: 20px auto;
+        background: white;
+        box-shadow: 0 0 8px rgba(0,0,0,0.2);
+      }
+      .block {
+        position: absolute;
+        border: 1px solid rgba(255,0,0,0.5);
+        background: rgba(255,255,255,0.7);
+        padding: 4px;
+        font-size: 14px;
+        line-height: 1.2em;
+        overflow-wrap: break-word;
+      }
+    </style>
+    </head><body>
+    <h1>Résultat OCR Organisé</h1>
+    """
+
+    html_body = ""
+
+    for page_idx, page in enumerate(output['pages']):
+        html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
+
+        # Pour chaque bloc de texte, positionner la div selon la bounding box normalisée
+        for block in page['blocks']:
+            # bbox format: [[x_min, y_min], [x_max, y_max]] (normé 0-1)
+            (x_min, y_min), (x_max, y_max) = block['geometry']
+            left = x_min * 800  # correspond à width page
+            top = y_min * 1120  # correspond à height page
+            width = (x_max - x_min) * 800
+            height = (y_max - y_min) * 1120
+
+            # Récupérer le texte complet du bloc (concaténation des lignes et mots)
+            block_text = ""
+            for line in block['lines']:
+                line_text = " ".join(word['value'] for word in line['words'])
+                block_text += line_text + "<br>"
+
+            html_body += f'<div class="block" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{block_text}</div>'
+
+        html_body += "</div>"  # fin page div
+
+    html_tail = "</body></html>"
+
+    with open(output_html_path, "w", encoding="utf-8") as f:
+        f.write(html_head + html_body + html_tail)
+
+    print(f"Fichier HTML sauvegardé sous : {output_html_path}")
+
+
+
+
+def extract_text_from_file(file_path: str) -> str:
+    _, output = run_ocr(file_path)
+    text = ""
+
+    for page in output['pages']:
+        for block in page['blocks']:
+            for line in block['lines']:
+                for word in line['words']:
+                    text += word['value'] + " "
+                text += "\n"
+            text += "\n"
+        text += "\n"
+
+    # Sauvegarde du JSON OCR
+    with open("uploads/ocr_output.json", "w", encoding="utf-8") as fjson:
+        json.dump(output, fjson, ensure_ascii=False, indent=2)
+
+    # Génération HTML
+    generate_html(output)
+
+    return text
+ 
+
+
+def generate_word_level_html(output, output_html_path="uploads/ocr_output_words.html"):
+    html_head = """
+    <html><head><meta charset="utf-8"><title>OCR mots avec bounding boxes</title>
+    <style>
+      body { font-family: Arial, sans-serif; background: #f0f0f0; }
+      .page {
+        position: relative;
+        width: 800px; height: 1120px; /* ratio A4 approx */
+        margin: 20px auto;
+        background: white;
+        box-shadow: 0 0 8px rgba(0,0,0,0.2);
+      }
+      .word {
+        position: absolute;
+        border: 1px solid rgba(0, 0, 255, 0.5);
+        background: rgba(255,255,255,0.8);
+        font-size: 12px;
+        line-height: 1em;
+        padding: 1px 2px;
+        white-space: nowrap;
+        overflow: hidden;
+        text-overflow: ellipsis;
+      }
+    </style>
+    </head><body>
+    <h1>OCR mots avec bounding boxes</h1>
+    """
+
+    html_body = ""
+
+    for page_idx, page in enumerate(output['pages']):
+        html_body += f'<div class="page"><h2>Page {page_idx + 1}</h2>'
+
+        for block in page['blocks']:
+            for line in block['lines']:
+                for word in line['words']:
+                    # bbox normalized format: [[x_min, y_min], [x_max, y_max]]
+                    (x_min, y_min), (x_max, y_max) = word['geometry']
+                    left = x_min * 800
+                    top = y_min * 1120
+                    width = (x_max - x_min) * 800
+                    height = (y_max - y_min) * 1120
+
+                    word_text = word['value']
+                    html_body += f'<div class="word" style="left:{left}px; top:{top}px; width:{width}px; height:{height}px;">{word_text}</div>'
+
+        html_body += "</div>"  # fin page
+
+    html_tail = "</body></html>"
+
+    with open(output_html_path, "w", encoding="utf-8") as f:
+        f.write(html_head + html_body + html_tail)
+
+    print(f"Fichier HTML mots sauvegardé sous : {output_html_path}")

+ 150 - 0
src/utils/processing.py

@@ -0,0 +1,150 @@
+import os
+import json
+import faiss
+import numpy as np
+from sentence_transformers import SentenceTransformer
+from agent_ai.chunking import semantic_chunking  
+from agent_ai.scraping import scrape_pages 
+from nltk.tokenize import sent_tokenize
+import re
+import requests
+
+
+CHUNKS_FILE = "data/All_chunks.json"
+INDEX_FILE = "data/faiss_index.index"
+RAW_PAGES_FILE = "data/raw_pages.json"
+URLS_FILE = "data/urls.json"
+
+embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
+
+def clean_text(text):
+    # Supprimer les balises DokuWiki comme ~~ODT~~ ou ~~TOC~~
+    text = re.sub(r"~~.*?~~", " ", text)
+
+    # Supprimer les balises HTML restantes éventuelles
+    text = re.sub(r"<[^>]+>", " ", text)
+
+    # supprimer les caractères non imprimables sauf accentués
+    text = re.sub(r"[^\x00-\x7FÀ-ÿ]+", " ", text)
+
+    # supprimer les espaces multiples
+    text = re.sub(r"\s+", " ", text)
+
+    return text.strip()
+
+
+def update_raw_pages(new_pages_dict):
+    # Charger les anciennes pages
+    old_pages = {}
+    if os.path.exists(RAW_PAGES_FILE):
+        with open(RAW_PAGES_FILE, "r", encoding="utf-8") as f:
+            old_pages = json.load(f)
+
+    # Comparer et détecter les modifications
+    updated = {}
+    for url, new_text in new_pages_dict.items():
+        if url not in old_pages or old_pages[url] != new_text:
+            updated[url] = new_text  # Ajouté ou modifié
+
+    # Supprimer les anciens contenus modifiés
+    for url in updated.keys():
+        old_pages.pop(url, None)
+
+    # Ajouter les nouveaux contenus
+    old_pages.update(updated)
+    with open(RAW_PAGES_FILE, "w", encoding="utf-8") as f:
+        json.dump(old_pages, f, indent=2, ensure_ascii=False)
+
+    # 🔁 Mettre à jour la liste des URLs
+    if os.path.exists(URLS_FILE):
+        with open(URLS_FILE, "r", encoding="utf-8") as f:
+            all_urls = set(json.load(f))
+    else:
+        all_urls = set()
+
+    all_urls.update(new_pages_dict.keys())
+    with open(URLS_FILE, "w", encoding="utf-8") as f:
+        json.dump(list(all_urls), f, indent=2)
+
+    return updated
+
+def update_chunks_for_modified_pages(updated_pages):
+    if os.path.exists(CHUNKS_FILE):
+        with open(CHUNKS_FILE, "r", encoding="utf-8") as f:
+            all_chunks = json.load(f)
+    else:
+        all_chunks = []
+
+    # Remove old chunks for updated URLs
+    updated_urls = set(updated_pages.keys())
+    all_chunks = [c for c in all_chunks if c["url"] not in updated_urls]
+
+    # Add new chunks
+    chunk_index_start = len(all_chunks)
+    new_chunks = []
+    for url, text in updated_pages.items():
+        text = clean_text(text)
+        sentences = sent_tokenize(text)
+        chunks = semantic_chunking(sentences, similarity_threshold=0.8)  
+        for ch in chunks:
+            new_chunks.append({
+                "chunk_id": chunk_index_start + len(new_chunks),
+                "text": ch,
+                "url": url,
+                "word_count": len(ch.split())
+            })
+
+    all_chunks.extend(new_chunks)
+
+    with open(CHUNKS_FILE, "w", encoding="utf-8") as f:
+        json.dump(all_chunks, f, indent=2, ensure_ascii=False)
+
+    return all_chunks
+
+
+def build_and_save_index(chunks):
+    texts = [c["text"] for c in chunks]
+    urls = [c["url"] for c in chunks]
+    embeddings = embedding_model.encode(texts, convert_to_tensor=False)
+    index = faiss.IndexFlatL2(len(embeddings[0]))
+    index.add(np.array(embeddings).astype("float32"))
+
+    # ✅ Save index to disk
+    faiss.write_index(index, INDEX_FILE)
+
+    return index, texts, urls
+
+def full_update_pipeline():
+    print("🔄 Running full update pipeline...")
+
+    pages = scrape_pages() 
+    page_dict = {p["url"]: p["text"] for p in pages}
+    updated = update_raw_pages(page_dict)
+    if updated:
+        all_chunks = update_chunks_for_modified_pages(updated)
+    else:
+        if os.path.exists(CHUNKS_FILE):
+            with open(CHUNKS_FILE, "r", encoding="utf-8") as f:
+                all_chunks = json.load(f)
+        else:
+            print("❌ Aucune donnée pour construire l'index.")
+            return None, None, None
+
+    index, texts, urls = build_and_save_index(all_chunks)
+    print("✅ Index reconstruit (même sans mises à jour).")
+    return index, texts, urls
+
+
+def load_index_from_disk():
+    if not os.path.exists(INDEX_FILE) or not os.path.exists(CHUNKS_FILE):
+        return None, [], []
+
+    index = faiss.read_index(INDEX_FILE)
+    with open(CHUNKS_FILE, "r", encoding="utf-8") as f:
+        chunks = json.load(f)
+    texts = [chunk["text"] for chunk in chunks]
+    urls = [chunk["url"] for chunk in chunks]
+
+    return index, texts, urls
+
+

+ 46 - 0
tests/test_auth.py

@@ -0,0 +1,46 @@
+import pytest #framework de test
+from unittest.mock import patch # mock est une simulation d’un objet réel que l’on utilise pendant les tests
+import sys
+import os
+sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+from agent_ai.auth import login_to_wiki
+
+@patch("agent_ai.auth.session.get") # remplace temporairement session.get / session.post
+@patch("agent_ai.auth.session.post")
+def test_login_success(mock_post, mock_get):
+    # Mock de la réponse GET avec un token CSRF valide
+    mock_get.return_value.text = '''
+        <html><form>
+            <input type="hidden" name="sectok" value="fake_csrf_token">
+        </form></html>
+    '''
+    # Simule la page de login contenant un token CSRF
+    # Mock de la réponse POST avec indication de succès (présence de 'logout')
+    mock_post.return_value.text = "You are now logged in. <a href='logout'>Logout</a>"
+
+    result = login_to_wiki("fakeuser", "fakepass")
+    assert result == True
+
+@patch("agent_ai.auth.session.get")
+@patch("agent_ai.auth.session.post")
+def test_login_failure(mock_post, mock_get):
+    # Mock de la réponse GET avec un token CSRF valide
+    mock_get.return_value.text = '''
+        <html><form>
+            <input type="hidden" name="sectok" value="fake_csrf_token">
+        </form></html>
+    '''
+
+    # Mock de la réponse POST avec échec (pas de 'logout')
+    mock_post.return_value.text = "Invalid login"
+
+    result = login_to_wiki("fakeuser", "wrongpass")
+    assert result == False
+
+@patch("agent_ai.auth.session.get")
+def test_missing_csrf_token(mock_get):
+    # Simule une page sans le champ CSRF
+    mock_get.return_value.text = "<html><form></form></html>"
+
+    result = login_to_wiki("fakeuser", "fakepass")
+    assert result == False

+ 47 - 0
tests/test_chunking.py

@@ -0,0 +1,47 @@
+from agent_ai.chunking import semantic_chunking  
+import pytest
+
+def test_similar_sentences_grouped():
+    sentences = [
+        "L'intelligence artificielle est en plein essor.",
+        "L'IA transforme de nombreux secteurs.",
+        "Les modèles de langage sont au cœur de cette révolution."
+    ]
+    chunks = semantic_chunking(sentences, similarity_threshold=0.2)
+    assert len(chunks) == 1  # Toutes les phrases sont similaires → 1 chunk
+
+def test_dissimilar_sentences_separated():
+    sentences = [
+        "Paris est la capitale de la France.",
+        "Le moteur de voiture est tombé en panne.",
+        "Python est un langage de programmation populaire.",
+        "La météo aujourd'hui est très ensoleillée avec peu de vent.",
+        "Les baleines migrent chaque année vers des eaux plus chaudes.",
+        "La cuisson du pain nécessite de la patience et une bonne température.",
+        "Le football est l’un des sports les plus pratiqués dans le monde.",
+        "La musique classique a une influence apaisante sur le cerveau.",
+        "Les ordinateurs quantiques représentent l’avenir de la technologie.",
+        "L’astronomie permet d’explorer les mystères de l’univers."
+        ]
+    chunks = semantic_chunking(sentences, similarity_threshold=0.7)
+    assert len(chunks) >= 2  # Elles devraient être séparées
+
+def test_short_sentences_ignored():
+    sentences = [
+        "Ok.",
+        "Bonjour.",
+        "Merci.",
+        "Très bien.",
+        "Ça va."
+    ]
+    chunks = semantic_chunking(sentences)
+    assert len(chunks) == 0  # Trop courtes -> ignorées
+
+def test_min_words_per_chunk_respected():
+    sentences = ["Ceci est une phrase pertinente."] * 20  # Répétition pour atteindre 20+ mots
+    chunks = semantic_chunking(sentences)
+    assert all(len(c.split()) >= 20 for c in chunks)
+
+def test_empty_input():
+    chunks = semantic_chunking([])
+    assert chunks == []

+ 118 - 0
tests/test_deployment.py

@@ -0,0 +1,118 @@
+import requests
+import time
+import os
+import subprocess
+import json
+
+def test_docker_installation():
+    """Test si Docker est installé"""
+    try:
+        result = subprocess.run(['docker', '--version'], capture_output=True, text=True)
+        return result.returncode == 0
+    except FileNotFoundError:
+        return False
+
+def test_docker_compose_installation():
+    """Test si Docker Compose est installé"""
+    try:
+        result = subprocess.run(['docker-compose', '--version'], capture_output=True, text=True)
+        return result.returncode == 0
+    except FileNotFoundError:
+        return False
+
+def test_environment_variables():
+    """Test si les variables d'environnement sont configurées"""
+    required_vars = ['SERPAPI_KEY', 'WIKI_USERNAME', 'WIKI_PASSWORD']
+    missing_vars = []
+    
+    for var in required_vars:
+        if not os.environ.get(var):
+            missing_vars.append(var)
+    
+    return len(missing_vars) == 0, missing_vars
+
+def test_app_health():
+    """Test si l'application répond"""
+    try:
+        response = requests.get('http://localhost:5000/', timeout=10)
+        return response.status_code == 200
+    except requests.exceptions.RequestException:
+        return False
+
+def test_ollama_health():
+    """Test si Ollama répond"""
+    try:
+        response = requests.get('http://localhost:11434/api/tags', timeout=10)
+        return response.status_code == 200
+    except requests.exceptions.RequestException:
+        return False
+
+def test_file_upload():
+    """Test l'upload de fichier"""
+    try:
+        # Créer un fichier de test
+        with open('test.txt', 'w') as f:
+            f.write('Test content')
+        
+        with open('test.txt', 'rb') as f:
+            files = {'file': f}
+            data = {'question': 'What is this?'}
+            response = requests.post('http://localhost:5000/upload_file', 
+                                  files=files, data=data, timeout=30)
+        
+        os.remove('test.txt')
+        return response.status_code == 200
+    except Exception as e:
+        print(f"Erreur test upload: {e}")
+        return False
+
+def run_all_tests():
+    """Exécuter tous les tests"""
+    print("🧪 Tests de déploiement")
+    print("=" * 30)
+    
+    tests = [
+        ("Docker installé", test_docker_installation),
+        ("Docker Compose installé", test_docker_compose_installation),
+        ("Variables d'environnement", test_environment_variables),
+        ("Application Flask", test_app_health),
+        ("Service Ollama", test_ollama_health),
+        ("Upload de fichier", test_file_upload)
+    ]
+    
+    results = []
+    for test_name, test_func in tests:
+        print(f"🔍 Test: {test_name}")
+        if test_name == "Variables d'environnement":
+            success, missing = test_func()
+            if success:
+                print("✅ Variables d'environnement configurées")
+            else:
+                print(f"❌ Variables manquantes: {missing}")
+            results.append((test_name, success))
+        else:
+            success = test_func()
+            status = "✅" if success else "❌"
+            print(f"{status} {test_name}")
+            results.append((test_name, success))
+        print()
+    
+    # Résumé
+    print("📊 Résumé des tests:")
+    print("=" * 30)
+    passed = sum(1 for _, success in results if success)
+    total = len(results)
+    
+    for test_name, success in results:
+        status = "✅" if success else "❌"
+        print(f"{status} {test_name}")
+    
+    print(f"\n🎯 {passed}/{total} tests réussis")
+    
+    if passed == total:
+        print("🎉 Tous les tests sont passés! Le déploiement est fonctionnel.")
+    else:
+        print("⚠️  Certains tests ont échoué. Vérifiez la configuration.")
+
+if __name__ == "__main__":
+    run_all_tests() 

+ 46 - 0
tests/test_embedding_index.py

@@ -0,0 +1,46 @@
+import numpy as np
+import pytest
+from agent_ai.embedding_index import build_faiss_index, search_faiss
+
+def test_build_and_search_faiss_index():
+    embeddings = np.array([
+        [1.0, 0.0, 0.0, 0.0],
+        [0.9, 0.1, 0.0, 0.0],
+        [0.0, 1.0, 0.0, 0.0],
+        [0.0, 0.9, 0.1, 0.0],
+        [0.0, 0.0, 1.0, 0.0]
+    ], dtype=np.float32)
+
+    # Construire l'index
+    index = build_faiss_index(embeddings)
+
+    # Requête : un vecteur proche du premier
+    query = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
+
+    distances, indices = search_faiss(index, query, top_k=3)
+
+    # Vérifier la forme des résultats
+    assert distances.shape == (1, 3)
+    assert indices.shape == (1, 3)
+
+    # Le vecteur le plus proche doit être lui-même (distance max = 1 après normalisation)
+    assert indices[0, 0] == 0
+    assert np.isclose(distances[0, 0], 0.0, atol=1e-5)
+
+
+    # Les distances doivent être décroissantes (cosine similarity décroissante)
+    assert distances[0, 0] <= distances[0, 1] <= distances[0, 2]
+
+def test_search_batch_queries():
+    embeddings = np.random.rand(10, 8).astype(np.float32)
+    index = build_faiss_index(embeddings)
+
+    queries = np.array([
+        embeddings[0],
+        embeddings[1]
+    ])
+
+    distances, indices = search_faiss(index, queries, top_k=2)
+
+    assert distances.shape == (2, 2)
+    assert indices.shape == (2, 2)

+ 15 - 0
tests/test_qa_chain.py

@@ -0,0 +1,15 @@
+from unittest.mock import patch
+from agent_ai.qa_chain import get_qa_chain
+
+def test_get_qa_chain_mocked():
+    with patch("agent_ai.qa_chain.OllamaLLM.invoke") as mock_invoke:
+        mock_invoke.return_value = {"text": "Paris !"}
+        
+        chain = get_qa_chain()
+
+        output = chain.invoke({
+            "context": "Paris est la capitale de la France.",
+            "question": "Quelle est la capitale de la France ?"
+        })
+
+        assert output["text"] == "Paris."

+ 38 - 0
tests/test_scraping.py

@@ -0,0 +1,38 @@
+from unittest.mock import patch
+from agent_ai.scraping import fetch_all_pages_content
+
+@patch("agent_ai.scraping.session.get")
+def test_fetch_success(mock_get):
+    mock_get.return_value.status_code = 200
+    mock_get.return_value.text = '''
+        <textarea name="wikitext">Sample content</textarea>
+    '''
+
+    urls = ["https://example.com/page"]
+    result = fetch_all_pages_content(urls)
+    assert result[urls[0]] == "Sample content"
+
+@patch("agent_ai.scraping.session.get")
+def test_fetch_no_textarea(mock_get):
+    mock_get.return_value.status_code = 200
+    mock_get.return_value.text = "<html>No textarea</html>"
+
+    urls = ["https://example.com/no-textarea"]
+    result = fetch_all_pages_content(urls)
+    assert urls[0] not in result
+
+@patch("agent_ai.scraping.session.get")
+def test_fetch_error_status(mock_get):
+    mock_get.return_value.status_code = 404
+
+    urls = ["https://example.com/404"]
+    result = fetch_all_pages_content(urls)
+    assert urls[0] not in result
+
+@patch("agent_ai.scraping.session.get")
+def test_fetch_exception(mock_get):
+    mock_get.side_effect = Exception("Network error")
+
+    urls = ["https://example.com/error"]
+    result = fetch_all_pages_content(urls)
+    assert urls[0] not in result

+ 4 - 0
wsgi.py

@@ -0,0 +1,4 @@
+from src.app import app
+
+if __name__ == "__main__":
+    app.run()