Spaces:
Sleeping
Sleeping
added app.py file
Browse files
app.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import numpy as np
|
| 4 |
+
import onnxruntime as ort
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
import ast
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
# === Load and clean class names ===
|
| 14 |
+
class_file_path = os.path.join(os.path.dirname(__file__), 'class_names.txt')
|
| 15 |
+
with open(class_file_path, 'r') as f:
|
| 16 |
+
raw_line = f.read()
|
| 17 |
+
class_names = ast.literal_eval(raw_line.replace("Classes: ", "").strip())
|
| 18 |
+
|
| 19 |
+
# === Load ONNX model ===
|
| 20 |
+
model_path = os.path.join(os.path.dirname(__file__), 'model.onnx')
|
| 21 |
+
learn = ort.InferenceSession(model_path)
|
| 22 |
+
|
| 23 |
+
# === OpenRouter setup ===
|
| 24 |
+
client = OpenAI(
|
| 25 |
+
base_url="https://openrouter.ai/api/v1",
|
| 26 |
+
api_key=os.getenv("OPENROUTER_API_KEY"),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def generate_description_and_prevention(label):
|
| 30 |
+
if label == "not_a_crop":
|
| 31 |
+
return (
|
| 32 |
+
"The uploaded image does not seem to show a valid crop or leaf.",
|
| 33 |
+
"Please upload a clear image of a single crop or a leaf showing disease symptoms."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
prompt = (
|
| 37 |
+
f"Explain in simple words what the plant disease or condition '{label}' is, "
|
| 38 |
+
f"and give 2 to 4 clear, practical prevention tips.\n"
|
| 39 |
+
"Use this format:\n"
|
| 40 |
+
"Description:\n"
|
| 41 |
+
"Explain briefly what this disease is and how it affects the plant.\n"
|
| 42 |
+
"Prevention:\n"
|
| 43 |
+
"- Tip 1\n"
|
| 44 |
+
"- Tip 2\n"
|
| 45 |
+
"- (Optional) Tip 3\n"
|
| 46 |
+
"- (Optional) Tip 4"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
response = client.chat.completions.create(
|
| 51 |
+
model="deepseek/deepseek-r1:free",
|
| 52 |
+
messages=[
|
| 53 |
+
{"role": "system", "content": "You are a knowledgeable plant pathologist."},
|
| 54 |
+
{"role": "user", "content": prompt}
|
| 55 |
+
],
|
| 56 |
+
temperature=0.7,
|
| 57 |
+
max_tokens=800
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
content = response.choices[0].message.content
|
| 61 |
+
if "Description:" in content and "Prevention:" in content:
|
| 62 |
+
parts = content.split("Prevention:")
|
| 63 |
+
description = parts[0].replace("Description:", "").strip()
|
| 64 |
+
prevention = parts[1].strip()
|
| 65 |
+
return description, prevention
|
| 66 |
+
else:
|
| 67 |
+
return "Description not structured correctly.", "No prevention steps found."
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"[ERROR] OpenRouter API error: {e}")
|
| 70 |
+
return "OpenRouter error.", "Failed to generate prevention steps."
|
| 71 |
+
|
| 72 |
+
def preprocess_image(image, size=(224, 224)):
|
| 73 |
+
image = image.resize(size)
|
| 74 |
+
img_array = np.array(image).astype(np.float32) / 255.0
|
| 75 |
+
img_array = img_array.transpose(2, 0, 1)
|
| 76 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 77 |
+
return img_array
|
| 78 |
+
|
| 79 |
+
def predict(image):
|
| 80 |
+
image = image.convert("RGB")
|
| 81 |
+
input_tensor = preprocess_image(image)
|
| 82 |
+
|
| 83 |
+
input_name = learn.get_inputs()[0].name
|
| 84 |
+
outputs = learn.run(None, {input_name: input_tensor})
|
| 85 |
+
probs = outputs[0][0]
|
| 86 |
+
pred_idx = int(np.argmax(probs))
|
| 87 |
+
pred_class = class_names[pred_idx]
|
| 88 |
+
confidence = float(probs[pred_idx] * 100)
|
| 89 |
+
|
| 90 |
+
description, prevention = generate_description_and_prevention(pred_class)
|
| 91 |
+
|
| 92 |
+
return pred_class, round(confidence, 2), description, prevention
|
| 93 |
+
|
| 94 |
+
# === Gradio Interface ===
|
| 95 |
+
iface = gr.Interface(
|
| 96 |
+
fn=predict,
|
| 97 |
+
inputs=gr.Image(type="pil"),
|
| 98 |
+
outputs=[
|
| 99 |
+
gr.Label(label="Prediction"),
|
| 100 |
+
gr.Number(label="Confidence %"),
|
| 101 |
+
gr.Textbox(label="Description"),
|
| 102 |
+
gr.Textbox(label="Prevention")
|
| 103 |
+
],
|
| 104 |
+
title="🌱 Crop Disease Detection",
|
| 105 |
+
description="Upload a crop or leaf image to detect plant diseases and get prevention tips."
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|