Spaces:
Sleeping
Sleeping
Download app.py from DATASUREAPP/Viticare_Expert: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/DATASUREAPP/Viticare_Expert/resolve/main/app.py
- Command line
-
hf download hf://spaces/DATASUREAPP/Viticare_Expert/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DATASUREAPP/Viticare_Expert/resolve/main/app.py
11 kB
| import gradio as gr | |
| import cv2, os, requests, piexif, folium, csv | |
| import matplotlib.pyplot as plt | |
| from PIL import Image | |
| from ultralytics import YOLO | |
| from geopy.geocoders import Nominatim | |
| from huggingface_hub import InferenceClient | |
| from datetime import datetime | |
| import pandas as pd | |
| # --- CONFIGURATION & RAG --- | |
| DOCS_PATH = "docs_vigne" | |
| CSV_FILE = "suivi_diagnostics.csv" | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| client = InferenceClient(api_key=HF_TOKEN) | |
| model = YOLO('best.pt') | |
| # --- INITIALISATION RAG (Une seule fois au démarrage) --- | |
| from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_community.vectorstores import Chroma | |
| def init_rag(): | |
| if os.path.exists(DOCS_PATH) and os.listdir(DOCS_PATH): | |
| try: | |
| loader = DirectoryLoader(DOCS_PATH, glob="./*.pdf", loader_cls=PyPDFLoader) | |
| docs = loader.load() | |
| splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) | |
| texts = splitter.split_documents(docs) | |
| embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") | |
| return Chroma.from_documents(texts, embeddings) | |
| except: return None | |
| return None | |
| vector_db = init_rag() | |
| # --- FONCTIONS TECHNIQUES --- | |
| def get_metadata(img_path): | |
| """Extrait GPS et Date de la photo""" | |
| try: | |
| exif = piexif.load(img_path) | |
| lat, lon, gps_found = 44.8378, -0.5792, False | |
| date_photo = datetime.now().strftime("%Y-%m-%d") | |
| if "GPS" in exif and len(exif["GPS"]) > 4: | |
| def to_dec(v): return (v[0][0]/v[0][1]) + (v[1][0]/v[1][1])/60 + (v[2][0]/v[2][1])/3600 | |
| lat, lon, gps_found = to_dec(exif["GPS"][2]), to_dec(exif["GPS"][4]), True | |
| if "0th" in exif and piexif.ImageIFD.DateTime in exif["0th"]: | |
| date_str = exif["0th"][piexif.ImageIFD.DateTime].decode('utf-8') | |
| date_photo = datetime.strptime(date_str[:10], "%Y:%m:%d").strftime("%Y-%m-%d") | |
| return lat, lon, gps_found, date_photo | |
| except: | |
| return 44.8378, -0.5792, False, datetime.now().strftime("%Y-%m-%d") | |
| def get_weather_extended(lat, lon): | |
| """Récupère météo historique et prévisions""" | |
| try: | |
| url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&daily=temperature_2m_max,relative_humidity_2m_max&past_days=7&timezone=auto" | |
| r = requests.get(url).json() | |
| return r['daily']['time'], r['daily']['temperature_2m_max'], r['daily']['relative_humidity_2m_max'] | |
| except: return [], [], [] | |
| def create_full_plot(dates, temps, hums, target_date): | |
| """Graphique Température + Humidité""" | |
| if not dates: return None | |
| fig, ax1 = plt.subplots(figsize=(10, 4)) | |
| dates_short = [d.split('-')[2]+'/'+d.split('-')[1] for d in dates] | |
| # Température (Ligne) | |
| ax1.plot(dates_short, temps, color='#4b0082', marker='o', linewidth=2, label="Temp Max (°C)") | |
| ax1.set_ylabel('Température (°C)', color='#4b0082', fontweight='bold') | |
| # Humidité (Barres) | |
| ax2 = ax1.twinx() | |
| ax2.bar(dates_short, hums, color='#9370DB', alpha=0.3, label="Humidité (%)") | |
| ax2.set_ylabel('Humidité (%)', color='#9370DB', fontweight='bold') | |
| ax2.set_ylim(0, 100) | |
| try: | |
| idx = dates.index(target_date) | |
| ax1.axvline(x=idx, color='#FFD700', linestyle='--', label="Date Capture") | |
| except: pass | |
| plt.title("Historique Météo : Température & Humidité", fontweight='bold') | |
| fig.tight_layout() | |
| return fig | |
| def call_mistral_rag(maladie, temp, hum, lat, lon): | |
| """Appel IA Mistral avec RAG""" | |
| rag_info = "" | |
| if vector_db: | |
| try: | |
| docs = vector_db.similarity_search(maladie, k=2) | |
| rag_info = "\nDocs techniques: " + " ".join([d.page_content for d in docs]) | |
| except: pass | |
| try: | |
| prompt = f"Expert agronome. Maladie: {maladie}. Météo: {temp}°C, {hum}% hum. {rag_info}. RÉPONDS EN FRANÇAIS. Conseil court." | |
| resp = client.chat_completion(model="mistralai/Mistral-7B-Instruct-v0.2", messages=[{"role": "user", "content": prompt}], max_tokens=200) | |
| return resp.choices[0].message.content.strip() | |
| except: return "Conseil indisponible." | |
| def save_to_csv(data_dict): | |
| """Enregistre dans le fichier CSV""" | |
| file_exists = os.path.isfile(CSV_FILE) | |
| with open(CSV_FILE, mode='a', newline='', encoding='utf-8') as f: | |
| writer = csv.DictWriter(f, fieldnames=data_dict.keys()) | |
| if not file_exists: writer.writeheader() | |
| writer.writerow(data_dict) | |
| # --- LOGIQUE ANALYSE --- | |
| def analyze_vigne(image_path, city_manual): | |
| # 1. Localisation et Date | |
| lat, lon, gps_found, date_photo = get_metadata(image_path) | |
| if city_manual: | |
| try: | |
| loc = Nominatim(user_agent="viticare").geocode(city_manual) | |
| if loc: lat, lon = loc.latitude, loc.longitude | |
| except: pass | |
| # 2. Météo et Graphique | |
| dates, temps, hums = get_weather_extended(lat, lon) | |
| weather_plot = create_full_plot(dates, temps, hums, date_photo) | |
| # 3. Calcul des indices de risques agronomiques | |
| risks_dict = calculate_disease_risks(dates, temps, hums) | |
| # Construction du texte d'affichage des risques | |
| risks_md = "📊 **Indices de Risques Climatiques :**\n" | |
| for disease, level in risks_dict.items(): | |
| risks_md += f"- {disease} : {level}\n" | |
| # 4. Détection Vision (YOLO) | |
| results = model.predict(image_path, conf=0.25) | |
| img_res = results[0].plot() | |
| img_pil = Image.fromarray(cv2.cvtColor(img_res, cv2.COLOR_BGR2RGB)) | |
| conf_score = float(results[0].boxes.conf[0]) if len(results[0].boxes) > 0 else 0.0 | |
| label = results[0].names[int(results[0].boxes[0].cls)] if len(results[0].boxes) > 0 else "Saine" | |
| # 5. Météo au moment de la photo et Conseil IA | |
| # temps[7] correspond à J-0 (aujourd'hui/date cible) dans Open-Meteo past_days=7 | |
| curr_t, curr_h = (temps[7], hums[7]) if len(temps)>7 else (20, 50) | |
| advice = call_mistral_rag(label, curr_t, curr_h, lat, lon) | |
| # 6. Préparation des données pour le CSV | |
| data_to_save = { | |
| "timestamp_analyse": datetime.now().strftime("%Y-%m-%d %H:%M"), | |
| "date_photo": date_photo, | |
| "coordonnees": f"{lat},{lon}", | |
| "diagnostic": label, | |
| "confiance_yolo": f"{conf_score:.2f}", | |
| "temp_photo": curr_t, | |
| "hum_photo": curr_h, | |
| "recommandation_mistral": advice.replace("\n", " "), | |
| "risques_climatiques": str(risks_dict), # Sauvegarde des 5 risques calculés | |
| "feedback_utilisateur": "" | |
| } | |
| # Formatage final du texte Markdown pour l'UI | |
| full_output_text = f"## {label.upper()}\n\n{risks_md}\n\n💡 **Conseil Expert :** {advice}" | |
| return img_pil, weather_plot, full_output_text, data_to_save | |
| def calculate_disease_risks(dates, temps, hums): | |
| risks = { | |
| "Mildiou": "Faible", | |
| "Black Rot": "Faible", | |
| "Escoriose": "Faible", | |
| "Black Measles": "Faible", | |
| "Flavescence Dorée": "Faible" | |
| } | |
| if not temps or not hums: return risks | |
| # On analyse les 3 derniers jours de l'historique | |
| recent_t = temps[5:8] | |
| recent_h = hums[5:8] | |
| avg_t = sum(recent_t) / len(recent_t) | |
| avg_h = sum(recent_h) / len(recent_h) | |
| # Logique Mildiou | |
| if avg_t > 11 and avg_h > 75: risks["Mildiou"] = "ÉLEVÉ 🚨" | |
| elif avg_t > 10 and avg_h > 60: risks["Mildiou"] = "Modéré ⚠️" | |
| # Logique Black Rot | |
| if 15 < avg_t < 25 and avg_h > 70: risks["Black Rot"] = "ÉLEVÉ 🚨" | |
| # Logique Escoriose | |
| if 8 < avg_t < 18 and avg_h > 80: risks["Escoriose"] = "ÉLEVÉ 🚨" | |
| # Logique Black Measles (Esca) - Lié à la chaleur | |
| if max(recent_t) > 30: risks["Black Measles"] = "ÉLEVÉ (Stress thermique) 🚨" | |
| # Logique Flavescence Dorée | |
| if avg_t > 22: risks["Flavescence Dorée"] = "Modéré (Vecteurs actifs) ⚠️" | |
| return risks | |
| def finalize_feedback(vote, data): | |
| if not data: return "Faites d'abord une analyse." | |
| data["feedback_utilisateur"] = vote | |
| save_to_csv(data) | |
| return f"✅ Diagnostic marqué comme **{vote}**. Données enregistrées dans `{CSV_FILE}`." | |
| # --- INTERFACE GRADIO --- | |
| css = ".gradio-container {background-color: #4b0082;} .contain {background-color: white !important; border-radius: 15px; padding: 20px;}" | |
| # --- NOUVELLE FONCTION POUR L'AFFICHAGE --- | |
| def get_csv_data(): | |
| if os.path.exists(CSV_FILE): | |
| # On lit le CSV et on retourne le chemin du fichier ET les 5 dernières lignes | |
| df = pd.read_csv(CSV_FILE) | |
| return CSV_FILE, df.tail(5) | |
| return None, None | |
| # ... (Garder tout ton début de code identique jusqu'à l'interface) ... | |
| # --- INTERFACE GRADIO MISE À JOUR --- | |
| with gr.Blocks(css=css, title="Viticare Expert AI") as demo: | |
| gr.HTML("<h1 style='color:white; text-align:center;'>🍇 Viticare Expert & Data Collector</h1>") | |
| analysis_state = gr.State() | |
| # TOUT CE BLOC DOIT ÊTRE DÉCALÉ (INDENTÉ) VERS LA DROITE : | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_img = gr.Image( | |
| type="filepath", | |
| label="📸 Photo de la feuille", | |
| sources=["webcam", "upload"], | |
| streaming=False # Optionnel : aide à la stabilité | |
| ) | |
| input_city = gr.Textbox(label="📍 Ville (Si pas de GPS)") | |
| btn_run = gr.Button("🚀 ANALYSER LA VIGNE", variant="primary") | |
| with gr.Column(): | |
| output_img = gr.Image(label="Analyse Vision") | |
| output_plot = gr.Plot(label="Historique Météo") | |
| with gr.Row(): | |
| output_text = gr.Markdown() | |
| with gr.Row(): | |
| gr.Markdown("### 🗳️ Ce diagnostic est-il correct ?") | |
| btn_like = gr.Button("👍 OUI", variant="secondary") | |
| btn_dislike = gr.Button("👎 NON", variant="secondary") | |
| output_status = gr.Markdown() | |
| # --- NOUVELLE SECTION : GESTION DES DONNÉES --- | |
| gr.Markdown("---") | |
| gr.Markdown("### 📥 Extraction & Historique des données") | |
| with gr.Row(): | |
| btn_refresh_csv = gr.Button("🔄 ACTUALISER L'HISTORIQUE") | |
| csv_file_download = gr.File(label="Télécharger le fichier complet") | |
| output_dataframe = gr.DataFrame(label="Derniers diagnostics enregistrés", interactive=False) | |
| # Événements (Eux aussi doivent être bien indentés) | |
| btn_run.click(analyze_vigne, [input_img, input_city], [output_img, output_plot, output_text, analysis_state]) | |
| btn_like.click(finalize_feedback, [gr.State("Valide"), analysis_state], output_status) | |
| btn_dislike.click(finalize_feedback, [gr.State("Invalide"), analysis_state], output_status) | |
| btn_refresh_csv.click(get_csv_data, outputs=[csv_file_download, output_dataframe]) | |
| if __name__ == "__main__": | |
| demo.launch() |