Spaces:
Running
Running
import os | |
import gradio as gr | |
from transformers import pipeline | |
from PIL import Image | |
# Retrieve Hugging Face token from Secrets | |
hf_token = os.getenv("HF_TOKEN") | |
plant_disease_classifier = pipeline( | |
task="image-classification", | |
model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification", | |
top_k=3 | |
) | |
nutrient_deficiency_classifier = pipeline( | |
task="image-classification", | |
model="yanyu/efficientformer_l1", | |
top_k=3 | |
) | |
def diagnose_crop_health(image: Image.Image): | |
""" | |
Takes a PIL Image of a crop leaf and returns: | |
- Top 3 disease predictions | |
- Top 3 nutrient deficiency predictions | |
- Combined care advice based on both | |
""" | |
disease_results = plant_disease_classifier(image) | |
nutrient_results = nutrient_deficiency_classifier(image) | |
disease_preds = [f"{res['label']} ({res['score']*100:.1f}%)" for res in disease_results] | |
nutrient_preds = [f"{res['label']} ({res['score']*100:.1f}%)" for res in nutrient_results] | |
# Generate advice based on predictions | |
advices = [] | |
top_disease = disease_results[0]['label'].lower() | |
top_nutrient = nutrient_results[0]['label'].lower() | |
if "healthy" in top_disease: | |
advices.append("No disease detected—maintain standard crop care.") | |
else: | |
advices.append(f"Disease detected: {disease_results[0]['label']}. Isolate and apply targeted treatment.") | |
if "healthy" in top_nutrient: | |
advices.append("No nutrient deficiency detected—continue regular fertilization.") | |
else: | |
advices.append(f"Nutrient issue: {nutrient_results[0]['label']}. Amend soil based on deficiency (e.g., add N, P, or K).") | |
return "\n".join(disease_preds), "\n".join(nutrient_preds), "\n".join(advices) | |
# Build the Gradio interface | |
iface = gr.Interface( | |
fn=diagnose_crop_health, | |
inputs=gr.Image(type="pil", label="Upload Crop Leaf Image"), | |
outputs=[ | |
gr.Textbox(label="Disease Predictions (Top 3)"), | |
gr.Textbox(label="Nutrient Predictions (Top 3)"), | |
gr.Textbox(label="Care Advice") | |
], | |
title="Crop Health Monitor", | |
description=( | |
"Upload a photo of your crop's leaf to diagnose diseases and nutrient deficiencies, " | |
"and receive combined care recommendations using two complementary models." | |
), | |
examples=[ | |
["Plants/Unhealthy_crop_1.jpg"], | |
["Plants/Unhealthy_crop_2.jpg"], | |
["Plants/Unhealthy_crop_3.jpg"], | |
["Plants/Unhealthy_crop_4.jpg"], | |
["Plants/Unhealthy_crop_5.jpg"], | |
["Plants/Healthy_crop_1.jpg"], | |
["Plants/Healthy_crop_2.jpg"] | |
], | |
allow_flagging="never" | |
) | |
if __name__ == "__main__": | |
iface.launch(server_name="0.0.0.0", server_port=7860) |