Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,7 +6,6 @@ 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,99 +20,26 @@ except Exception as e:
|
|
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 = "
|
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 = {
|
109 |
-
|
|
|
|
|
|
|
|
|
110 |
try:
|
111 |
response = requests.post(url, headers=headers, json=data)
|
112 |
if response.status_code == 200:
|
113 |
-
|
114 |
-
|
|
|
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)}")
|
|
|
6 |
import json
|
7 |
import logging
|
8 |
import requests
|
|
|
9 |
|
10 |
# Configure Logging
|
11 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
|
20 |
logging.error(f"❌ Failed to load model: {str(e)}")
|
21 |
raise RuntimeError("Failed to load the model. Please check the logs for details.")
|
22 |
|
23 |
+
# Gemini API Key (Replace with your actual key)
|
24 |
+
GEMINI_API_KEY = "AIzaSyCiRL0ES-zsJGJYsY03xmpwqcggDGcL2Fk" # <-- Replace with your actual API key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
# Function to Get AI-Powered Treatment Suggestions
|
27 |
def get_treatment_suggestions(disease_name):
|
|
|
28 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateText?key={GEMINI_API_KEY}"
|
29 |
headers = {"Content-Type": "application/json"}
|
30 |
+
data = {
|
31 |
+
"prompt": f"Provide detailed organic and chemical treatment options, including dosage and preventive care, for {disease_name} in crops.",
|
32 |
+
"temperature": 0.7,
|
33 |
+
"max_tokens": 250
|
34 |
+
}
|
35 |
+
|
36 |
try:
|
37 |
response = requests.post(url, headers=headers, json=data)
|
38 |
if response.status_code == 200:
|
39 |
+
result = response.json()
|
40 |
+
treatment = result.get("candidates", [{}])[0].get("output", "No treatment suggestions found.")
|
41 |
+
return treatment
|
42 |
else:
|
|
|
43 |
return f"API Error: {response.status_code} - {response.text}"
|
44 |
except Exception as e:
|
45 |
logging.error(f"Error fetching treatment suggestions: {str(e)}")
|