import gradio as gr import requests import os import google.generativeai as genai # --- 1. SETUP GEMINI BOT --- genai.configure(api_key=os.environ.get("GEMINI_API_KEY")) chat_model = genai.GenerativeModel("gemini-2.5-flash") # --- 2. SETUP HUGGING FACE SCANNER --- HF_API_URL = "https://api-inference.huggingface.co/models/Daksh159/plant-disease-mobilenetv2" def detect_disease(image_path): if image_path is None: return "Please upload an image." hf_token = os.environ.get("HF_TOKEN") headers = {} if hf_token: headers["Authorization"] = f"Bearer {hf_token}" else: return "Error: HF_TOKEN secret is missing. Please check your Space settings." try: with open(image_path, "rb") as f: data = f.read() response = requests.post(HF_API_URL, headers=headers, data=data) # --- THE FIX: Catch the exact error from Hugging Face --- if response.status_code != 200: return f"API Error ({response.status_code}): Hugging Face says '{response.text}'. (If it says 503, the model is just waking up. Try again in 30 seconds!)" result = response.json() # Check if it's a list (which is the successful format) if isinstance(result, list) and len(result) > 0: disease = result[0].get("label", "Unknown Disease") confidence = result[0].get("score", 0) return f"🌿 Detected: {disease}\n🎯 Confidence: {confidence:.2%}" elif "error" in result: return f"⏳ Model is warming up: {result['error']}" else: return "Could not identify the disease. Try a clearer image." except Exception as e: return f"Code error: {str(e)}" def chat_with_agribot(message, history): try: prompt = f"You are AgriBot, an expert agricultural AI assistant. Answer this user's question clearly and concisely: {message}" response = chat_model.generate_content(prompt) return response.text except Exception as e: return f"Chatbot error: {str(e)}" # --- 3. BUILD THE USER INTERFACE --- with gr.Blocks(theme=gr.themes.Soft(primary_hue="green")) as demo: gr.Markdown("# 🌿 AgriScan: AI Plant Disease Detection & Assistant") gr.Markdown("Upload a photo of a sick plant leaf to diagnose the issue, or ask AgriBot for farming advice!") with gr.Row(): with gr.Column(): gr.Markdown("### 📸 1. Disease Scanner") image_input = gr.Image(type="filepath", label="Upload Leaf Image") scan_btn = gr.Button("Scan for Disease", variant="primary") scan_result = gr.Textbox(label="Diagnosis Result", lines=3) scan_btn.click(fn=detect_disease, inputs=image_input, outputs=scan_result) with gr.Column(): gr.Markdown("### 🤖 2. AgriBot Assistant") gr.ChatInterface(fn=chat_with_agribot) demo.launch()