Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,14 +1,17 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from PIL import Image
|
| 4 |
from transformers import pipeline
|
| 5 |
import io, os, re
|
| 6 |
import google.generativeai as genai
|
| 7 |
|
| 8 |
-
app = FastAPI(title="🌾 AI Plant Disease Diagnosis Expert")
|
| 9 |
|
| 10 |
# === Configure Gemini ===
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
# === Load Hugging Face model ===
|
| 14 |
print("🔍 Loading Hugging Face disease model...")
|
|
@@ -27,17 +30,19 @@ def clean_label(label: str):
|
|
| 27 |
|
| 28 |
# === Helper: clean Gemini output ===
|
| 29 |
def clean_text(text: str):
|
| 30 |
-
# Remove markdown and escape sequences for clean JSON response
|
| 31 |
text = re.sub(r"[*#`\-]+", "", text)
|
| 32 |
text = re.sub(r"\n{2,}", "\n", text)
|
| 33 |
return text.strip()
|
| 34 |
|
| 35 |
# === Main prediction route ===
|
| 36 |
@app.post("/predict")
|
| 37 |
-
async def predict(
|
|
|
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
Accepts an image of a plant leaf, classifies disease via Hugging Face model,
|
| 40 |
-
and generates a professional,
|
| 41 |
"""
|
| 42 |
try:
|
| 43 |
# 1️⃣ Read uploaded image
|
|
@@ -48,7 +53,6 @@ async def predict(file: UploadFile = File(...)):
|
|
| 48 |
hf_results = hf_pipe(image)
|
| 49 |
sorted_results = sorted(hf_results, key=lambda x: x["score"], reverse=True)
|
| 50 |
|
| 51 |
-
# Prepare list of all predictions
|
| 52 |
all_predictions = [
|
| 53 |
{"label": clean_label(r["label"]), "confidence": round(r["score"], 4)}
|
| 54 |
for r in sorted_results
|
|
@@ -58,14 +62,28 @@ async def predict(file: UploadFile = File(...)):
|
|
| 58 |
disease = top_pred["label"]
|
| 59 |
confidence = top_pred["confidence"]
|
| 60 |
|
| 61 |
-
# 3️⃣
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
prompt = f"""
|
| 63 |
-
You are an
|
| 64 |
-
You
|
| 65 |
-
The
|
| 66 |
-
Use
|
| 67 |
|
| 68 |
-
|
|
|
|
| 69 |
1. Disease Name
|
| 70 |
2. Description (1-2 sentences)
|
| 71 |
3. Visible Symptoms (bullet list)
|
|
@@ -73,31 +91,35 @@ Your output must follow this structure:
|
|
| 73 |
5. Ideal Conditions for Spread
|
| 74 |
6. Safe Management & Control Steps (5-6 points)
|
| 75 |
7. Preventive Measures for Future
|
| 76 |
-
8. Verification & Expert Advice
|
| 77 |
-
9. Disclaimer
|
| 78 |
|
| 79 |
-
Keep
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
Keep it concise, but convincing.
|
| 84 |
-
"""
|
| 85 |
|
|
|
|
| 86 |
model = genai.GenerativeModel("gemini-2.5-flash")
|
| 87 |
-
gemini_resp = model.generate_content(
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
report = {
|
| 92 |
-
"Report Title": "Plant Disease Diagnostic Summary",
|
|
|
|
| 93 |
"Disease Name": disease,
|
| 94 |
"Model Confidence": f"{confidence*100:.2f}%",
|
| 95 |
"Detailed Report": explanation,
|
| 96 |
"Other Possible Diseases": all_predictions[1:5],
|
| 97 |
"Note": (
|
| 98 |
"This report is for agricultural guidance only. "
|
| 99 |
-
"Farmers are advised to consult a certified agronomist or local agricultural
|
| 100 |
-
"for laboratory confirmation before applying
|
| 101 |
)
|
| 102 |
}
|
| 103 |
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from PIL import Image
|
| 4 |
from transformers import pipeline
|
| 5 |
import io, os, re
|
| 6 |
import google.generativeai as genai
|
| 7 |
|
| 8 |
+
app = FastAPI(title="🌾 AI Plant Disease Diagnosis Expert (Multilingual)")
|
| 9 |
|
| 10 |
# === Configure Gemini ===
|
| 11 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 12 |
+
if not GOOGLE_API_KEY:
|
| 13 |
+
raise ValueError("⚠️ Missing GOOGLE_API_KEY environment variable!")
|
| 14 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 15 |
|
| 16 |
# === Load Hugging Face model ===
|
| 17 |
print("🔍 Loading Hugging Face disease model...")
|
|
|
|
| 30 |
|
| 31 |
# === Helper: clean Gemini output ===
|
| 32 |
def clean_text(text: str):
|
|
|
|
| 33 |
text = re.sub(r"[*#`\-]+", "", text)
|
| 34 |
text = re.sub(r"\n{2,}", "\n", text)
|
| 35 |
return text.strip()
|
| 36 |
|
| 37 |
# === Main prediction route ===
|
| 38 |
@app.post("/predict")
|
| 39 |
+
async def predict(
|
| 40 |
+
file: UploadFile = File(...),
|
| 41 |
+
language: str = Form("en") # Default: English; supports ISO codes like 'hi', 'mr', 'ta', etc.
|
| 42 |
+
):
|
| 43 |
"""
|
| 44 |
Accepts an image of a plant leaf, classifies disease via Hugging Face model,
|
| 45 |
+
and generates a professional, multilingual diagnosis report via Gemini.
|
| 46 |
"""
|
| 47 |
try:
|
| 48 |
# 1️⃣ Read uploaded image
|
|
|
|
| 53 |
hf_results = hf_pipe(image)
|
| 54 |
sorted_results = sorted(hf_results, key=lambda x: x["score"], reverse=True)
|
| 55 |
|
|
|
|
| 56 |
all_predictions = [
|
| 57 |
{"label": clean_label(r["label"]), "confidence": round(r["score"], 4)}
|
| 58 |
for r in sorted_results
|
|
|
|
| 62 |
disease = top_pred["label"]
|
| 63 |
confidence = top_pred["confidence"]
|
| 64 |
|
| 65 |
+
# 3️⃣ Language-based dynamic prompt for Gemini
|
| 66 |
+
language_name = {
|
| 67 |
+
"en": "English",
|
| 68 |
+
"hi": "Hindi",
|
| 69 |
+
"mr": "Marathi",
|
| 70 |
+
"ta": "Tamil",
|
| 71 |
+
"bn": "Bengali",
|
| 72 |
+
"te": "Telugu",
|
| 73 |
+
"gu": "Gujarati",
|
| 74 |
+
"pa": "Punjabi",
|
| 75 |
+
"kn": "Kannada",
|
| 76 |
+
"ml": "Malayalam"
|
| 77 |
+
}.get(language.lower(), "English")
|
| 78 |
+
|
| 79 |
prompt = f"""
|
| 80 |
+
You are an agricultural plant pathologist.
|
| 81 |
+
You are writing a disease diagnosis report for a farmer in {language_name}.
|
| 82 |
+
The detected disease is '{disease}' with {confidence*100:.1f}% confidence.
|
| 83 |
+
Use the photo and this data to write a structured diagnosis.
|
| 84 |
|
| 85 |
+
Write your answer completely in {language_name}.
|
| 86 |
+
Follow this format:
|
| 87 |
1. Disease Name
|
| 88 |
2. Description (1-2 sentences)
|
| 89 |
3. Visible Symptoms (bullet list)
|
|
|
|
| 91 |
5. Ideal Conditions for Spread
|
| 92 |
6. Safe Management & Control Steps (5-6 points)
|
| 93 |
7. Preventive Measures for Future
|
| 94 |
+
8. Verification & Expert Advice
|
| 95 |
+
9. Disclaimer
|
| 96 |
|
| 97 |
+
Keep tone clear and farmer-friendly.
|
| 98 |
+
Avoid mentioning AI or models.
|
| 99 |
+
Use plain text, no markdown or symbols.
|
| 100 |
+
"""
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# 4️⃣ Generate multilingual report using Gemini
|
| 103 |
model = genai.GenerativeModel("gemini-2.5-flash")
|
| 104 |
+
gemini_resp = model.generate_content(
|
| 105 |
+
[prompt, {"mime_type": "image/jpeg", "data": image_bytes}]
|
| 106 |
+
)
|
| 107 |
+
explanation = clean_text(
|
| 108 |
+
gemini_resp.text if hasattr(gemini_resp, "text") else str(gemini_resp)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# 5️⃣ Combine and return
|
| 112 |
report = {
|
| 113 |
+
"Report Title": "🌾 Plant Disease Diagnostic Summary",
|
| 114 |
+
"Language": language_name,
|
| 115 |
"Disease Name": disease,
|
| 116 |
"Model Confidence": f"{confidence*100:.2f}%",
|
| 117 |
"Detailed Report": explanation,
|
| 118 |
"Other Possible Diseases": all_predictions[1:5],
|
| 119 |
"Note": (
|
| 120 |
"This report is for agricultural guidance only. "
|
| 121 |
+
"Farmers are advised to consult a certified agronomist or local agricultural officer "
|
| 122 |
+
"for laboratory confirmation before applying treatment."
|
| 123 |
)
|
| 124 |
}
|
| 125 |
|