Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines15161718192021226 unmodified lines2930313233343515 unmodified lines51525354555657585960617 unmodified lines697071727374757677787980818283846 unmodified lines91929394959697989910010119 unmodified lines1211221231241251261271281291301311321331341 unmodified line13613713813914014114214314414514614718 unmodified lines16616716816917017117217317417517617717817918014 unmodified lines# --- Comprehensive Agronomy Knowledge Database ---disease_analytics = {'Healthy': {"status": "π’ OPTIMAL","danger": "None","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."6 unmodified lines"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 Disease)","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.",15 unmodified lines}}# --- Analytics Session Counter States ---total_single_images_analyzed = 0total_zip_folders_processed = 0# Single Prediction Logic with Text Report Outputdef predict_single_leaf(input_image):global total_single_images_analyzedif input_image is None:7 unmodified lineshighest_idx = np.argmax(scores)predicted_label = class_names[highest_idx]# Increment tracking metricstotal_single_images_analyzed += 1analytics_text = f"π **Session Overview:** Total Single Images Scanned: `{total_single_images_analyzed}` | Bulk Zips Unpacked: `{total_zip_folders_processed}`"# Fetch diagnostic details from our databaseinfo = disease_analytics[predicted_label]report_markdown = f"""### π Agronomy Field Report for **{predicted_label}*** **Health Alert Level:** {info['status']}* **Estimated Danger Profile:** {info['danger']}---π **Clinical Field Symptoms:** {info['symptoms']}6 unmodified linesresult_probabilities = {class_names[i]: float(scores[i]) for i in range(5)}return result_probabilities, report_markdown, analytics_text# Mass Zip Logicdef predict_bulk_zip(zip_file):global total_zip_folders_processedif zip_file is None:return None, gr.update()extract_dir = "./temp_mass_images"if os.path.exists(extract_dir):19 unmodified linesresults.append({"File Name": filename,"Predicted Diagnosis": class_names[highest_idx],"Confidence Level": f"{(scores[highest_idx] * 100):.2f}%"})except Exception:continueshutil.rmtree(extract_dir)total_zip_folders_processed += 1analytics_text = f"π **Session Overview:** Total Single Images Scanned: `{total_single_images_analyzed}` | Bulk Zips Unpacked: `{total_zip_folders_processed}`"1 unmodified linedf = pd.DataFrame(results)report_path = "./mass_detection_report.csv"df.to_csv(report_path, index=False)return report_path, analytics_textreturn None, analytics_text# =====================================================================# BUILD USER INTERFACE WITH ACCESSIBLE "SOFT" AGRI THEME# =====================================================================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.")18 unmodified lineswith gr.Tab("Mass Bulk Detection (Zip Folder)"):gr.Markdown("### π Batch Processing Engine")file_input = gr.File(file_types=[".zip"], label="Upload Unlabeled Leaf Folder (.zip)")file_output = gr.File(label="Download Generated Diagnostics Report (.csv)")file_button = gr.Button("Initialize Batch Processing", variant="primary")file_button.click(fn=predict_bulk_zip,inputs=file_input,outputs=[file_output, analytics_banner])# Enforce secure authentication wallapp.launch(auth=[("admin", "sugarcane2026")])14 unmodified lines15161718192021226 unmodified lines2930313233343515 unmodified lines515253545556575859607 unmodified lines68697071727374757677787980816 unmodified lines888990919293949596979819 unmodified lines1181191201211221231241251261271281291301311321331341351 unmodified line13713813914014114214314414514618 unmodified lines16516616716816917017117217317417517617717817918018118218318414 unmodified lines# --- 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."6 unmodified lines"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.",15 unmodified lines}}total_single_images_analyzed = 0total_zip_folders_processed = 0# Single Prediction Logicdef predict_single_leaf(input_image):global total_single_images_analyzedif input_image is None:7 unmodified lineshighest_idx = np.argmax(scores)predicted_label = class_names[highest_idx]total_single_images_analyzed += 1analytics_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']}6 unmodified linesresult_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 Tabledef predict_bulk_zip(zip_file):global total_zip_folders_processedif zip_file is None:return None, None, gr.update()extract_dir = "./temp_mass_images"if os.path.exists(extract_dir):19 unmodified linesresults.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:continueshutil.rmtree(extract_dir)total_zip_folders_processed += 1analytics_text = f"π **Session Overview:** Total Single Images Scanned: `{total_single_images_analyzed}` | Bulk Zips Unpacked: `{total_zip_folders_processed}`"1 unmodified linedf = pd.DataFrame(results)report_path = "./mass_detection_report.csv"df.to_csv(report_path, index=False)return report_path, df, analytics_textreturn 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.")18 unmodified lineswith 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")])
app.py+27-23