init
Browse files- .gitignore +46 -0
- .streamlit/config.toml +15 -0
- DEPLOY.md +296 -0
- Dockerfile +31 -0
- README.md +58 -6
- app.py +253 -0
- app/__init__.py +4 -0
- app/config.py +32 -0
- app/embeddings.py +53 -0
- app/llm_client.py +84 -0
- app/pdf_processor.py +100 -0
- app/qdrant_client.py +175 -0
- deploy.sh +99 -0
- requirements.txt +18 -0
- uploads/.gitkeep +0 -0
.gitignore
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Environment variables
|
| 2 |
+
.env
|
| 3 |
+
.env.local
|
| 4 |
+
|
| 5 |
+
# Python
|
| 6 |
+
__pycache__/
|
| 7 |
+
*.py[cod]
|
| 8 |
+
*$py.class
|
| 9 |
+
*.so
|
| 10 |
+
.Python
|
| 11 |
+
*.egg-info/
|
| 12 |
+
.installed.cfg
|
| 13 |
+
*.egg
|
| 14 |
+
|
| 15 |
+
# Virtual environments
|
| 16 |
+
venv/
|
| 17 |
+
ENV/
|
| 18 |
+
env/
|
| 19 |
+
.venv
|
| 20 |
+
|
| 21 |
+
# IDE
|
| 22 |
+
.vscode/
|
| 23 |
+
.idea/
|
| 24 |
+
*.swp
|
| 25 |
+
*.swo
|
| 26 |
+
*~
|
| 27 |
+
.DS_Store
|
| 28 |
+
|
| 29 |
+
# Jupyter Notebook
|
| 30 |
+
.ipynb_checkpoints
|
| 31 |
+
|
| 32 |
+
# Testing
|
| 33 |
+
.pytest_cache/
|
| 34 |
+
.coverage
|
| 35 |
+
htmlcov/
|
| 36 |
+
|
| 37 |
+
# Logs
|
| 38 |
+
*.log
|
| 39 |
+
|
| 40 |
+
# Uploads (keep .gitkeep)
|
| 41 |
+
uploads/*
|
| 42 |
+
!uploads/.gitkeep
|
| 43 |
+
|
| 44 |
+
# Streamlit secrets
|
| 45 |
+
.streamlit/secrets.toml
|
| 46 |
+
|
.streamlit/config.toml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[theme]
|
| 2 |
+
primaryColor = "#FF6B6B"
|
| 3 |
+
backgroundColor = "#FFFFFF"
|
| 4 |
+
secondaryBackgroundColor = "#F0F2F6"
|
| 5 |
+
textColor = "#262730"
|
| 6 |
+
font = "sans serif"
|
| 7 |
+
|
| 8 |
+
[server]
|
| 9 |
+
headless = true
|
| 10 |
+
port = 7860
|
| 11 |
+
enableCORS = false
|
| 12 |
+
enableXsrfProtection = false
|
| 13 |
+
|
| 14 |
+
[browser]
|
| 15 |
+
gatherUsageStats = false
|
DEPLOY.md
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚀 Déploiement PVGFD sur Hugging Face Spaces
|
| 2 |
+
|
| 3 |
+
Guide rapide pour déployer l'application PVGFD sur HF Spaces avec Docker.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 📋 Prérequis
|
| 8 |
+
|
| 9 |
+
- Compte Hugging Face (https://huggingface.co/join)
|
| 10 |
+
- Token HF avec permissions "Write" (https://huggingface.co/settings/tokens)
|
| 11 |
+
- Cluster Qdrant Cloud (https://cloud.qdrant.io/)
|
| 12 |
+
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## ⚡ Déploiement Rapide (5 minutes)
|
| 16 |
+
|
| 17 |
+
### 1. Créer le Space sur HF
|
| 18 |
+
|
| 19 |
+
1. Allez sur https://huggingface.co/spaces
|
| 20 |
+
2. Cliquez **"Create new Space"**
|
| 21 |
+
3. Configuration :
|
| 22 |
+
```
|
| 23 |
+
Owner: puyol85 (ou votre username)
|
| 24 |
+
Space name: pvgfd
|
| 25 |
+
SDK: Docker
|
| 26 |
+
Hardware: CPU basic (gratuit)
|
| 27 |
+
```
|
| 28 |
+
4. Cliquez **"Create Space"**
|
| 29 |
+
|
| 30 |
+
### 2. Déployer
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
cd /home/koffi/projects/pvgfd
|
| 34 |
+
|
| 35 |
+
# Rendre le script exécutable
|
| 36 |
+
chmod +x deploy.sh
|
| 37 |
+
|
| 38 |
+
# Déployer
|
| 39 |
+
./deploy.sh
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Le script vous demandera :
|
| 43 |
+
- **Username** : puyol85 (ou appuyez sur Entrée)
|
| 44 |
+
- **Token** : Votre token HF
|
| 45 |
+
|
| 46 |
+
### 3. Configurer les Secrets
|
| 47 |
+
|
| 48 |
+
Après le push, allez sur :
|
| 49 |
+
```
|
| 50 |
+
https://huggingface.co/spaces/puyol85/pvgfd/settings
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Cliquez sur **"Variables and secrets"** → **"New secret"**
|
| 54 |
+
|
| 55 |
+
Ajoutez ces secrets :
|
| 56 |
+
|
| 57 |
+
```
|
| 58 |
+
HF_TOKEN = hf_votre_token
|
| 59 |
+
HF_ENDPOINT_URL = https://xxx.us-east-1.aws.endpoints.huggingface.cloud
|
| 60 |
+
HF_EMBEDDING_MODEL = sentence-transformers/all-MiniLM-L6-v2
|
| 61 |
+
QDRANT_URL = xxx.cloud.qdrant.io
|
| 62 |
+
QDRANT_API_KEY = votre_api_key
|
| 63 |
+
QDRANT_COLLECTION = bm_documents
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
## 📁 Structure du Projet
|
| 69 |
+
|
| 70 |
+
```
|
| 71 |
+
pvgfd/
|
| 72 |
+
├── app.py # Application Streamlit principale
|
| 73 |
+
├── app/
|
| 74 |
+
│ ├── config.py # Configuration (lit les secrets)
|
| 75 |
+
│ ├── pdf_processor.py # Traitement PDF
|
| 76 |
+
│ ├── embeddings.py # Génération d'embeddings
|
| 77 |
+
│ ├── qdrant_client.py # Client Qdrant
|
| 78 |
+
│ └── llm_client.py # Client LLM Hugging Face
|
| 79 |
+
├── .streamlit/
|
| 80 |
+
│ └── config.toml # Config Streamlit
|
| 81 |
+
├── uploads/ # Dossier uploads (vide au départ)
|
| 82 |
+
├── Dockerfile # Image Docker pour HF Spaces
|
| 83 |
+
├── requirements.txt # Dépendances Python
|
| 84 |
+
├── README.md # README avec header YAML pour HF
|
| 85 |
+
├── deploy.sh # Script de déploiement
|
| 86 |
+
└── .gitignore # Fichiers à ignorer
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
---
|
| 90 |
+
|
| 91 |
+
## 🐳 Dockerfile Expliqué
|
| 92 |
+
|
| 93 |
+
```dockerfile
|
| 94 |
+
FROM python:3.10-slim
|
| 95 |
+
|
| 96 |
+
# Utilisateur non-root (requis par HF)
|
| 97 |
+
RUN useradd -m -u 1000 user
|
| 98 |
+
USER user
|
| 99 |
+
|
| 100 |
+
# PATH avec bin local
|
| 101 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 102 |
+
|
| 103 |
+
WORKDIR /app
|
| 104 |
+
|
| 105 |
+
# Installation des dépendances
|
| 106 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 107 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 108 |
+
|
| 109 |
+
# Copie du code
|
| 110 |
+
COPY --chown=user . /app
|
| 111 |
+
|
| 112 |
+
# Création du dossier uploads
|
| 113 |
+
RUN mkdir -p /app/uploads
|
| 114 |
+
|
| 115 |
+
# Port HF Spaces
|
| 116 |
+
EXPOSE 7860
|
| 117 |
+
|
| 118 |
+
# Lancement Streamlit
|
| 119 |
+
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
**Points clés :**
|
| 123 |
+
- ✅ Utilisateur non-root (user:1000) - **obligatoire HF**
|
| 124 |
+
- ✅ Port 7860 - **port par défaut HF Spaces**
|
| 125 |
+
- ✅ `--chown=user` pour tous les fichiers
|
| 126 |
+
- ✅ Pas de volumes (tout dans l'image)
|
| 127 |
+
|
| 128 |
+
---
|
| 129 |
+
|
| 130 |
+
## 🔄 Workflow Git
|
| 131 |
+
|
| 132 |
+
### Déploiement Initial
|
| 133 |
+
|
| 134 |
+
```bash
|
| 135 |
+
cd /home/koffi/projects/pvgfd
|
| 136 |
+
|
| 137 |
+
# Initialiser Git
|
| 138 |
+
git init
|
| 139 |
+
git branch -M main
|
| 140 |
+
|
| 141 |
+
# Ajouter le remote HF
|
| 142 |
+
git remote add space https://huggingface.co/spaces/puyol85/pvgfd
|
| 143 |
+
|
| 144 |
+
# Premier commit
|
| 145 |
+
git add .
|
| 146 |
+
git commit -m "Initial commit: PVGFD Q&A app"
|
| 147 |
+
|
| 148 |
+
# Push (avec token)
|
| 149 |
+
git push space main
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
### Mises à Jour
|
| 153 |
+
|
| 154 |
+
```bash
|
| 155 |
+
# Modifier votre code
|
| 156 |
+
nano app.py
|
| 157 |
+
|
| 158 |
+
# Commit et push
|
| 159 |
+
git add .
|
| 160 |
+
git commit -m "Update: nouvelle fonctionnalité"
|
| 161 |
+
git push space main
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
---
|
| 165 |
+
|
| 166 |
+
## 🔐 Gestion du Token
|
| 167 |
+
|
| 168 |
+
### Option 1 : Sauvegarder dans ~/.hf_token
|
| 169 |
+
|
| 170 |
+
```bash
|
| 171 |
+
# Sauvegarder le token
|
| 172 |
+
echo "hf_votre_token" > ~/.hf_token
|
| 173 |
+
chmod 600 ~/.hf_token
|
| 174 |
+
|
| 175 |
+
# Le script le lira automatiquement
|
| 176 |
+
./deploy.sh
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### Option 2 : Token dans l'URL
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
git remote add space https://puyol85:hf_TOKEN@huggingface.co/spaces/puyol85/pvgfd
|
| 183 |
+
git push space main
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
---
|
| 187 |
+
|
| 188 |
+
## ✅ Vérification
|
| 189 |
+
|
| 190 |
+
### 1. Build Logs
|
| 191 |
+
|
| 192 |
+
Allez sur :
|
| 193 |
+
```
|
| 194 |
+
https://huggingface.co/spaces/puyol85/pvgfd
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Cliquez sur **"Logs"** pour voir le build en temps réel.
|
| 198 |
+
|
| 199 |
+
### 2. Test de l'App
|
| 200 |
+
|
| 201 |
+
Une fois le build terminé (2-5 min) :
|
| 202 |
+
1. L'app s'affiche automatiquement
|
| 203 |
+
2. Testez l'upload d'un PDF
|
| 204 |
+
3. Posez une question
|
| 205 |
+
4. Vérifiez la réponse
|
| 206 |
+
|
| 207 |
+
---
|
| 208 |
+
|
| 209 |
+
## 🆘 Dépannage
|
| 210 |
+
|
| 211 |
+
### Build Fail
|
| 212 |
+
|
| 213 |
+
**Symptôme** : Le build échoue
|
| 214 |
+
|
| 215 |
+
**Solutions** :
|
| 216 |
+
1. Vérifiez `requirements.txt` (toutes les dépendances présentes)
|
| 217 |
+
2. Vérifiez le Dockerfile (syntaxe correcte)
|
| 218 |
+
3. Consultez les logs pour l'erreur exacte
|
| 219 |
+
|
| 220 |
+
### App Crash au Démarrage
|
| 221 |
+
|
| 222 |
+
**Symptôme** : L'app démarre mais crash immédiatement
|
| 223 |
+
|
| 224 |
+
**Solutions** :
|
| 225 |
+
1. Vérifiez que tous les secrets sont configurés
|
| 226 |
+
2. Testez la connexion Qdrant
|
| 227 |
+
3. Vérifiez le token HF
|
| 228 |
+
|
| 229 |
+
### Permission Denied
|
| 230 |
+
|
| 231 |
+
**Symptôme** : Erreur de permissions dans les logs
|
| 232 |
+
|
| 233 |
+
**Solution** : Vérifiez que tous les `COPY` dans le Dockerfile ont `--chown=user`
|
| 234 |
+
|
| 235 |
+
---
|
| 236 |
+
|
| 237 |
+
## 📊 Différences avec Docker Compose
|
| 238 |
+
|
| 239 |
+
| Docker Compose (Local) | Docker (HF Spaces) |
|
| 240 |
+
|------------------------|-------------------|
|
| 241 |
+
| ❌ Multi-conteneurs | ✅ Un seul conteneur |
|
| 242 |
+
| ❌ docker-compose.yml | ✅ Dockerfile uniquement |
|
| 243 |
+
| ❌ Services séparés | ✅ Tout dans une image |
|
| 244 |
+
| ❌ Volumes persistants | ✅ Stockage éphémère |
|
| 245 |
+
| ❌ Réseau interne | ✅ Accès externe uniquement |
|
| 246 |
+
|
| 247 |
+
---
|
| 248 |
+
|
| 249 |
+
## 🎯 Commandes Utiles
|
| 250 |
+
|
| 251 |
+
```bash
|
| 252 |
+
# Vérifier le statut Git
|
| 253 |
+
git status
|
| 254 |
+
|
| 255 |
+
# Voir les remotes
|
| 256 |
+
git remote -v
|
| 257 |
+
|
| 258 |
+
# Forcer un rebuild (après config)
|
| 259 |
+
git commit --allow-empty -m "Trigger rebuild"
|
| 260 |
+
git push space main
|
| 261 |
+
|
| 262 |
+
# Voir les logs du dernier commit
|
| 263 |
+
git log -1
|
| 264 |
+
|
| 265 |
+
# Supprimer le remote et recréer
|
| 266 |
+
git remote remove space
|
| 267 |
+
git remote add space https://puyol85:TOKEN@huggingface.co/spaces/puyol85/pvgfd
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
---
|
| 271 |
+
|
| 272 |
+
## 📚 Ressources
|
| 273 |
+
|
| 274 |
+
- **Documentation HF Docker** : https://huggingface.co/docs/hub/spaces-sdks-docker
|
| 275 |
+
- **Documentation Streamlit** : https://docs.streamlit.io/
|
| 276 |
+
- **Exemples de Spaces** : https://huggingface.co/spaces
|
| 277 |
+
|
| 278 |
+
---
|
| 279 |
+
|
| 280 |
+
## ✅ Checklist
|
| 281 |
+
|
| 282 |
+
- [ ] Compte HF créé
|
| 283 |
+
- [ ] Token HF généré (Write)
|
| 284 |
+
- [ ] Cluster Qdrant créé
|
| 285 |
+
- [ ] Space `pvgfd` créé sur HF
|
| 286 |
+
- [ ] Code pushé vers HF
|
| 287 |
+
- [ ] Secrets configurés (6 variables)
|
| 288 |
+
- [ ] Build réussi
|
| 289 |
+
- [ ] App testée et fonctionnelle
|
| 290 |
+
|
| 291 |
+
---
|
| 292 |
+
|
| 293 |
+
**✨ Votre app PVGFD est maintenant sur Hugging Face Spaces !**
|
| 294 |
+
|
| 295 |
+
**URL** : https://huggingface.co/spaces/puyol85/pvgfd
|
| 296 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker-streamlit
|
| 2 |
+
# Dockerfile pour Streamlit sur Hugging Face Spaces
|
| 3 |
+
|
| 4 |
+
FROM python:3.10-slim
|
| 5 |
+
|
| 6 |
+
# Créer un utilisateur non-root (requis par HF)
|
| 7 |
+
RUN useradd -m -u 1000 user
|
| 8 |
+
USER user
|
| 9 |
+
|
| 10 |
+
# Ajouter le bin local au PATH
|
| 11 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 12 |
+
|
| 13 |
+
# Définir le répertoire de travail
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
|
| 16 |
+
# Copier les requirements et installer les dépendances
|
| 17 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 18 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 19 |
+
|
| 20 |
+
# Copier tout le code de l'application
|
| 21 |
+
COPY --chown=user . /app
|
| 22 |
+
|
| 23 |
+
# Créer le dossier uploads
|
| 24 |
+
RUN mkdir -p /app/uploads
|
| 25 |
+
|
| 26 |
+
# Exposer le port 7860 (port par défaut HF Spaces)
|
| 27 |
+
EXPOSE 7860
|
| 28 |
+
|
| 29 |
+
# Lancer l'application Streamlit
|
| 30 |
+
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
| 31 |
+
|
README.md
CHANGED
|
@@ -1,12 +1,64 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
emoji: 📚
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
license:
|
| 9 |
-
short_description: 'Projet de ville et Gestion Foncière Durable '
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: PVGFD Q&A
|
| 3 |
emoji: 📚
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
license: mit
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# PVGFD - Q&A sur Documents PDF
|
| 12 |
+
|
| 13 |
+
Application de Questions/Réponses basée sur des documents PDF, utilisant Hugging Face pour les modèles de langage et Qdrant comme base de données vectorielle.
|
| 14 |
+
|
| 15 |
+
## ✨ Fonctionnalités
|
| 16 |
+
|
| 17 |
+
- **Upload de documents PDF** : Interface simple pour ajouter vos documents
|
| 18 |
+
- **Traitement intelligent** : Extraction de texte, découpage en chunks, et génération d'embeddings
|
| 19 |
+
- **Recherche sémantique** : Utilisation de Qdrant pour trouver les passages pertinents
|
| 20 |
+
- **Génération de réponses** : LLM Hugging Face répond aux questions en se basant sur le contexte
|
| 21 |
+
|
| 22 |
+
## 🚀 Utilisation
|
| 23 |
+
|
| 24 |
+
1. **Configurer les variables d'environnement** dans les Settings de votre Space
|
| 25 |
+
2. **Uploader un document PDF**
|
| 26 |
+
3. **Poser vos questions** et obtenez des réponses basées sur le contenu
|
| 27 |
+
|
| 28 |
+
## 🔧 Configuration Requise
|
| 29 |
+
|
| 30 |
+
### Variables d'Environnement (Secrets HF)
|
| 31 |
+
|
| 32 |
+
Configurez ces secrets dans votre Space (Settings → Variables and secrets):
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
HF_TOKEN=votre_token_huggingface
|
| 36 |
+
HF_ENDPOINT_URL=votre_endpoint_url
|
| 37 |
+
HF_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
|
| 38 |
+
QDRANT_URL=votre_cluster_qdrant_cloud
|
| 39 |
+
QDRANT_API_KEY=votre_api_key_qdrant
|
| 40 |
+
QDRANT_COLLECTION=bm_documents
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Obtenir les Credentials
|
| 44 |
+
|
| 45 |
+
#### 1. Hugging Face Token
|
| 46 |
+
- Allez sur https://huggingface.co/settings/tokens
|
| 47 |
+
- Créez un nouveau token avec les permissions "read"
|
| 48 |
+
|
| 49 |
+
#### 2. Qdrant Cloud
|
| 50 |
+
- Créez un compte gratuit sur https://cloud.qdrant.io/
|
| 51 |
+
- Créez un cluster (tier gratuit disponible)
|
| 52 |
+
- Récupérez l'URL et l'API Key
|
| 53 |
+
|
| 54 |
+
## 🛠️ Technologies
|
| 55 |
+
|
| 56 |
+
- **Streamlit** - Interface web
|
| 57 |
+
- **Hugging Face** - Embeddings et LLM
|
| 58 |
+
- **Qdrant Cloud** - Base de données vectorielle
|
| 59 |
+
- **PyMuPDF** - Traitement PDF
|
| 60 |
+
- **Sentence Transformers** - Génération d'embeddings
|
| 61 |
+
|
| 62 |
+
## 📝 Licence
|
| 63 |
+
|
| 64 |
+
MIT License
|
app.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BM Answers - Application Streamlit pour Q&A sur documents PDF
|
| 3 |
+
"""
|
| 4 |
+
import streamlit as st
|
| 5 |
+
import os
|
| 6 |
+
import uuid
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from app.config import settings
|
| 11 |
+
from app.pdf_processor import PDFProcessor
|
| 12 |
+
from app.embeddings import EmbeddingGenerator
|
| 13 |
+
from app.qdrant_client import QdrantManager
|
| 14 |
+
from app.llm_client import LLMClient
|
| 15 |
+
|
| 16 |
+
# Configuration du logging
|
| 17 |
+
logging.basicConfig(level=logging.INFO)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
# Configuration de la page
|
| 21 |
+
st.set_page_config(
|
| 22 |
+
page_title="BM Answers",
|
| 23 |
+
page_icon="📚",
|
| 24 |
+
layout="wide",
|
| 25 |
+
initial_sidebar_state="expanded"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Créer le dossier uploads
|
| 29 |
+
os.makedirs(settings.upload_dir, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@st.cache_resource
|
| 33 |
+
def initialize_components():
|
| 34 |
+
"""Initialise les composants (mis en cache)"""
|
| 35 |
+
try:
|
| 36 |
+
pdf_processor = PDFProcessor(
|
| 37 |
+
chunk_size=settings.chunk_size,
|
| 38 |
+
chunk_overlap=settings.chunk_overlap
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
embedding_generator = EmbeddingGenerator(
|
| 42 |
+
model_name=settings.hf_embedding_model
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
qdrant_manager = QdrantManager(
|
| 46 |
+
url=settings.qdrant_url,
|
| 47 |
+
api_key=settings.qdrant_api_key,
|
| 48 |
+
collection_name=settings.qdrant_collection,
|
| 49 |
+
vector_size=embedding_generator.get_dimension()
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
llm_client = LLMClient(
|
| 53 |
+
token=settings.hf_token,
|
| 54 |
+
endpoint_url=settings.hf_endpoint_url
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
return pdf_processor, embedding_generator, qdrant_manager, llm_client
|
| 58 |
+
except Exception as e:
|
| 59 |
+
st.error(f"❌ Erreur d'initialisation: {e}")
|
| 60 |
+
st.stop()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Initialiser les composants
|
| 64 |
+
pdf_processor, embedding_generator, qdrant_manager, llm_client = initialize_components()
|
| 65 |
+
|
| 66 |
+
# Initialiser l'état de session
|
| 67 |
+
if 'messages' not in st.session_state:
|
| 68 |
+
st.session_state.messages = []
|
| 69 |
+
if 'uploaded_documents' not in st.session_state:
|
| 70 |
+
st.session_state.uploaded_documents = []
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main():
|
| 74 |
+
"""Interface principale"""
|
| 75 |
+
|
| 76 |
+
# En-tête
|
| 77 |
+
st.title("📚 BM Answers")
|
| 78 |
+
st.markdown("### Posez des questions sur vos documents PDF")
|
| 79 |
+
|
| 80 |
+
# Sidebar pour l'upload
|
| 81 |
+
with st.sidebar:
|
| 82 |
+
st.header("📄 Upload Document")
|
| 83 |
+
|
| 84 |
+
uploaded_file = st.file_uploader(
|
| 85 |
+
"Choisissez un fichier PDF",
|
| 86 |
+
type=['pdf'],
|
| 87 |
+
help="Maximum 10MB"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if uploaded_file is not None:
|
| 91 |
+
if st.button("🚀 Traiter le document", type="primary"):
|
| 92 |
+
process_document(uploaded_file)
|
| 93 |
+
|
| 94 |
+
# Afficher les documents uploadés
|
| 95 |
+
if st.session_state.uploaded_documents:
|
| 96 |
+
st.divider()
|
| 97 |
+
st.subheader("📚 Documents uploadés")
|
| 98 |
+
for doc in st.session_state.uploaded_documents:
|
| 99 |
+
st.write(f"✅ {doc['filename']}")
|
| 100 |
+
st.caption(f"{doc['num_chunks']} chunks")
|
| 101 |
+
|
| 102 |
+
# Informations système
|
| 103 |
+
st.divider()
|
| 104 |
+
st.caption("**Configuration:**")
|
| 105 |
+
if settings.hf_endpoint_url:
|
| 106 |
+
st.caption(f"🚀 Endpoint dédié HF")
|
| 107 |
+
else:
|
| 108 |
+
st.caption(f"🌐 API publique HF")
|
| 109 |
+
st.caption(f"📊 Embeddings: {settings.hf_embedding_model.split('/')[-1]}")
|
| 110 |
+
|
| 111 |
+
# Zone de chat principale
|
| 112 |
+
st.divider()
|
| 113 |
+
|
| 114 |
+
# Afficher l'historique des messages
|
| 115 |
+
for message in st.session_state.messages:
|
| 116 |
+
with st.chat_message(message["role"]):
|
| 117 |
+
st.markdown(message["content"])
|
| 118 |
+
|
| 119 |
+
# Afficher les sources si présentes
|
| 120 |
+
if "sources" in message and message["sources"]:
|
| 121 |
+
with st.expander("📎 Sources"):
|
| 122 |
+
for i, source in enumerate(message["sources"], 1):
|
| 123 |
+
st.markdown(f"**Source {i}** ({source['filename']}) - Score: {source['score']:.2f}")
|
| 124 |
+
st.text(source['text'][:200] + "...")
|
| 125 |
+
|
| 126 |
+
# Input utilisateur
|
| 127 |
+
if prompt := st.chat_input("Posez votre question..."):
|
| 128 |
+
# Vérifier qu'au moins un document a été uploadé
|
| 129 |
+
if not st.session_state.uploaded_documents:
|
| 130 |
+
st.warning("⚠️ Veuillez d'abord uploader un document PDF")
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
# Ajouter le message de l'utilisateur
|
| 134 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 135 |
+
with st.chat_message("user"):
|
| 136 |
+
st.markdown(prompt)
|
| 137 |
+
|
| 138 |
+
# Générer la réponse
|
| 139 |
+
with st.chat_message("assistant"):
|
| 140 |
+
with st.spinner("🤔 Recherche dans les documents..."):
|
| 141 |
+
response = generate_answer(prompt)
|
| 142 |
+
st.markdown(response["answer"])
|
| 143 |
+
|
| 144 |
+
# Afficher les sources
|
| 145 |
+
if response["sources"]:
|
| 146 |
+
with st.expander("📎 Sources"):
|
| 147 |
+
for i, source in enumerate(response["sources"], 1):
|
| 148 |
+
st.markdown(f"**Source {i}** ({source['filename']}) - Score: {source['score']:.2f}")
|
| 149 |
+
st.text(source['text'][:200] + "...")
|
| 150 |
+
|
| 151 |
+
# Ajouter la réponse à l'historique
|
| 152 |
+
st.session_state.messages.append({
|
| 153 |
+
"role": "assistant",
|
| 154 |
+
"content": response["answer"],
|
| 155 |
+
"sources": response["sources"]
|
| 156 |
+
})
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def process_document(uploaded_file):
|
| 160 |
+
"""Traite un document PDF uploadé"""
|
| 161 |
+
try:
|
| 162 |
+
# Vérifier la taille
|
| 163 |
+
if uploaded_file.size > settings.max_file_size:
|
| 164 |
+
st.error(f"❌ Fichier trop volumineux. Maximum: {settings.max_file_size / 1024 / 1024}MB")
|
| 165 |
+
return
|
| 166 |
+
|
| 167 |
+
with st.spinner("📄 Traitement du document..."):
|
| 168 |
+
# Générer un ID unique
|
| 169 |
+
document_id = str(uuid.uuid4())
|
| 170 |
+
|
| 171 |
+
# Sauvegarder le fichier
|
| 172 |
+
file_path = os.path.join(settings.upload_dir, f"{document_id}.pdf")
|
| 173 |
+
with open(file_path, "wb") as f:
|
| 174 |
+
f.write(uploaded_file.getbuffer())
|
| 175 |
+
|
| 176 |
+
# Traiter le PDF
|
| 177 |
+
st.info("🔍 Extraction du texte...")
|
| 178 |
+
chunks_with_positions = pdf_processor.process_pdf(file_path)
|
| 179 |
+
chunks = [chunk[0] for chunk in chunks_with_positions]
|
| 180 |
+
|
| 181 |
+
# Générer les embeddings
|
| 182 |
+
st.info(f"🧠 Génération des embeddings ({len(chunks)} chunks)...")
|
| 183 |
+
embeddings = embedding_generator.generate_embeddings_batch(chunks)
|
| 184 |
+
|
| 185 |
+
# Stocker dans Qdrant
|
| 186 |
+
st.info("💾 Stockage dans Qdrant Cloud...")
|
| 187 |
+
metadata = {
|
| 188 |
+
"filename": uploaded_file.name,
|
| 189 |
+
"upload_date": datetime.now().isoformat(),
|
| 190 |
+
}
|
| 191 |
+
num_chunks = qdrant_manager.add_document(
|
| 192 |
+
document_id=document_id,
|
| 193 |
+
chunks=chunks,
|
| 194 |
+
embeddings=embeddings,
|
| 195 |
+
metadata=metadata
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# Ajouter à la liste des documents
|
| 199 |
+
st.session_state.uploaded_documents.append({
|
| 200 |
+
"id": document_id,
|
| 201 |
+
"filename": uploaded_file.name,
|
| 202 |
+
"num_chunks": num_chunks,
|
| 203 |
+
"upload_date": datetime.now()
|
| 204 |
+
})
|
| 205 |
+
|
| 206 |
+
st.success(f"✅ Document traité avec succès! {num_chunks} chunks créés")
|
| 207 |
+
st.balloons()
|
| 208 |
+
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.error(f"Erreur lors du traitement: {e}")
|
| 211 |
+
st.error(f"❌ Erreur: {str(e)}")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def generate_answer(question: str):
|
| 215 |
+
"""Génère une réponse à une question"""
|
| 216 |
+
try:
|
| 217 |
+
# Générer l'embedding de la question
|
| 218 |
+
question_embedding = embedding_generator.generate_embedding(question)
|
| 219 |
+
|
| 220 |
+
# Rechercher les chunks pertinents
|
| 221 |
+
results = qdrant_manager.search(
|
| 222 |
+
query_embedding=question_embedding,
|
| 223 |
+
top_k=settings.top_k_results
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
if not results:
|
| 227 |
+
return {
|
| 228 |
+
"answer": "Je n'ai trouvé aucun document pertinent pour répondre à cette question.",
|
| 229 |
+
"sources": [],
|
| 230 |
+
"confidence": 0.0
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
# Générer la réponse avec le LLM
|
| 234 |
+
answer = llm_client.generate_answer(question, results)
|
| 235 |
+
|
| 236 |
+
return {
|
| 237 |
+
"answer": answer,
|
| 238 |
+
"sources": results,
|
| 239 |
+
"confidence": sum(r['score'] for r in results) / len(results)
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
except Exception as e:
|
| 243 |
+
logger.error(f"Erreur lors de la génération: {e}")
|
| 244 |
+
return {
|
| 245 |
+
"answer": f"❌ Erreur lors de la génération de la réponse: {str(e)}",
|
| 246 |
+
"sources": [],
|
| 247 |
+
"confidence": 0.0
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
main()
|
| 253 |
+
|
app/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BM Answers - Q&A sur Documents PDF"""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
| 4 |
+
|
app/config.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration de l'application"""
|
| 2 |
+
import os
|
| 3 |
+
from pydantic_settings import BaseSettings
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Settings(BaseSettings):
|
| 7 |
+
"""Configuration de l'application"""
|
| 8 |
+
|
| 9 |
+
# Hugging Face
|
| 10 |
+
hf_token: str = os.getenv("HF_TOKEN", "")
|
| 11 |
+
hf_endpoint_url: str = os.getenv("HF_ENDPOINT_URL", "")
|
| 12 |
+
hf_embedding_model: str = os.getenv("HF_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
| 13 |
+
|
| 14 |
+
# Qdrant Cloud
|
| 15 |
+
qdrant_url: str = os.getenv("QDRANT_URL", "")
|
| 16 |
+
qdrant_api_key: str = os.getenv("QDRANT_API_KEY", "")
|
| 17 |
+
qdrant_collection: str = os.getenv("QDRANT_COLLECTION", "bm_documents")
|
| 18 |
+
|
| 19 |
+
# Application
|
| 20 |
+
upload_dir: str = os.getenv("UPLOAD_DIR", "./uploads")
|
| 21 |
+
max_file_size: int = int(os.getenv("MAX_FILE_SIZE", "10485760")) # 10MB
|
| 22 |
+
chunk_size: int = int(os.getenv("CHUNK_SIZE", "500"))
|
| 23 |
+
chunk_overlap: int = int(os.getenv("CHUNK_OVERLAP", "50"))
|
| 24 |
+
top_k_results: int = int(os.getenv("TOP_K_RESULTS", "3"))
|
| 25 |
+
|
| 26 |
+
class Config:
|
| 27 |
+
env_file = ".env"
|
| 28 |
+
extra = "ignore" # Ignore les champs supplémentaires dans .env
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
settings = Settings()
|
| 32 |
+
|
app/embeddings.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Génération d'embeddings avec Sentence Transformers"""
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
| 3 |
+
from typing import List
|
| 4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class EmbeddingGenerator:
|
| 11 |
+
"""Génère des embeddings pour le texte"""
|
| 12 |
+
|
| 13 |
+
def __init__(self, model_name: str = "sentence-transformers/all-MiniLM-L6-v2"):
|
| 14 |
+
"""
|
| 15 |
+
Args:
|
| 16 |
+
model_name: Nom du modèle Sentence Transformers
|
| 17 |
+
"""
|
| 18 |
+
logger.info(f"Chargement du modèle d'embeddings: {model_name}")
|
| 19 |
+
self.model = SentenceTransformer(model_name)
|
| 20 |
+
self.embedding_dim = self.model.get_sentence_embedding_dimension()
|
| 21 |
+
logger.info(f"Modèle chargé. Dimension des embeddings: {self.embedding_dim}")
|
| 22 |
+
|
| 23 |
+
def generate_embedding(self, text: str) -> List[float]:
|
| 24 |
+
"""
|
| 25 |
+
Génère un embedding pour un texte
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
text: Texte à encoder
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Liste de floats (embedding)
|
| 32 |
+
"""
|
| 33 |
+
embedding = self.model.encode(text, convert_to_numpy=True)
|
| 34 |
+
return embedding.tolist()
|
| 35 |
+
|
| 36 |
+
def generate_embeddings_batch(self, texts: List[str]) -> List[List[float]]:
|
| 37 |
+
"""
|
| 38 |
+
Génère des embeddings pour plusieurs textes (batch)
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
texts: Liste de textes
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
Liste d'embeddings
|
| 45 |
+
"""
|
| 46 |
+
logger.info(f"Génération de {len(texts)} embeddings en batch")
|
| 47 |
+
embeddings = self.model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
|
| 48 |
+
return embeddings.tolist()
|
| 49 |
+
|
| 50 |
+
def get_dimension(self) -> int:
|
| 51 |
+
"""Retourne la dimension des embeddings"""
|
| 52 |
+
return self.embedding_dim
|
| 53 |
+
|
app/llm_client.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Client pour Hugging Face Inference API"""
|
| 2 |
+
from huggingface_hub import InferenceClient
|
| 3 |
+
from typing import List, Dict
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LLMClient:
|
| 10 |
+
"""Client pour générer des réponses avec Hugging Face"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, token: str, endpoint_url: str = ""):
|
| 13 |
+
"""
|
| 14 |
+
Args:
|
| 15 |
+
token: Token Hugging Face
|
| 16 |
+
endpoint_url: URL de l'endpoint dédié (si vide, utilise l'API publique)
|
| 17 |
+
"""
|
| 18 |
+
logger.info(f"Initialisation du client LLM: {endpoint_url or 'API publique'}")
|
| 19 |
+
self.client = InferenceClient(token=token)
|
| 20 |
+
self.endpoint_url = endpoint_url
|
| 21 |
+
|
| 22 |
+
def generate_answer(self, question: str, context_chunks: List[Dict]) -> str:
|
| 23 |
+
"""
|
| 24 |
+
Génère une réponse basée sur le contexte
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
question: Question de l'utilisateur
|
| 28 |
+
context_chunks: Liste de chunks pertinents avec métadonnées
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Réponse générée
|
| 32 |
+
"""
|
| 33 |
+
# Construire le contexte
|
| 34 |
+
context = "\n\n".join([
|
| 35 |
+
f"[Document: {chunk['filename']}]\n{chunk['text']}"
|
| 36 |
+
for chunk in context_chunks
|
| 37 |
+
])
|
| 38 |
+
|
| 39 |
+
# Prompt avec instructions
|
| 40 |
+
prompt = f"""Tu es un assistant IA qui répond aux questions en te basant UNIQUEMENT sur le contexte fourni.
|
| 41 |
+
|
| 42 |
+
Contexte:
|
| 43 |
+
{context}
|
| 44 |
+
|
| 45 |
+
Question: {question}
|
| 46 |
+
|
| 47 |
+
Instructions:
|
| 48 |
+
- Réponds de manière précise et concise
|
| 49 |
+
- Base ta réponse UNIQUEMENT sur le contexte fourni
|
| 50 |
+
- Si la réponse n'est pas dans le contexte, dis "Je ne trouve pas cette information dans les documents fournis"
|
| 51 |
+
- Cite le nom du document quand c'est pertinent
|
| 52 |
+
|
| 53 |
+
Réponse:"""
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
# Génération avec l'endpoint dédié ou l'API publique
|
| 57 |
+
if self.endpoint_url:
|
| 58 |
+
# Utiliser l'endpoint dédié
|
| 59 |
+
response = self.client.text_generation(
|
| 60 |
+
prompt,
|
| 61 |
+
model=self.endpoint_url,
|
| 62 |
+
max_new_tokens=500,
|
| 63 |
+
temperature=0.7,
|
| 64 |
+
top_p=0.95,
|
| 65 |
+
repetition_penalty=1.1,
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
# Fallback sur l'API publique (nécessite un model valide)
|
| 69 |
+
response = self.client.text_generation(
|
| 70 |
+
prompt,
|
| 71 |
+
model="HuggingFaceH4/zephyr-7b-beta",
|
| 72 |
+
max_new_tokens=500,
|
| 73 |
+
temperature=0.7,
|
| 74 |
+
top_p=0.95,
|
| 75 |
+
repetition_penalty=1.1,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
logger.info(f"Réponse générée ({len(response)} caractères)")
|
| 79 |
+
return response.strip()
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.error(f"Erreur lors de la génération: {e}")
|
| 83 |
+
return f"Erreur lors de la génération de la réponse: {str(e)}"
|
| 84 |
+
|
app/pdf_processor.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Traitement des fichiers PDF"""
|
| 2 |
+
import fitz # PyMuPDF
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PDFProcessor:
|
| 10 |
+
"""Classe pour traiter les fichiers PDF"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, chunk_size: int = 500, chunk_overlap: int = 50):
|
| 13 |
+
"""
|
| 14 |
+
Args:
|
| 15 |
+
chunk_size: Taille des chunks en tokens (approximatif)
|
| 16 |
+
chunk_overlap: Chevauchement entre les chunks
|
| 17 |
+
"""
|
| 18 |
+
self.chunk_size = chunk_size
|
| 19 |
+
self.chunk_overlap = chunk_overlap
|
| 20 |
+
|
| 21 |
+
def extract_text(self, pdf_path: str) -> str:
|
| 22 |
+
"""
|
| 23 |
+
Extrait le texte d'un PDF
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
pdf_path: Chemin vers le fichier PDF
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
Texte extrait
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
doc = fitz.open(pdf_path)
|
| 33 |
+
text = ""
|
| 34 |
+
|
| 35 |
+
for page_num in range(len(doc)):
|
| 36 |
+
page = doc[page_num]
|
| 37 |
+
text += page.get_text()
|
| 38 |
+
|
| 39 |
+
doc.close()
|
| 40 |
+
logger.info(f"Extrait {len(text)} caractères de {pdf_path}")
|
| 41 |
+
return text
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.error(f"Erreur lors de l'extraction du PDF {pdf_path}: {e}")
|
| 45 |
+
raise
|
| 46 |
+
|
| 47 |
+
def chunk_text(self, text: str) -> List[Tuple[str, int]]:
|
| 48 |
+
"""
|
| 49 |
+
Découpe le texte en chunks avec overlap
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
text: Texte à découper
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
Liste de tuples (chunk_text, start_position)
|
| 56 |
+
"""
|
| 57 |
+
# Approximation: 1 token ≈ 4 caractères
|
| 58 |
+
chunk_size_chars = self.chunk_size * 4
|
| 59 |
+
overlap_chars = self.chunk_overlap * 4
|
| 60 |
+
|
| 61 |
+
chunks = []
|
| 62 |
+
start = 0
|
| 63 |
+
|
| 64 |
+
while start < len(text):
|
| 65 |
+
end = start + chunk_size_chars
|
| 66 |
+
chunk = text[start:end]
|
| 67 |
+
|
| 68 |
+
# Éviter de couper au milieu d'un mot
|
| 69 |
+
if end < len(text):
|
| 70 |
+
last_space = chunk.rfind(' ')
|
| 71 |
+
if last_space > chunk_size_chars * 0.8: # Au moins 80% du chunk
|
| 72 |
+
end = start + last_space
|
| 73 |
+
chunk = text[start:end]
|
| 74 |
+
|
| 75 |
+
if chunk.strip(): # Ignorer les chunks vides
|
| 76 |
+
chunks.append((chunk.strip(), start))
|
| 77 |
+
|
| 78 |
+
start = end - overlap_chars
|
| 79 |
+
|
| 80 |
+
# Éviter les boucles infinies
|
| 81 |
+
if start >= len(text):
|
| 82 |
+
break
|
| 83 |
+
|
| 84 |
+
logger.info(f"Texte découpé en {len(chunks)} chunks")
|
| 85 |
+
return chunks
|
| 86 |
+
|
| 87 |
+
def process_pdf(self, pdf_path: str) -> List[Tuple[str, int]]:
|
| 88 |
+
"""
|
| 89 |
+
Traite un PDF: extraction + chunking
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
pdf_path: Chemin vers le fichier PDF
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
Liste de chunks avec leurs positions
|
| 96 |
+
"""
|
| 97 |
+
text = self.extract_text(pdf_path)
|
| 98 |
+
chunks = self.chunk_text(text)
|
| 99 |
+
return chunks
|
| 100 |
+
|
app/qdrant_client.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Client pour interagir avec Qdrant Cloud"""
|
| 2 |
+
from qdrant_client import QdrantClient
|
| 3 |
+
from qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition, MatchValue
|
| 4 |
+
from typing import List, Dict, Optional
|
| 5 |
+
import logging
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class QdrantManager:
|
| 12 |
+
"""Gère les interactions avec Qdrant Cloud"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, url: str, api_key: str, collection_name: str, vector_size: int = 384):
|
| 15 |
+
"""
|
| 16 |
+
Args:
|
| 17 |
+
url: URL du cluster Qdrant Cloud
|
| 18 |
+
api_key: API Key Qdrant
|
| 19 |
+
collection_name: Nom de la collection
|
| 20 |
+
vector_size: Dimension des vecteurs (384 pour all-MiniLM-L6-v2)
|
| 21 |
+
"""
|
| 22 |
+
logger.info(f"Connexion à Qdrant Cloud: {url}")
|
| 23 |
+
self.client = QdrantClient(
|
| 24 |
+
url=url,
|
| 25 |
+
api_key=api_key,
|
| 26 |
+
prefer_grpc=True,
|
| 27 |
+
)
|
| 28 |
+
self.collection_name = collection_name
|
| 29 |
+
self.vector_size = vector_size
|
| 30 |
+
self._ensure_collection_exists()
|
| 31 |
+
|
| 32 |
+
def _ensure_collection_exists(self):
|
| 33 |
+
"""Crée la collection si elle n'existe pas"""
|
| 34 |
+
try:
|
| 35 |
+
collections = self.client.get_collections().collections
|
| 36 |
+
collection_names = [col.name for col in collections]
|
| 37 |
+
|
| 38 |
+
if self.collection_name not in collection_names:
|
| 39 |
+
logger.info(f"Création de la collection: {self.collection_name}")
|
| 40 |
+
self.client.create_collection(
|
| 41 |
+
collection_name=self.collection_name,
|
| 42 |
+
vectors_config=VectorParams(
|
| 43 |
+
size=self.vector_size,
|
| 44 |
+
distance=Distance.COSINE
|
| 45 |
+
)
|
| 46 |
+
)
|
| 47 |
+
logger.info(f"Collection créée: {self.collection_name}")
|
| 48 |
+
else:
|
| 49 |
+
logger.info(f"Collection existante: {self.collection_name}")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.error(f"Erreur lors de la vérification/création de la collection: {e}")
|
| 52 |
+
raise
|
| 53 |
+
|
| 54 |
+
def add_document(self, document_id: str, chunks: List[str], embeddings: List[List[float]], metadata: Dict) -> int:
|
| 55 |
+
"""
|
| 56 |
+
Ajoute un document (chunks + embeddings) dans Qdrant
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
document_id: ID unique du document
|
| 60 |
+
chunks: Liste des chunks de texte
|
| 61 |
+
embeddings: Liste des embeddings correspondants
|
| 62 |
+
metadata: Métadonnées du document (filename, date, etc.)
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
Nombre de chunks ajoutés
|
| 66 |
+
"""
|
| 67 |
+
if len(chunks) != len(embeddings):
|
| 68 |
+
raise ValueError("Le nombre de chunks doit correspondre au nombre d'embeddings")
|
| 69 |
+
|
| 70 |
+
points = []
|
| 71 |
+
for idx, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
|
| 72 |
+
point_id = str(uuid.uuid4())
|
| 73 |
+
payload = {
|
| 74 |
+
"document_id": document_id,
|
| 75 |
+
"chunk_text": chunk,
|
| 76 |
+
"chunk_index": idx,
|
| 77 |
+
"filename": metadata.get("filename", ""),
|
| 78 |
+
"upload_date": metadata.get("upload_date", ""),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
points.append(PointStruct(
|
| 82 |
+
id=point_id,
|
| 83 |
+
vector=embedding,
|
| 84 |
+
payload=payload
|
| 85 |
+
))
|
| 86 |
+
|
| 87 |
+
# Upsert par batch
|
| 88 |
+
self.client.upsert(
|
| 89 |
+
collection_name=self.collection_name,
|
| 90 |
+
points=points
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
logger.info(f"Ajouté {len(points)} chunks pour le document {document_id}")
|
| 94 |
+
return len(points)
|
| 95 |
+
|
| 96 |
+
def search(self, query_embedding: List[float], top_k: int = 3, document_id: Optional[str] = None) -> List[Dict]:
|
| 97 |
+
"""
|
| 98 |
+
Recherche les chunks les plus pertinents
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
query_embedding: Embedding de la question
|
| 102 |
+
top_k: Nombre de résultats
|
| 103 |
+
document_id: Filtrer par document spécifique (optionnel)
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
Liste de résultats avec score et métadonnées
|
| 107 |
+
"""
|
| 108 |
+
search_filter = None
|
| 109 |
+
if document_id:
|
| 110 |
+
search_filter = Filter(
|
| 111 |
+
must=[
|
| 112 |
+
FieldCondition(
|
| 113 |
+
key="document_id",
|
| 114 |
+
match=MatchValue(value=document_id)
|
| 115 |
+
)
|
| 116 |
+
]
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
results = self.client.search(
|
| 120 |
+
collection_name=self.collection_name,
|
| 121 |
+
query_vector=query_embedding,
|
| 122 |
+
limit=top_k,
|
| 123 |
+
query_filter=search_filter
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
formatted_results = []
|
| 127 |
+
for result in results:
|
| 128 |
+
formatted_results.append({
|
| 129 |
+
"text": result.payload.get("chunk_text", ""),
|
| 130 |
+
"score": result.score,
|
| 131 |
+
"document_id": result.payload.get("document_id", ""),
|
| 132 |
+
"filename": result.payload.get("filename", ""),
|
| 133 |
+
"chunk_index": result.payload.get("chunk_index", 0),
|
| 134 |
+
})
|
| 135 |
+
|
| 136 |
+
return formatted_results
|
| 137 |
+
|
| 138 |
+
def delete_document(self, document_id: str) -> int:
|
| 139 |
+
"""
|
| 140 |
+
Supprime tous les chunks d'un document
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
document_id: ID du document
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
Nombre de points supprimés
|
| 147 |
+
"""
|
| 148 |
+
result = self.client.delete(
|
| 149 |
+
collection_name=self.collection_name,
|
| 150 |
+
points_selector=Filter(
|
| 151 |
+
must=[
|
| 152 |
+
FieldCondition(
|
| 153 |
+
key="document_id",
|
| 154 |
+
match=MatchValue(value=document_id)
|
| 155 |
+
)
|
| 156 |
+
]
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
logger.info(f"Document {document_id} supprimé de Qdrant")
|
| 161 |
+
return 1 # Retourne 1 pour indiquer succès
|
| 162 |
+
|
| 163 |
+
def get_documents(self) -> List[Dict]:
|
| 164 |
+
"""
|
| 165 |
+
Récupère la liste des documents uniques
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
Liste des documents avec métadonnées
|
| 169 |
+
"""
|
| 170 |
+
# Note: Qdrant ne stocke pas directement la liste des documents
|
| 171 |
+
# Il faudrait maintenir une base séparée ou faire un scroll de tous les points
|
| 172 |
+
# Pour simplicité, on retourne une liste vide ici
|
| 173 |
+
# À améliorer avec une vraie base de données pour les métadonnées
|
| 174 |
+
return []
|
| 175 |
+
|
deploy.sh
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Script de déploiement pour pvgfd sur Hugging Face Spaces
|
| 4 |
+
# Lit les credentials depuis ~/.hf_token ou demande interactivement
|
| 5 |
+
|
| 6 |
+
set -e
|
| 7 |
+
|
| 8 |
+
echo "=================================="
|
| 9 |
+
echo "🚀 Déploiement PVGFD sur HF Spaces"
|
| 10 |
+
echo "=================================="
|
| 11 |
+
echo ""
|
| 12 |
+
|
| 13 |
+
# Vérifier si on est dans le bon dossier
|
| 14 |
+
if [ ! -f "app.py" ]; then
|
| 15 |
+
echo "❌ Erreur: app.py non trouvé"
|
| 16 |
+
echo " Exécutez ce script depuis /home/koffi/projects/pvgfd"
|
| 17 |
+
exit 1
|
| 18 |
+
fi
|
| 19 |
+
|
| 20 |
+
# Charger le token depuis ~/.hf_token si existe
|
| 21 |
+
if [ -f "$HOME/.hf_token" ]; then
|
| 22 |
+
echo "📁 Chargement du token depuis ~/.hf_token..."
|
| 23 |
+
export HF_TOKEN=$(cat "$HOME/.hf_token")
|
| 24 |
+
fi
|
| 25 |
+
|
| 26 |
+
# Demander les infos si pas définies
|
| 27 |
+
if [ -z "$HF_USERNAME" ]; then
|
| 28 |
+
read -p "Votre username Hugging Face [puyol85]: " HF_USERNAME
|
| 29 |
+
HF_USERNAME=${HF_USERNAME:-puyol85}
|
| 30 |
+
fi
|
| 31 |
+
|
| 32 |
+
if [ -z "$HF_TOKEN" ]; then
|
| 33 |
+
read -p "Votre token HF (ou appuyez sur Entrée pour utiliser celui sauvegardé): " HF_TOKEN_INPUT
|
| 34 |
+
if [ -n "$HF_TOKEN_INPUT" ]; then
|
| 35 |
+
HF_TOKEN=$HF_TOKEN_INPUT
|
| 36 |
+
# Sauvegarder pour la prochaine fois
|
| 37 |
+
echo "$HF_TOKEN" > "$HOME/.hf_token"
|
| 38 |
+
chmod 600 "$HOME/.hf_token"
|
| 39 |
+
echo "✅ Token sauvegardé dans ~/.hf_token"
|
| 40 |
+
fi
|
| 41 |
+
fi
|
| 42 |
+
|
| 43 |
+
SPACE_NAME="pvgfd"
|
| 44 |
+
|
| 45 |
+
echo ""
|
| 46 |
+
echo "✅ Configuration:"
|
| 47 |
+
echo " Username: $HF_USERNAME"
|
| 48 |
+
echo " Space: $SPACE_NAME"
|
| 49 |
+
echo " URL: https://huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME"
|
| 50 |
+
echo ""
|
| 51 |
+
|
| 52 |
+
# Init Git si nécessaire
|
| 53 |
+
if [ ! -d ".git" ]; then
|
| 54 |
+
echo "📦 Initialisation Git..."
|
| 55 |
+
git init
|
| 56 |
+
git branch -M main
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
# Configurer le remote avec token dans l'URL
|
| 60 |
+
echo "🔗 Configuration du remote..."
|
| 61 |
+
git remote remove space 2>/dev/null || true
|
| 62 |
+
git remote add space "https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME"
|
| 63 |
+
|
| 64 |
+
# Staging et commit
|
| 65 |
+
echo "📦 Préparation des fichiers..."
|
| 66 |
+
git add .
|
| 67 |
+
|
| 68 |
+
read -p "Message de commit [Update PVGFD app]: " COMMIT_MSG
|
| 69 |
+
COMMIT_MSG=${COMMIT_MSG:-"Update PVGFD app"}
|
| 70 |
+
|
| 71 |
+
git commit -m "$COMMIT_MSG" || echo "⚠️ Aucun changement à commiter"
|
| 72 |
+
|
| 73 |
+
# Push
|
| 74 |
+
echo ""
|
| 75 |
+
echo "🚀 Push vers Hugging Face..."
|
| 76 |
+
git push space main
|
| 77 |
+
|
| 78 |
+
echo ""
|
| 79 |
+
echo "=================================="
|
| 80 |
+
echo "✅ Déploiement réussi !"
|
| 81 |
+
echo "=================================="
|
| 82 |
+
echo ""
|
| 83 |
+
echo "🌐 Votre Space:"
|
| 84 |
+
echo " https://huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME"
|
| 85 |
+
echo ""
|
| 86 |
+
echo "⏳ Build en cours (2-5 minutes)..."
|
| 87 |
+
echo ""
|
| 88 |
+
echo "🔐 Configurez les secrets:"
|
| 89 |
+
echo " https://huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME/settings"
|
| 90 |
+
echo ""
|
| 91 |
+
echo " Secrets requis:"
|
| 92 |
+
echo " - HF_TOKEN"
|
| 93 |
+
echo " - HF_ENDPOINT_URL"
|
| 94 |
+
echo " - HF_EMBEDDING_MODEL"
|
| 95 |
+
echo " - QDRANT_URL"
|
| 96 |
+
echo " - QDRANT_API_KEY"
|
| 97 |
+
echo " - QDRANT_COLLECTION"
|
| 98 |
+
echo ""
|
| 99 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Web Framework
|
| 2 |
+
streamlit==1.31.0
|
| 3 |
+
|
| 4 |
+
# PDF Processing
|
| 5 |
+
PyMuPDF==1.23.8
|
| 6 |
+
|
| 7 |
+
# Vector Database
|
| 8 |
+
qdrant-client==1.7.3
|
| 9 |
+
|
| 10 |
+
# Embeddings & LLM
|
| 11 |
+
sentence-transformers==2.3.1
|
| 12 |
+
huggingface-hub==0.20.2
|
| 13 |
+
|
| 14 |
+
# Utilities
|
| 15 |
+
python-dotenv==1.0.0
|
| 16 |
+
pydantic==2.5.3
|
| 17 |
+
pydantic-settings==2.1.0
|
| 18 |
+
|
uploads/.gitkeep
ADDED
|
File without changes
|