import spaces # <-- This MUST be the absolute first line, before gradio or setfit import os import pickle import gradio as gr import numpy as np from setfit import SetFitModel MODEL_ID = "Tree-Diagram/setfit_crop_disease_model_v1" # The ORIGINAL label_mappings.pkl from the old app, uploaded next to this file. LABEL_MAPPING_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "label_mappings.pkl" ) print("=" * 60) print(f"Loading SetFit model: {MODEL_ID}") print("=" * 60) # Load the model outside the function so it stays in memory model = SetFitModel.from_pretrained(MODEL_ID) print("Model loaded successfully.") # Same lookup the old backend used: predicted index -> disease name. # (If this file is missing, the Space stops with a clear error in the logs.) with open(LABEL_MAPPING_PATH, "rb") as f: IDX_TO_DIAGNOSIS = pickle.load(f)["idx_to_diagnosis"] print(f"Loaded {len(IDX_TO_DIAGNOSIS)} disease labels.") print("Model is ready for predictions.") @spaces.GPU # <-- This tells ZeroGPU to allocate the GPU only when a user clicks Diagnose def predict_disease(text: str): text = (text or "").strip() if not text: return "ERROR: Please enter a symptom description.", 0.0 try: # Same steps as the old backend: predict -> int() -> look up the name. preds = model.predict([text]) pred_idx = int(preds[0]) diagnosis = IDX_TO_DIAGNOSIS.get(pred_idx, "Unknown Disease") confidence = 0.0 try: probs = model.predict_proba([text]) if hasattr(probs, "detach"): probs = probs.detach().cpu().numpy() confidence = float(np.max(probs)) except Exception as prob_err: print(f"Could not compute confidence: {prob_err}") print(f"Prediction index {pred_idx} -> {diagnosis} ({confidence:.2f})") return diagnosis, round(confidence, 4) except Exception as e: print(f"Prediction error: {e}") raise with gr.Blocks(title="AgroShield Diagnosis API") as demo: gr.Markdown("# 🌱 AgroShield Crop Disease Diagnosis") input_text = gr.Textbox( label="Crop Symptom Observation", placeholder="Describe the symptoms observed on the crop...", lines=6, ) output = gr.Textbox( label="Predicted Disease" ) confidence_box = gr.Number( label="Confidence" ) predict_button = gr.Button("Diagnose Disease") predict_button.click( fn=predict_disease, inputs=input_text, outputs=[output, confidence_box], api_name="predict" ) if __name__ == "__main__": demo.launch(ssr_mode=False)