Spaces:
Running
Running
Déploiement version démo Hugging Face : mode démo en tête de script, aucun chargement de modèle en ligne
Browse files- README.md +45 -1
- requirements.txt +12 -9
- src/streamlit_app.py +431 -219
- start.sh +27 -0
README.md
CHANGED
@@ -33,4 +33,48 @@ Les résultats fournis sont à titre indicatif uniquement. Pour un diagnostic m
|
|
33 |
## Développement
|
34 |
- Framework: Streamlit
|
35 |
- Modèle: google/gemma-3n-e4b-it
|
36 |
-
- Dernière mise à jour: Juillet 2025
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
## Développement
|
34 |
- Framework: Streamlit
|
35 |
- Modèle: google/gemma-3n-e4b-it
|
36 |
+
- Dernière mise à jour: Juillet 2025
|
37 |
+
|
38 |
+
---
|
39 |
+
|
40 |
+
## 🇫🇷 Installation rapide
|
41 |
+
1. **Téléchargez ou clonez ce dépôt**
|
42 |
+
2. **Placez le dossier du modèle Gemma 3n dans `models/`** (exemple : `models/gemma-3n-transformers-gemma-3n-e2b-it-v1`)
|
43 |
+
3. **Ouvrez un terminal dans le dossier du projet**
|
44 |
+
4. **Exécutez le script d’installation automatique** :
|
45 |
+
```powershell
|
46 |
+
python install_agrilens.py
|
47 |
+
```
|
48 |
+
5. **Lancez l’application** :
|
49 |
+
```powershell
|
50 |
+
streamlit run src/streamlit_app.py
|
51 |
+
```
|
52 |
+
|
53 |
+
## 🇬🇧 Quick install
|
54 |
+
1. **Download or clone this repo**
|
55 |
+
2. **Place the Gemma 3n model folder in `models/`** (e.g. `models/gemma-3n-transformers-gemma-3n-e2b-it-v1`)
|
56 |
+
3. **Open a terminal in the project folder**
|
57 |
+
4. **Run the auto-install script**:
|
58 |
+
```powershell
|
59 |
+
python install_agrilens.py
|
60 |
+
```
|
61 |
+
5. **Launch the app**:
|
62 |
+
```powershell
|
63 |
+
streamlit run src/streamlit_app.py
|
64 |
+
```
|
65 |
+
|
66 |
+
---
|
67 |
+
|
68 |
+
## 🇫🇷 Script d’installation automatique
|
69 |
+
Le script `install_agrilens.py` :
|
70 |
+
- Crée l’environnement virtuel si besoin
|
71 |
+
- Installe toutes les dépendances (`requirements.txt`)
|
72 |
+
- Vérifie la présence du modèle dans `models/`
|
73 |
+
- Affiche les instructions de lancement
|
74 |
+
|
75 |
+
## 🇬🇧 Auto-install script
|
76 |
+
The `install_agrilens.py` script:
|
77 |
+
- Creates the virtual environment if needed
|
78 |
+
- Installs all dependencies (`requirements.txt`)
|
79 |
+
- Checks for the model in `models/`
|
80 |
+
- Shows launch instructions
|
requirements.txt
CHANGED
@@ -1,10 +1,13 @@
|
|
1 |
-
streamlit
|
2 |
-
transformers>=4.
|
3 |
torch
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
transformers>=4.53.1
|
3 |
torch
|
4 |
+
pillow
|
5 |
+
huggingface-hub
|
6 |
+
accelerate
|
7 |
+
timm
|
8 |
+
uvicorn
|
9 |
+
fastapi
|
10 |
+
kagglehub
|
11 |
+
requests
|
12 |
+
fpdf
|
13 |
+
pandas
|
src/streamlit_app.py
CHANGED
@@ -1,22 +1,56 @@
|
|
1 |
-
import os
|
2 |
import streamlit as st
|
3 |
-
|
4 |
-
import torch
|
5 |
-
from transformers import pipeline
|
6 |
-
import time
|
7 |
-
from pathlib import Path
|
8 |
-
import json
|
9 |
-
import logging
|
10 |
-
from fastapi import FastAPI, Request, Response
|
11 |
-
import uvicorn
|
12 |
-
|
13 |
-
# Configuration de la page
|
14 |
st.set_page_config(
|
15 |
-
page_title="AgriLens AI -
|
16 |
page_icon="🌱",
|
17 |
layout="wide",
|
18 |
initial_sidebar_state="expanded"
|
19 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
# Style CSS personnalisé
|
22 |
st.markdown("""
|
@@ -48,224 +82,402 @@ st.markdown("""
|
|
48 |
</style>
|
49 |
""", unsafe_allow_html=True)
|
50 |
|
51 |
-
#
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
-
#
|
55 |
-
|
56 |
-
|
|
|
57 |
|
58 |
-
#
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
"""Charge le modèle avec gestion du cache et du timeout"""
|
71 |
-
global MODEL
|
72 |
-
|
73 |
-
if MODEL is not None:
|
74 |
-
return MODEL
|
75 |
-
|
76 |
-
if not check_environment():
|
77 |
-
st.error("Configuration manquante. Vérifiez les logs pour plus d'informations.")
|
78 |
-
return None
|
79 |
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
)
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
-
def
|
129 |
-
|
130 |
-
|
131 |
-
#
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
for percent_complete in range(100):
|
140 |
-
time.sleep(0.01) # Simulation de traitement plus rapide
|
141 |
-
progress_bar.progress(percent_complete + 1, text=progress_text)
|
142 |
-
|
143 |
-
# Appel au modèle (pipeline image-text-to-text)
|
144 |
-
content = [
|
145 |
-
{"type": "image", "image": image.convert("RGB")},
|
146 |
-
{"type": "text", "text": prompt}
|
147 |
-
]
|
148 |
-
messages = [{"role": "user", "content": content}]
|
149 |
-
response = model(text=messages, max_new_tokens=500)
|
150 |
-
|
151 |
-
# Nettoyage de la barre de progression
|
152 |
-
progress_bar.empty()
|
153 |
-
|
154 |
-
return response[0]['generated_text'] if response and 'generated_text' in response[0] else str(response)
|
155 |
-
except Exception as e:
|
156 |
-
st.error(f"Erreur lors de l'analyse : {str(e)}")
|
157 |
-
return None
|
158 |
|
159 |
-
def
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
""")
|
184 |
-
|
185 |
-
# Chargement du modèle avec gestion d'erreur améliorée
|
186 |
-
with st.spinner("Initialisation de l'application..."):
|
187 |
-
model = load_model()
|
188 |
-
|
189 |
-
if model is None:
|
190 |
-
st.error("""
|
191 |
-
❌ Impossible de charger le modèle. Vérifiez que :
|
192 |
-
- Vous êtes connecté à Internet
|
193 |
-
- Votre token d'API Hugging Face est valide (variable d'environnement HF_TOKEN)
|
194 |
-
- Vous avez accepté les conditions d'utilisation du modèle Gemma 3n
|
195 |
-
- Vous avez suffisamment de mémoire GPU disponible
|
196 |
-
|
197 |
-
Essayez de rafraîchir la page dans quelques instants.
|
198 |
-
""")
|
199 |
-
return
|
200 |
-
|
201 |
-
# Section de téléchargement
|
202 |
-
uploaded_file = display_upload_section()
|
203 |
-
|
204 |
-
if uploaded_file is not None:
|
205 |
-
# Affichage de l'image
|
206 |
-
image = Image.open(uploaded_file)
|
207 |
-
st.image(image, caption='Votre image', use_column_width=True)
|
208 |
-
|
209 |
-
# Bouton d'analyse
|
210 |
-
if st.button("🔍 Analyser l'image", type="primary", use_container_width=True):
|
211 |
-
with st.spinner('Analyse en cours...'):
|
212 |
try:
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
if result:
|
217 |
-
# Affichage des résultats
|
218 |
-
st.markdown("### 🔍 Résultats de l'analyse")
|
219 |
-
st.markdown("---")
|
220 |
-
st.markdown(result)
|
221 |
-
|
222 |
-
# Section de feedback
|
223 |
-
st.markdown("---")
|
224 |
-
st.markdown("### 📝 Votre avis compte !")
|
225 |
-
col1, col2, col3 = st.columns(3)
|
226 |
-
with col2:
|
227 |
-
if st.button("👍 Le diagnostic est pertinent"):
|
228 |
-
st.success("Merci pour votre retour !")
|
229 |
-
if st.button("👎 Le diagnostic est inexact"):
|
230 |
-
st.warning("Merci pour votre retour. Nous allons améliorer notre modèle.")
|
231 |
except Exception as e:
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
else:
|
237 |
-
|
238 |
-
st.markdown("---")
|
239 |
-
st.markdown("### 📸 Exemple d'image attendue")
|
240 |
-
st.image("https://via.placeholder.com/600x400?text=Photo+d%27une+plante+malade",
|
241 |
-
use_column_width=True)
|
242 |
-
st.caption("Exemple : Feuilles de tomate avec des taches brunes")
|
243 |
|
244 |
-
|
245 |
-
st.markdown("---")
|
246 |
-
st.markdown("""
|
247 |
-
<div style="text-align: center; color: #666; font-size: 0.9em;">
|
248 |
-
<p>ℹ️ Ce diagnostic est fourni à titre informatif uniquement.</p>
|
249 |
-
<p>Pour un diagnostic professionnel, consultez un agronome qualifié.</p>
|
250 |
-
<p>Version 1.0.0 | © 2025 AgriLens AI</p>
|
251 |
-
</div>
|
252 |
-
""", unsafe_allow_html=True)
|
253 |
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
|
|
|
|
|
|
263 |
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
st.set_page_config(
|
4 |
+
page_title="AgriLens AI - Plant Disease Diagnosis",
|
5 |
page_icon="🌱",
|
6 |
layout="wide",
|
7 |
initial_sidebar_state="expanded"
|
8 |
)
|
9 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
10 |
+
from PIL import Image
|
11 |
+
import torch
|
12 |
+
import urllib.parse
|
13 |
+
import logging
|
14 |
+
from io import BytesIO
|
15 |
+
from fpdf import FPDF
|
16 |
+
import base64
|
17 |
+
import re
|
18 |
+
|
19 |
+
logging.basicConfig(level=logging.INFO)
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
# --- Mode démo Hugging Face, doit être tout en haut ---
|
23 |
+
IS_DEMO = os.environ.get('HF_SPACE', False) or os.environ.get('DEMO_MODE', False)
|
24 |
+
if IS_DEMO:
|
25 |
+
st.markdown("""<div style='background:#ffe082; padding:1em; border-radius:8px; text-align:center; font-size:1.1em;'>
|
26 |
+
⚠️ <b>Version de démonstration Hugging Face</b> :<br>
|
27 |
+
L’inférence réelle (modèle Gemma 3n) n’est pas disponible en ligne.<br>
|
28 |
+
Pour un diagnostic complet, utilisez la version locale (offline).
|
29 |
+
</div>""", unsafe_allow_html=True)
|
30 |
+
st.image('https://huggingface.co/datasets/mishig/sample_images/resolve/main/tomato_leaf_disease.jpg', width=300, caption='Exemple de feuille malade')
|
31 |
+
st.markdown("""**Exemple de diagnostic généré (démo)** :
|
32 |
+
La feuille présente des taches brunes irrégulières, probablement dues à une maladie fongique.
|
33 |
+
1. Diagnostic précis : Mildiou (stade initial)
|
34 |
+
2. Agent pathogène : Phytophthora infestans
|
35 |
+
3. Mode d’infection : spores transportées par l’eau et le vent
|
36 |
+
4. Conseils : éliminer les feuilles infectées, traiter avec un fongicide à base de cuivre, surveiller l’humidité
|
37 |
+
5. Prévention : rotation des cultures, variétés résistantes
|
38 |
+
""")
|
39 |
+
st.stop()
|
40 |
+
|
41 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
42 |
+
from PIL import Image
|
43 |
+
import torch
|
44 |
+
import urllib.parse
|
45 |
+
import logging
|
46 |
+
from io import BytesIO
|
47 |
+
from fpdf import FPDF
|
48 |
+
import base64
|
49 |
+
import re
|
50 |
+
import os
|
51 |
+
|
52 |
+
logging.basicConfig(level=logging.INFO)
|
53 |
+
logger = logging.getLogger(__name__)
|
54 |
|
55 |
# Style CSS personnalisé
|
56 |
st.markdown("""
|
|
|
82 |
</style>
|
83 |
""", unsafe_allow_html=True)
|
84 |
|
85 |
+
# === Textes multilingues ===
|
86 |
+
UI_TEXTS = {
|
87 |
+
'fr': {
|
88 |
+
'title': "AgriLens AI",
|
89 |
+
'subtitle': "Diagnostic intelligent des maladies des plantes",
|
90 |
+
'summary': "Un outil d'aide à la décision pour les producteurs agricoles",
|
91 |
+
'desc': "Analysez une photo de plante malade et recevez un diagnostic structuré, des conseils pratiques et des recommandations adaptées à votre contexte.",
|
92 |
+
'advantages': [
|
93 |
+
"100% local, aucune donnée envoyée sur Internet",
|
94 |
+
"Conseils adaptés à l'agriculture africaine",
|
95 |
+
"Simple, rapide, accessible à tous"
|
96 |
+
],
|
97 |
+
'step1': "<b>Étape 1 :</b> Uploadez une photo nette de la plante malade",
|
98 |
+
'step2': "<b>Étape 2 :</b> (Optionnel) Ajoutez un contexte ou une question",
|
99 |
+
'step3': "<b>Étape 3 :</b> Cliquez sur <b>Diagnostiquer</b>",
|
100 |
+
'upload_label': "Photo de la plante malade",
|
101 |
+
'context_label': "Contexte ou question (optionnel)",
|
102 |
+
'diagnose_btn': "Diagnostiquer",
|
103 |
+
'warn_no_img': "Veuillez d'abord uploader une image de plante malade.",
|
104 |
+
'diag_in_progress': "Diagnostic en cours... (cela peut prendre jusqu'à 2 minutes sur CPU)",
|
105 |
+
'diag_done': "✅ Diagnostic terminé !",
|
106 |
+
'diag_title': "### 📋 Résultat du diagnostic :",
|
107 |
+
'decision_help': "🧑🌾 Cet outil est une aide à la décision : analysez le diagnostic, adaptez les conseils à votre contexte, et consultez un expert local si besoin.",
|
108 |
+
'share_whatsapp': "Partager sur WhatsApp",
|
109 |
+
'share_facebook': "Partager sur Facebook",
|
110 |
+
'copy_diag': "Copier le diagnostic",
|
111 |
+
'new_diag': "Nouveau diagnostic",
|
112 |
+
'prompt_debug': "🔍 Afficher le prompt utilisé (debug)",
|
113 |
+
'copy_tip': "💡 Conseil : Sélectionnez et copiez le texte ci-dessus pour l'utiliser.",
|
114 |
+
'no_result': "❌ Aucun résultat généré. Le modèle n'a pas produit de réponse.",
|
115 |
+
'lang_select': "Langue / Language"
|
116 |
+
},
|
117 |
+
'en': {
|
118 |
+
'title': "AgriLens AI",
|
119 |
+
'subtitle': "Smart Plant Disease Diagnosis",
|
120 |
+
'summary': "A decision support tool for farmers",
|
121 |
+
'desc': "Analyze a photo of a diseased plant and receive a structured diagnosis, practical advice, and recommendations tailored to your context.",
|
122 |
+
'advantages': [
|
123 |
+
"100% local, no data sent online",
|
124 |
+
"Advice adapted to African agriculture",
|
125 |
+
"Simple, fast, accessible to all"
|
126 |
+
],
|
127 |
+
'step1': "<b>Step 1:</b> Upload a clear photo of the diseased plant",
|
128 |
+
'step2': "<b>Step 2:</b> (Optional) Add context or a question",
|
129 |
+
'step3': "<b>Step 3:</b> Click <b>Diagnose</b>",
|
130 |
+
'upload_label': "Photo of the diseased plant",
|
131 |
+
'context_label': "Context or question (optional)",
|
132 |
+
'diagnose_btn': "Diagnose",
|
133 |
+
'warn_no_img': "Please upload a photo of the diseased plant first.",
|
134 |
+
'diag_in_progress': "Diagnosis in progress... (this may take up to 2 minutes on CPU)",
|
135 |
+
'diag_done': "✅ Diagnosis complete!",
|
136 |
+
'diag_title': "### 📋 Diagnosis result:",
|
137 |
+
'decision_help': "🧑🌾 This tool is a decision support: analyze the diagnosis, adapt the advice to your context, and consult a local expert if needed.",
|
138 |
+
'share_whatsapp': "Share on WhatsApp",
|
139 |
+
'share_facebook': "Share on Facebook",
|
140 |
+
'copy_diag': "Copy diagnosis",
|
141 |
+
'new_diag': "New diagnosis",
|
142 |
+
'prompt_debug': "🔍 Show used prompt (debug)",
|
143 |
+
'copy_tip': "💡 Tip: Select and copy the text above to use it.",
|
144 |
+
'no_result': "❌ No result generated. The model did not produce a response.",
|
145 |
+
'lang_select': "Langue / Language"
|
146 |
+
}
|
147 |
+
}
|
148 |
|
149 |
+
# === Sélecteur de langue et configuration dans la sidebar ===
|
150 |
+
st.sidebar.markdown("## 🌍 Configuration")
|
151 |
+
language = st.sidebar.selectbox(UI_TEXTS['fr']['lang_select'], options=['fr', 'en'], format_func=lambda x: 'Français' if x=='fr' else 'English', key='lang_select_box')
|
152 |
+
T = UI_TEXTS[language]
|
153 |
|
154 |
+
# --- Sélecteur de culture ---
|
155 |
+
cultures = [
|
156 |
+
('tomate', 'Tomate'),
|
157 |
+
('mais', 'Maïs'),
|
158 |
+
('manioc', 'Manioc'),
|
159 |
+
('riz', 'Riz'),
|
160 |
+
('banane', 'Banane'),
|
161 |
+
('cacao', 'Cacao'),
|
162 |
+
('cafe', 'Café'),
|
163 |
+
('igname', 'Igname'),
|
164 |
+
('arachide', 'Arachide'),
|
165 |
+
('coton', 'Coton'),
|
166 |
+
('palmier', 'Palmier à huile'),
|
167 |
+
('ananas', 'Ananas'),
|
168 |
+
('sorgho', 'Sorgho'),
|
169 |
+
('mil', 'Mil'),
|
170 |
+
('patate', 'Patate douce'),
|
171 |
+
('autre', 'Autre')
|
172 |
+
]
|
173 |
+
culture = st.sidebar.selectbox('🌾 Culture concernée', options=[c[0] for c in cultures], format_func=lambda x: dict(cultures)[x], key='culture_select')
|
174 |
|
175 |
+
# --- Champ localisation ---
|
176 |
+
localisation = st.sidebar.text_input('📍 Localisation (région, pays, village...)', key='localisation_input')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
+
# --- Bandeau d'accueil ---
|
179 |
+
st.markdown(f"""
|
180 |
+
<div style='background: linear-gradient(90deg, #2e8b57 0%, #a8e063 100%); padding: 2em 1em; border-radius: 16px; text-align: center;'>
|
181 |
+
<span style='font-size:4em;'>🌱</span><br>
|
182 |
+
<span style='font-size:2.5em; font-weight:bold; color:#fff;'>{T['title']}</span><br>
|
183 |
+
<span style='font-size:1.3em; color:#f0f8ff;'>{T['subtitle']}</span>
|
184 |
+
</div>
|
185 |
+
""", unsafe_allow_html=True)
|
186 |
+
st.markdown(f"""
|
187 |
+
<div style='margin-top:2em; text-align:center;'>
|
188 |
+
<b>{T['summary']}</b><br>
|
189 |
+
<span style='color:#2e8b57;'>{T['desc']}</span>
|
190 |
+
</div>
|
191 |
+
""", unsafe_allow_html=True)
|
192 |
+
st.markdown("""
|
193 |
+
<ul style='margin-top:2em; font-size:1.1em;'>
|
194 |
+
""" + ''.join([f"<li>{adv}</li>" for adv in T['advantages']]) + """
|
195 |
+
</ul>
|
196 |
+
""", unsafe_allow_html=True)
|
197 |
+
|
198 |
+
# --- Instructions étapes ---
|
199 |
+
st.markdown(f"""
|
200 |
+
<div style='margin-top:1em; text-align:center; font-size:1.2em;'>
|
201 |
+
{T['step1']}<br>
|
202 |
+
{T['step2']}<br>
|
203 |
+
{T['step3']}
|
204 |
+
</div>
|
205 |
+
""", unsafe_allow_html=True)
|
206 |
+
|
207 |
+
MODEL_PATH = "models/gemma-3n-transformers-gemma-3n-e2b-it-v1"
|
208 |
+
|
209 |
+
@st.cache_resource(show_spinner=True)
|
210 |
+
def load_gemma_multimodal():
|
211 |
+
processor = AutoProcessor.from_pretrained(MODEL_PATH)
|
212 |
+
model = AutoModelForImageTextToText.from_pretrained(MODEL_PATH).to("cuda" if torch.cuda.is_available() else "cpu")
|
213 |
+
return processor, model
|
214 |
+
|
215 |
+
# Section Exemples (avant l'upload)
|
216 |
+
with st.expander('📸 Exemples (images et prompts)', expanded=False):
|
217 |
+
st.markdown('**Exemple d’image de feuille malade :**')
|
218 |
+
st.image('https://huggingface.co/datasets/mishig/sample_images/resolve/main/tomato_leaf_disease.jpg', width=300, caption='Feuille de tomate malade')
|
219 |
+
st.markdown('**Prompt exemple :**')
|
220 |
+
st.code("Ma culture de tomate présente des taches brunes sur les feuilles, surtout après la pluie. Que faire ?", language=None)
|
221 |
+
st.markdown('Vous pouvez tester l’outil avec cette image et ce prompt.')
|
222 |
+
|
223 |
+
# Responsive: ajuster la largeur des colonnes sur mobile
|
224 |
+
if st.session_state.get('is_mobile', False):
|
225 |
+
col1, col2 = st.columns([1,1])
|
226 |
+
else:
|
227 |
+
col1, col2 = st.columns([2,1])
|
228 |
|
229 |
+
with col1:
|
230 |
+
uploaded_images = st.file_uploader(
|
231 |
+
T['upload_label'] + " (jusqu'à 4 images différentes : feuille, tige, fruit, racine...)",
|
232 |
+
type=["jpg", "jpeg", "png"],
|
233 |
+
key='img_upload',
|
234 |
+
accept_multiple_files=True,
|
235 |
+
help="Vous pouvez sélectionner jusqu'à 4 photos différentes de la même plante."
|
236 |
+
)
|
237 |
+
if uploaded_images:
|
238 |
+
if len(uploaded_images) > 4:
|
239 |
+
st.warning("Vous ne pouvez uploader que 4 images maximum. Seules les 4 premières seront utilisées.")
|
240 |
+
uploaded_images = uploaded_images[:4]
|
241 |
+
for idx, img in enumerate(uploaded_images):
|
242 |
+
st.image(img, width=180, caption=f"Image {idx+1}")
|
243 |
+
with col2:
|
244 |
+
user_prompt = st.text_area(T['context_label'], "", key='context_area')
|
245 |
+
|
246 |
+
# --- Mode rapide dans la sidebar ---
|
247 |
+
st.sidebar.markdown('---')
|
248 |
+
fast_mode = st.sidebar.checkbox('⚡ Mode rapide (réponse courte)', value=False, help="Réduit le temps d'attente en limitant la longueur de la réponse.")
|
249 |
+
max_tokens = 256 if fast_mode else 512
|
250 |
+
|
251 |
+
def resize_image(img, max_size=1024):
|
252 |
+
w, h = img.size
|
253 |
+
if max(w, h) > max_size:
|
254 |
+
scale = max_size / max(w, h)
|
255 |
+
new_size = (int(w*scale), int(h*scale))
|
256 |
+
return img.resize(new_size, Image.LANCZOS)
|
257 |
+
return img
|
258 |
+
|
259 |
+
def process_image_with_gemma_multimodal(images, user_prompt=None, language='fr', fast_mode=True, max_tokens=512, progress=None):
|
260 |
+
processor, model = load_gemma_multimodal()
|
261 |
+
# Adapter le contexte selon la culture et la localisation
|
262 |
+
culture_label = dict(cultures)[culture]
|
263 |
+
loc_str = f" à {localisation}" if localisation else ""
|
264 |
+
if language == 'fr':
|
265 |
+
default_prompt = (
|
266 |
+
f"Vous êtes un expert en phytopathologie et vous conseillez un producteur de {culture_label}{loc_str}.\n"
|
267 |
+
f"Voici {len(images)} image(s) de différentes parties de la plante : " + " ".join(["<image_soft_token>"]*len(images)) + "\n"
|
268 |
+
"Analyse les images et structure ta réponse ainsi :\n"
|
269 |
+
"1. Diagnostic précis (nom de la maladie, gravité, stade)\n"
|
270 |
+
"2. Agent pathogène suspecté (nom scientifique et vulgarisé)\n"
|
271 |
+
"3. Mode d'infection et de transmission (explication simple)\n"
|
272 |
+
"4. Conseils pratiques pour le producteur :\n"
|
273 |
+
" - Mesures immédiates à prendre au champ\n"
|
274 |
+
" - Traitements recommandés (biologiques et chimiques, avec doses précises et mode d'application détaillé, en privilégiant toujours les doses recommandées par le fabricant ou l'expert local)\n"
|
275 |
+
" - Précautions à respecter (protection, délai avant récolte, etc.)\n"
|
276 |
+
"5. Conseils de prévention pour la prochaine saison\n"
|
277 |
+
"Sois synthétique, clair, adapte-toi à un producteur non spécialiste, et termine par un message d'encouragement."
|
278 |
)
|
279 |
+
else:
|
280 |
+
default_prompt = (
|
281 |
+
f"You are a plant disease expert advising a {culture_label} farmer{loc_str}.\n"
|
282 |
+
f"Here are {len(images)} images of different parts of the plant: " + " ".join(["<image_soft_token>"]*len(images)) + "\n"
|
283 |
+
"Analyze the images and structure your answer as follows:\n"
|
284 |
+
"1. Precise diagnosis (disease name, severity, stage)\n"
|
285 |
+
"2. Suspected pathogen (scientific and common name)\n"
|
286 |
+
"3. Infection and transmission mode (simple explanation)\n"
|
287 |
+
"4. Practical advice for the farmer:\n"
|
288 |
+
" - Immediate actions to take in the field\n"
|
289 |
+
" - Recommended treatments (biological and chemical, with precise doses and detailed application method, always favoring the doses recommended by the manufacturer or local expert)\n"
|
290 |
+
" - Precautions to follow (protection, pre-harvest interval, etc.)\n"
|
291 |
+
"5. Prevention tips for the next season\n"
|
292 |
+
"Be clear, concise, adapt your answer to a non-specialist farmer, and end with an encouraging message."
|
293 |
+
)
|
294 |
+
if user_prompt and user_prompt.strip():
|
295 |
+
prompt = user_prompt.strip() + "\n" + default_prompt
|
296 |
+
else:
|
297 |
+
prompt = default_prompt
|
298 |
+
if progress:
|
299 |
+
progress.progress(10, text="🔎 Préparation de l'inférence...")
|
300 |
+
with st.spinner(T['diag_in_progress']):
|
301 |
+
inputs = processor(images=images, text=prompt, return_tensors="pt").to(model.device)
|
302 |
+
if progress:
|
303 |
+
progress.progress(30, text="🧠 Génération de la réponse...")
|
304 |
+
outputs = model.generate(**inputs, max_new_tokens=max_tokens)
|
305 |
+
if progress:
|
306 |
+
progress.progress(90, text="📝 Finalisation...")
|
307 |
+
result = processor.decode(outputs[0], skip_special_tokens=True)
|
308 |
+
return result, prompt
|
309 |
|
310 |
+
def clean_result(result, prompt):
|
311 |
+
# Supprime le prompt recopié en début de réponse
|
312 |
+
if result.strip().startswith(prompt.strip()[:40]):
|
313 |
+
# On coupe tout ce qui précède le premier vrai diagnostic (ex: '1. Diagnostic' ou 'Diagnostic précis')
|
314 |
+
m = re.search(r'(1\.\s*Diagnostic|Diagnostic précis|1\.\s*Precise diagnosis|Precise diagnosis)', result, re.IGNORECASE)
|
315 |
+
if m:
|
316 |
+
return result[m.start():].strip()
|
317 |
+
else:
|
318 |
+
# Sinon, on enlève juste le prompt
|
319 |
+
return result[len(prompt):].strip()
|
320 |
+
return result.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
321 |
|
322 |
+
def clean_for_pdf(text):
|
323 |
+
# Enlève balises HTML et caractères non supportés par FPDF
|
324 |
+
text = re.sub(r'<[^>]+>', '', text)
|
325 |
+
text = text.replace('\r', '').replace('\t', ' ')
|
326 |
+
# FPDF ne supporte pas certains caractères Unicode : on remplace par ?
|
327 |
+
text = ''.join(c if ord(c) < 128 or c in '\n\r' else '?' for c in text)
|
328 |
+
# Tronque si trop long (FPDF limite ~10k caractères)
|
329 |
+
if len(text) > 9000:
|
330 |
+
text = text[:9000] + '\n... [Texte tronqué pour export PDF] ...'
|
331 |
+
return text
|
332 |
+
|
333 |
+
# Historique des diagnostics (stocké en session)
|
334 |
+
if 'history' not in st.session_state:
|
335 |
+
st.session_state['history'] = []
|
336 |
+
|
337 |
+
# Mode expert dans la sidebar
|
338 |
+
expert_mode = st.sidebar.checkbox('🧑🔬 Mode expert', value=False, key='expert_mode')
|
339 |
+
|
340 |
+
# Section Ressources dans la sidebar
|
341 |
+
with st.sidebar.expander('📚 Ressources', expanded=False):
|
342 |
+
st.markdown('''
|
343 |
+
- [Guide maladies du manioc (PDF)](https://www.fao.org/3/i3278f/i3278f.pdf)
|
344 |
+
- [Guide maladies du riz (PDF)](https://www.fao.org/3/y4751f/y4751f.pdf)
|
345 |
+
- [Vidéos YouTube - Diagnostic agricole](https://www.youtube.com/results?search_query=diagnostic+maladies+plantes)
|
346 |
+
- [Contact expert local](mailto:expert@agrilens.ai)
|
347 |
+
''')
|
348 |
|
349 |
+
# --- Alerte GPU ---
|
350 |
+
gpu_ok = torch.cuda.is_available()
|
351 |
+
gpu_name = torch.cuda.get_device_name(0) if gpu_ok else None
|
352 |
+
if gpu_ok:
|
353 |
+
st.success(f"✅ Accélération GPU activée : {gpu_name}")
|
354 |
+
else:
|
355 |
+
st.warning("⚠️ Le GPU n'est pas utilisé pour l'inférence. L'application sera plus rapide sur une machine équipée d'une carte NVIDIA compatible CUDA.")
|
356 |
+
|
357 |
+
|
358 |
+
if st.button(T['diagnose_btn'], type="primary", use_container_width=True):
|
359 |
+
if not uploaded_images or len(uploaded_images) == 0:
|
360 |
+
st.warning(T['warn_no_img'])
|
361 |
+
else:
|
362 |
+
try:
|
363 |
+
images = []
|
364 |
+
for img_file in uploaded_images:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
365 |
try:
|
366 |
+
img = Image.open(img_file).convert("RGB")
|
367 |
+
img = resize_image(img, max_size=1024)
|
368 |
+
images.append(img)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
369 |
except Exception as e:
|
370 |
+
logger.error(f"Erreur lors de l'ouverture d'une image : {e}")
|
371 |
+
st.error(f"❌ Une des images n'a pas pu être lue. Vérifiez le format ou réessayez avec une autre photo.")
|
372 |
+
st.info("💡 Astuce : Utilisez des photos nettes, bien cadrées, sans reflets ni flou.")
|
373 |
+
st.stop()
|
374 |
+
st.info(T['diag_in_progress'])
|
375 |
+
progress = st.progress(0, text="⏳ Analyse en cours...")
|
376 |
+
try:
|
377 |
+
result, prompt_debug = process_image_with_gemma_multimodal(images, user_prompt=user_prompt, language=language, fast_mode=fast_mode, max_tokens=max_tokens, progress=progress)
|
378 |
+
except RuntimeError as e:
|
379 |
+
logger.error(f"Erreur lors du chargement du modèle ou de l'inférence : {e}")
|
380 |
+
st.error("❌ Le modèle n'a pas pu être chargé ou l'inférence a échoué. Vérifiez la mémoire disponible ou réessayez plus tard.")
|
381 |
+
st.info("💡 Astuce : Fermez d'autres applications pour libérer de la RAM, ou redémarrez l'ordinateur.")
|
382 |
+
st.stop()
|
383 |
+
except Exception as e:
|
384 |
+
logger.error(f"Erreur inattendue lors de l'inférence : {e}")
|
385 |
+
st.error("❌ Une erreur inattendue est survenue lors de l'analyse. Veuillez réessayer ou contacter le support.")
|
386 |
+
st.stop()
|
387 |
+
progress.progress(100, text="✅ Analyse terminée")
|
388 |
+
# Nettoyage du résultat pour ne pas afficher le prompt
|
389 |
+
result_clean = clean_result(result, prompt_debug)
|
390 |
+
if result_clean and result_clean.strip():
|
391 |
+
st.session_state['history'].append({
|
392 |
+
'culture': dict(cultures)[culture],
|
393 |
+
'localisation': localisation,
|
394 |
+
'prompt': prompt_debug,
|
395 |
+
'result': result_clean
|
396 |
+
})
|
397 |
+
st.success(T['diag_done'])
|
398 |
+
st.markdown(T['diag_title'])
|
399 |
+
st.markdown(result_clean)
|
400 |
+
st.info(T['decision_help'])
|
401 |
+
share_text = urllib.parse.quote(f"Diagnostic AgriLens AI :\n{result_clean}")
|
402 |
+
st.sidebar.markdown(f"""
|
403 |
+
<div style='margin-top:1em; display:flex; flex-direction:column; gap:0.7em;'>
|
404 |
+
<a href='https://wa.me/?text={share_text}' target='_blank' style='background:#25D366; color:#fff; padding:0.5em 1.2em; border-radius:6px; text-decoration:none; font-weight:bold; display:block; text-align:center;'>{T['share_whatsapp']}</a>
|
405 |
+
<a href='https://www.facebook.com/sharer/sharer.php?u="e={share_text}' target='_blank' style='background:#4267B2; color:#fff; padding:0.5em 1.2em; border-radius:6px; text-decoration:none; font-weight:bold; display:block; text-align:center;'>{T['share_facebook']}</a>
|
406 |
+
<button onclick=\"navigator.clipboard.writeText(decodeURIComponent('{share_text}'))\" style='background:#2e8b57; color:#fff; padding:0.5em 1.2em; border:none; border-radius:6px; font-weight:bold; cursor:pointer; width:100%;'>{T['copy_diag']}</button>
|
407 |
+
<button onclick=\"window.location.reload();\" style='background:#a8e063; color:#2e8b57; font-size:1.1em; padding:0.6em 2em; border:none; border-radius:8px; cursor:pointer; width:100%; margin-top:0.7em;'>{T['new_diag']}</button>
|
408 |
+
</div>
|
409 |
+
""", unsafe_allow_html=True)
|
410 |
+
# PDF robuste avec nettoyage
|
411 |
+
def create_pdf(text):
|
412 |
+
pdf = FPDF()
|
413 |
+
pdf.add_page()
|
414 |
+
pdf.set_font("Arial", size=12)
|
415 |
+
for line in text.split('\n'):
|
416 |
+
pdf.multi_cell(0, 10, line)
|
417 |
+
pdf_bytes = BytesIO()
|
418 |
+
pdf.output(pdf_bytes)
|
419 |
+
pdf_bytes.seek(0)
|
420 |
+
return pdf_bytes.read()
|
421 |
+
try:
|
422 |
+
pdf_data = create_pdf(clean_for_pdf(result_clean))
|
423 |
+
st.download_button(
|
424 |
+
label="⬇️ Télécharger le diagnostic en PDF",
|
425 |
+
data=pdf_data,
|
426 |
+
file_name="diagnostic_agri.pdf",
|
427 |
+
mime="application/pdf",
|
428 |
+
use_container_width=True
|
429 |
+
)
|
430 |
+
except Exception as e:
|
431 |
+
logger.error(f"Erreur lors de la génération du PDF : {e}")
|
432 |
+
st.error("❌ L'export PDF a échoué. Veuillez réessayer ou contacter le support.")
|
433 |
+
# Mode expert, etc. inchangés
|
434 |
+
if expert_mode:
|
435 |
+
st.markdown('---')
|
436 |
+
st.markdown('**Prompt complet envoyé au modèle :**')
|
437 |
+
st.code(prompt_debug, language=None)
|
438 |
+
st.markdown('**Annotation / Correction :**')
|
439 |
+
st.text_area('Ajouter une note ou une correction (optionnel)', key=f'annot_{len(st.session_state["history"])}')
|
440 |
+
st.info(T['copy_tip'])
|
441 |
+
else:
|
442 |
+
st.error(T['no_result'])
|
443 |
+
st.info("💡 Astuce : Essayez une photo plus nette ou un autre angle de la plante.")
|
444 |
+
except Exception as e:
|
445 |
+
logger.error(f"Erreur critique : {e}")
|
446 |
+
st.error("❌ Une erreur critique est survenue. Veuillez réessayer ou contacter le support technique.")
|
447 |
+
|
448 |
+
# --- Historique des diagnostics ---
|
449 |
+
with st.expander('🗂️ Historique des diagnostics', expanded=False):
|
450 |
+
if st.session_state['history']:
|
451 |
+
import pandas as pd
|
452 |
+
hist_df = pd.DataFrame(st.session_state['history'])
|
453 |
+
st.dataframe(hist_df[['culture', 'localisation', 'result']], use_container_width=True)
|
454 |
+
csv = hist_df.to_csv(index=False).encode('utf-8')
|
455 |
+
st.download_button('⬇️ Télécharger l’historique (CSV)', data=csv, file_name='historique_diagnostics.csv', mime='text/csv')
|
456 |
else:
|
457 |
+
st.info('Aucun diagnostic enregistré pour le moment.')
|
|
|
|
|
|
|
|
|
|
|
458 |
|
459 |
+
st.divider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
460 |
|
461 |
+
# Sidebar : bouton Aide/FAQ
|
462 |
+
with st.sidebar.expander('❓ Aide / FAQ', expanded=False):
|
463 |
+
st.markdown('''
|
464 |
+
- **Comment obtenir un bon diagnostic ?**
|
465 |
+
- Prenez une photo nette, bien éclairée, sans flou ni reflets.
|
466 |
+
- Décrivez le contexte (culture, symptômes, conditions météo).
|
467 |
+
- **Le diagnostic ne correspond pas ?**
|
468 |
+
- Essayez une autre photo ou reformulez votre question.
|
469 |
+
- **Problème technique ?**
|
470 |
+
- Redémarrez l’application ou contactez le support :
|
471 |
+
- 📧 [support@agrilens.ai](mailto:support@agrilens.ai)
|
472 |
+
''')
|
473 |
|
474 |
+
# --- Pied de page / Footer ---
|
475 |
+
st.markdown("""
|
476 |
+
<hr style='margin-top:2em; margin-bottom:0.5em; border:1px solid #e0e0e0;'>
|
477 |
+
<div style='text-align:center; font-size:1em; color:#888;'>
|
478 |
+
<b>AgriLens AI</b> – © 2024 Sidoine YEBADOKPO<br>
|
479 |
+
Expert en analyse de données, Développeur Web<br>
|
480 |
+
<a href='mailto:syebadokpo@gmail.com'>syebadokpo@gmail.com</a> · <a href='https://linkedin.com/in/sidoineko' target='_blank'>LinkedIn</a> · <a href='https://huggingface.co/Sidoineko/portfolio' target='_blank'>Hugging Face</a><br>
|
481 |
+
<span style='font-size:0.95em;'>🇫🇷 Application créée par Sidoine YEBADOKPO | 🇬🇧 App created by Sidoine YEBADOKPO</span>
|
482 |
+
</div>
|
483 |
+
""", unsafe_allow_html=True)
|
start.sh
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# AgriLens AI - Script d'installation et de lancement automatisé
|
3 |
+
# 🇫🇷 Ce script prépare l'environnement et lance l'application (Linux/Mac)
|
4 |
+
# 🇬🇧 This script sets up the environment and launches the app (Linux/Mac)
|
5 |
+
|
6 |
+
set -e
|
7 |
+
|
8 |
+
# Vérification du modèle local
|
9 |
+
MODEL_DIR="models/gemma-3n"
|
10 |
+
if [ ! -d "$MODEL_DIR" ]; then
|
11 |
+
echo "[FR] Le dossier du modèle ($MODEL_DIR) est manquant. Placez les fichiers Gemma 3n dans ce dossier."
|
12 |
+
echo "[EN] Model folder ($MODEL_DIR) is missing. Please put Gemma 3n files in this folder."
|
13 |
+
exit 1
|
14 |
+
fi
|
15 |
+
|
16 |
+
# Création de l'environnement virtuel
|
17 |
+
if [ ! -d "venv" ]; then
|
18 |
+
python3 -m venv venv
|
19 |
+
fi
|
20 |
+
source venv/bin/activate
|
21 |
+
|
22 |
+
# Installation des dépendances
|
23 |
+
pip install --upgrade pip
|
24 |
+
pip install -r requirements.txt
|
25 |
+
|
26 |
+
# Lancement de l'application
|
27 |
+
streamlit run src/streamlit_app.py
|