import gradio as gr import numpy as np import tensorflow as tf import pandas as pd import os import zipfile import shutil # Load the model directly from the Space environment model_path = 'sugarcane_20_epoch_model.keras' model = tf.keras.models.load_model(model_path) class_names = ['Healthy', 'Mosaic', 'RedRot', 'Rust', 'Yellow'] # --- Comprehensive Agronomy Knowledge Database --- disease_analytics = { 'Healthy': { "status": "🟢 OPTIMAL HEALTH", "danger": "No active threat profile.", "symptoms": "Vibrant green leaves, uniform growth, robust stalks, and no unusual spotting or striping.", "cause": "Good soil nutrition, balanced moisture control, and effective field management.", "action": "Continue current irrigation schedules, monitor soil pH weekly, and sustain routine nitrogen-phosphorus-potassium (NPK) feeding." }, 'Mosaic': { "status": "🔴 HIGH RISK (Viral)", "danger": "Can cause up to 20-40% yield loss; spreads rapidly via insect vectors.", "symptoms": "Mottled patterns of alternating dark green and yellowish-green patches or stripes on the foliage.", "cause": "Sugarcane Mosaic Virus (SCMV), primarily spread by aphids or contaminated pruning tools.", "action": "Immediately rogue out and safely burn infected plants. Control aphid populations using targeted organic or chemical insecticides. Clean all machinery between field sections." }, 'RedRot': { "status": "🚨 CRITICAL EXTREME (Fungal)", "danger": "Known as the 'Cancer of Sugarcane'. Can destroy entire fields if unchecked.", "symptoms": "Reddish spots along the leaf midribs. Stalk interiors show blood-red tissue bleeding inward with white patches.", "cause": "Colletotrichum falcatum fungus, thriving in waterlogged, warm environments.", "action": "Uproot infected crop clusters immediately to avoid spore spread. Improve field drainage systems drastically. Apply recommended copper-based fungicides to surrounding blocks." }, 'Rust': { "status": "🟠 MEDIUM RISK (Fungal)", "danger": "Reduces photosynthetic capacity, leading to smaller, thinner cane stalks.", "symptoms": "Elongated, powdery, rust-colored pustules on the undersides of leaves that rupture over time.", "cause": "Puccinia melanocephala fungus, spreading through airborne wind currents and high humidity.", "action": "Avoid overhead sprinkler irrigation to keep leaves dry. Apply a preventative triazole or strobilurin fungicide spray at the first sign of spread." }, 'Yellow': { "status": "🔴 HIGH RISK (Phytoplasma/Viral)", "danger": "Causes severe stunting of the cane and ruins sugar extraction levels.", "symptoms": "Bright yellowing of the midrib while the blade remains green, eventually spreading until the leaf dries completely.", "cause": "Sugarcane Yellow Leaf Virus (SCYLV), transmitted through cane aphids.", "action": "Eliminate insect vectors using systemic insecticides. For future plantings, strictly source certified disease-free seed cane tissue." } } total_single_images_analyzed = 0 total_zip_folders_processed = 0 # Single Prediction Logic def predict_single_leaf(input_image): global total_single_images_analyzed if input_image is None: return None, "", gr.update() img = tf.image.resize(input_image, (224, 224)) img_array = tf.expand_dims(img, 0) predictions = model.predict(img_array, verbose=0) scores = predictions[0] highest_idx = np.argmax(scores) predicted_label = class_names[highest_idx] total_single_images_analyzed += 1 analytics_text = f"📊 **Session Overview:** Total Single Images Scanned: `{total_single_images_analyzed}` | Bulk Zips Unpacked: `{total_zip_folders_processed}`" info = disease_analytics[predicted_label] report_markdown = f""" ### 📋 Agronomy Field Report for **{predicted_label}** * **Health Alert Level:** {info['status']} * **Biological Threat Profile:** {info['danger']} --- 🔍 **Clinical Field Symptoms:** {info['symptoms']} 🦠 **Primary Biological Cause:** {info['cause']} 🛠️ **Immediate Counter-Measures & Action Plan:** {info['action']} """ result_probabilities = {class_names[i]: float(scores[i]) for i in range(5)} return result_probabilities, report_markdown, analytics_text # Updated Mass Zip Logic to return BOTH a download file AND an onscreen DataFrame Table def predict_bulk_zip(zip_file): global total_zip_folders_processed if zip_file is None: return None, None, gr.update() extract_dir = "./temp_mass_images" if os.path.exists(extract_dir): shutil.rmtree(extract_dir) os.makedirs(extract_dir) with zipfile.ZipFile(zip_file.name, 'r') as zip_ref: zip_ref.extractall(extract_dir) results = [] for root, dirs, files in os.walk(extract_dir): for filename in files: if filename.lower().endswith(('.png', '.jpg', '.jpeg')): img_path = os.path.join(root, filename) try: img = tf.keras.utils.load_img(img_path, target_size=(224, 224)) img_array = tf.keras.utils.img_to_array(img) img_array = tf.expand_dims(img_array, 0) predictions = model.predict(img_array, verbose=0) scores = predictions[0] highest_idx = np.argmax(scores) results.append({ "File Name": filename, "Final Diagnosis": class_names[highest_idx], "Max Confidence": f"{(scores[highest_idx] * 100):.2f}%", "Healthy %": f"{(scores[0] * 100):.2f}%", "Mosaic %": f"{(scores[1] * 100):.2f}%", "RedRot %": f"{(scores[2] * 100):.2f}%", "Rust %": f"{(scores[3] * 100):.2f}%", "Yellow %": f"{(scores[4] * 100):.2f}%" }) except Exception: continue shutil.rmtree(extract_dir) total_zip_folders_processed += 1 analytics_text = f"📊 **Session Overview:** Total Single Images Scanned: `{total_single_images_analyzed}` | Bulk Zips Unpacked: `{total_zip_folders_processed}`" if results: df = pd.DataFrame(results) report_path = "./mass_detection_report.csv" df.to_csv(report_path, index=False) return report_path, df, analytics_text return None, None, analytics_text # --- Interface Layout --- with gr.Blocks(theme=gr.themes.Soft(), title="Sugarcane Enterprise Dashboard") as app: gr.Markdown("# 🌾 Sugarcane Leaf AI Intelligence Hub") gr.Markdown("Identify crop anomalies instantly using deep computer vision models.") analytics_banner = gr.Markdown("📊 **Session Overview:** Total Single Images Scanned: `0` | Bulk Zips Unpacked: `0`") with gr.Tab("Single Leaf Diagnostics"): gr.Markdown("### 📸 Image Scanner") with gr.Row(): with gr.Column(): image_input = gr.Image(label="Drop Leaf Photograph Here") image_button = gr.Button("Execute AI Diagnostic Run", variant="primary") with gr.Column(): label_output = gr.Label(num_top_classes=3, label="Top AI Confidence Matches") report_output = gr.Markdown("### 📋 Diagnostic Insights\n*Upload an image above and tap execute to generate field reports.*") image_button.click( fn=predict_single_leaf, inputs=image_input, outputs=[label_output, report_output, analytics_banner] ) with gr.Tab("Mass Bulk Detection (Zip Folder)"): gr.Markdown("### 📁 Batch Processing Engine") with gr.Row(): with gr.Column(scale=1): file_input = gr.File(file_types=[".zip"], label="Upload Unlabeled Leaf Folder (.zip)") file_button = gr.Button("Initialize Batch Processing", variant="primary") file_output = gr.File(label="Download Generated Diagnostics Report (.csv)") with gr.Column(scale=2): gr.Markdown("### 📊 On-Screen Batch Analysis Breakdown") # New Gradio Dataframe component to render the table live on screen! table_output = gr.Dataframe(interactive=False, label="All Image Percentages Overview") file_button.click( fn=predict_bulk_zip, inputs=file_input, outputs=[file_output, table_output, analytics_banner] ) app.launch(auth=[("admin", "sugarcane2026")])