Spaces:
Sleeping

File size: 8,929 Bytes
bcda16e
 
 
 
 
 
 
 
ec07b6a
bcda16e
 
 
 
 
ec07b6a
 
 
b6221ac
 
ec07b6a
 
 
 
 
 
 
 
 
 
 
 
b6221ac
ec07b6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6221ac
bcda16e
ec07b6a
bcda16e
ec07b6a
 
bcda16e
 
 
 
ec07b6a
 
 
 
 
 
 
 
 
 
 
b6221ac
ec07b6a
 
 
 
 
 
 
 
 
 
 
bcda16e
b6221ac
bcda16e
ec07b6a
bcda16e
b6221ac
bcda16e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6221ac
 
 
 
 
 
 
bcda16e
 
 
 
 
ec07b6a
 
 
bcda16e
 
 
 
b6221ac
 
bcda16e
b6221ac
ec07b6a
 
 
 
 
bcda16e
 
ec07b6a
 
 
 
 
 
 
 
 
 
 
 
 
 
bcda16e
 
ec07b6a
b6221ac
 
 
 
 
 
 
 
 
ec07b6a
 
 
 
b6221ac
ec07b6a
bcda16e
ec07b6a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
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")])