Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,8 +3,10 @@ from transformers import AutoImageProcessor, AutoModelForImageClassification
|
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
import numpy as np
|
|
|
6 |
import logging
|
7 |
import requests
|
|
|
8 |
|
9 |
# Configure Logging
|
10 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
@@ -19,33 +21,100 @@ except Exception as e:
|
|
19 |
logging.error(f"❌ Failed to load model: {str(e)}")
|
20 |
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
21 |
|
22 |
-
# Gemini API Key
|
23 |
-
GEMINI_API_KEY = "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
# Function to Get AI-Powered Treatment Suggestions
|
26 |
def get_treatment_suggestions(disease_name):
|
27 |
prompt = f"Provide detailed organic and chemical treatment options, including dosage and preventive care, for {disease_name} in crops."
|
28 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateText?key={GEMINI_API_KEY}"
|
29 |
-
|
30 |
headers = {"Content-Type": "application/json"}
|
31 |
-
data = {
|
32 |
-
"contents": [{"parts": [{"text": prompt}]}], # Correct API request format
|
33 |
-
"temperature": 0.7,
|
34 |
-
"maxOutputTokens": 250 # Correct parameter name
|
35 |
-
}
|
36 |
|
37 |
try:
|
38 |
response = requests.post(url, headers=headers, json=data)
|
39 |
if response.status_code == 200:
|
40 |
-
|
41 |
-
|
42 |
-
if candidates:
|
43 |
-
return candidates[0].get("output", "No treatment suggestions found.")
|
44 |
-
else:
|
45 |
-
return "No treatment suggestions found."
|
46 |
else:
|
47 |
-
logging.error(f"API Error
|
48 |
-
return f"API Error: {response.status_code}"
|
49 |
except Exception as e:
|
50 |
logging.error(f"Error fetching treatment suggestions: {str(e)}")
|
51 |
return "Error retrieving treatment details."
|
@@ -74,7 +143,7 @@ iface = gr.Interface(
|
|
74 |
fn=predict,
|
75 |
inputs=gr.Image(type="numpy", label="Upload or capture plant image"),
|
76 |
outputs=gr.Textbox(label="Result"),
|
77 |
-
title="
|
78 |
description="Upload a plant leaf image to detect diseases and get AI-powered treatment suggestions.",
|
79 |
allow_flagging="never",
|
80 |
)
|
|
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
import numpy as np
|
6 |
+
import json
|
7 |
import logging
|
8 |
import requests
|
9 |
+
import os
|
10 |
|
11 |
# Configure Logging
|
12 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
|
21 |
logging.error(f"❌ Failed to load model: {str(e)}")
|
22 |
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
23 |
|
24 |
+
# Gemini API Key
|
25 |
+
GEMINI_API_KEY = "import gradio as gr
|
26 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
27 |
+
from PIL import Image
|
28 |
+
import torch
|
29 |
+
import numpy as np
|
30 |
+
import json
|
31 |
+
import logging
|
32 |
+
import requests
|
33 |
+
import os
|
34 |
+
|
35 |
+
# Configure Logging
|
36 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
37 |
+
|
38 |
+
# Load Model & Processor
|
39 |
+
model_name = "linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification"
|
40 |
+
try:
|
41 |
+
processor = AutoImageProcessor.from_pretrained(model_name, use_fast=True)
|
42 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
43 |
+
logging.info("✅ Model and processor loaded successfully.")
|
44 |
+
except Exception as e:
|
45 |
+
logging.error(f"❌ Failed to load model: {str(e)}")
|
46 |
+
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
47 |
+
|
48 |
+
# Gemini API Key
|
49 |
+
GEMINI_API_KEY = "xxxxxxxx" # Replace this with your actual API key
|
50 |
+
|
51 |
+
# Function to Get AI-Powered Treatment Suggestions
|
52 |
+
def get_treatment_suggestions(disease_name):
|
53 |
+
prompt = f"Provide detailed organic and chemical treatment options, including dosage and preventive care, for {disease_name} in crops."
|
54 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateText?key={GEMINI_API_KEY}"
|
55 |
+
headers = {"Content-Type": "application/json"}
|
56 |
+
data = {"contents": [{"parts": [{"text": prompt}]}]} # Correct request format
|
57 |
+
|
58 |
+
try:
|
59 |
+
response = requests.post(url, headers=headers, json=data)
|
60 |
+
if response.status_code == 200:
|
61 |
+
response_json = response.json()
|
62 |
+
return response_json["candidates"][0]["content"]["parts"][0]["text"]
|
63 |
+
else:
|
64 |
+
logging.error(f"API Error {response.status_code}: {response.text}")
|
65 |
+
return f"API Error: {response.status_code} - {response.text}"
|
66 |
+
except Exception as e:
|
67 |
+
logging.error(f"Error fetching treatment suggestions: {str(e)}")
|
68 |
+
return "Error retrieving treatment details."
|
69 |
+
|
70 |
+
# Define Prediction Function
|
71 |
+
def predict(image):
|
72 |
+
try:
|
73 |
+
image = Image.fromarray(np.uint8(image)).convert("RGB")
|
74 |
+
inputs = processor(images=image, return_tensors="pt")
|
75 |
+
with torch.no_grad():
|
76 |
+
outputs = model(**inputs)
|
77 |
+
logits = outputs.logits
|
78 |
+
predicted_class_idx = logits.argmax(-1).item()
|
79 |
+
predicted_label = model.config.id2label[predicted_class_idx]
|
80 |
+
|
81 |
+
# Get AI-generated treatment suggestions
|
82 |
+
treatment = get_treatment_suggestions(predicted_label)
|
83 |
+
|
84 |
+
return f"Predicted Disease: {predicted_label}\nTreatment: {treatment}"
|
85 |
+
except Exception as e:
|
86 |
+
logging.error(f"Prediction failed: {str(e)}")
|
87 |
+
return f"❌ Prediction failed: {str(e)}"
|
88 |
+
|
89 |
+
# Gradio Interface
|
90 |
+
iface = gr.Interface(
|
91 |
+
fn=predict,
|
92 |
+
inputs=gr.Image(type="numpy", label="Upload or capture plant image"),
|
93 |
+
outputs=gr.Textbox(label="Result"),
|
94 |
+
title="AI-Powered Plant Disease Detector",
|
95 |
+
description="Upload a plant leaf image to detect diseases and get AI-powered treatment suggestions.",
|
96 |
+
allow_flagging="never",
|
97 |
+
)
|
98 |
+
|
99 |
+
# Launch Gradio App
|
100 |
+
iface.launch()
|
101 |
+
" # Replace this with your actual API key
|
102 |
|
103 |
# Function to Get AI-Powered Treatment Suggestions
|
104 |
def get_treatment_suggestions(disease_name):
|
105 |
prompt = f"Provide detailed organic and chemical treatment options, including dosage and preventive care, for {disease_name} in crops."
|
106 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateText?key={GEMINI_API_KEY}"
|
|
|
107 |
headers = {"Content-Type": "application/json"}
|
108 |
+
data = {"contents": [{"parts": [{"text": prompt}]}]} # Correct request format
|
|
|
|
|
|
|
|
|
109 |
|
110 |
try:
|
111 |
response = requests.post(url, headers=headers, json=data)
|
112 |
if response.status_code == 200:
|
113 |
+
response_json = response.json()
|
114 |
+
return response_json["candidates"][0]["content"]["parts"][0]["text"]
|
|
|
|
|
|
|
|
|
115 |
else:
|
116 |
+
logging.error(f"API Error {response.status_code}: {response.text}")
|
117 |
+
return f"API Error: {response.status_code} - {response.text}"
|
118 |
except Exception as e:
|
119 |
logging.error(f"Error fetching treatment suggestions: {str(e)}")
|
120 |
return "Error retrieving treatment details."
|
|
|
143 |
fn=predict,
|
144 |
inputs=gr.Image(type="numpy", label="Upload or capture plant image"),
|
145 |
outputs=gr.Textbox(label="Result"),
|
146 |
+
title="AI-Powered Plant Disease Detector",
|
147 |
description="Upload a plant leaf image to detect diseases and get AI-powered treatment suggestions.",
|
148 |
allow_flagging="never",
|
149 |
)
|