Update app.py
Browse files
app.py
CHANGED
@@ -1,97 +1,104 @@
|
|
1 |
import torch
|
2 |
import gradio as gr
|
3 |
from PIL import Image
|
|
|
4 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
5 |
-
|
6 |
-
|
7 |
-
import
|
8 |
-
|
9 |
-
# ========== Configuration ==========
|
10 |
|
|
|
11 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
12 |
|
13 |
-
#
|
|
|
|
|
14 |
|
15 |
-
|
|
|
16 |
processor = AutoImageProcessor.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification")
|
17 |
model = AutoModelForImageClassification.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification").to(device)
|
18 |
-
model.eval()
|
|
|
|
|
|
|
19 |
|
|
|
|
|
|
|
|
|
20 |
if isinstance(image, str):
|
21 |
image = Image.open(image).convert("RGB")
|
22 |
-
|
23 |
inputs = processor(images=image, return_tensors="pt").to(device)
|
24 |
-
|
25 |
with torch.no_grad():
|
26 |
logits = model(**inputs).logits
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
return
|
31 |
-
|
32 |
-
# ========== Scrape Disease Info ==========
|
33 |
-
|
34 |
-
def get_disease_info(disease_name):
|
35 |
-
chrome_options = Options()
|
36 |
-
chrome_options.add_argument("--headless") # Run headless (no UI)
|
37 |
-
driver = webdriver.Chrome(options=chrome_options)
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
|
|
|
43 |
try:
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
return info_summary
|
74 |
-
|
75 |
except Exception as e:
|
76 |
-
return f"
|
77 |
-
|
78 |
-
finally:
|
79 |
-
driver.quit()
|
80 |
-
|
81 |
-
# ========== Web Interface ==========
|
82 |
|
|
|
83 |
def wrapped_predict(image):
|
|
|
84 |
disease_name = predict(image)
|
85 |
-
|
|
|
|
|
|
|
86 |
return disease_name, disease_info
|
87 |
|
|
|
88 |
def launch_web():
|
89 |
interface = gr.Interface(
|
90 |
fn=wrapped_predict,
|
91 |
inputs=gr.Image(type="pil", label="Upload Leaf Image"),
|
92 |
-
outputs=[
|
|
|
|
|
|
|
93 |
title="Plant Disease Detection",
|
94 |
-
description="Upload a leaf image to detect the disease
|
95 |
)
|
96 |
interface.launch(share=True, debug=True)
|
97 |
|
|
|
1 |
import torch
|
2 |
import gradio as gr
|
3 |
from PIL import Image
|
4 |
+
import os
|
5 |
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
6 |
+
import numpy as np
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
9 |
+
from sklearn.metrics import confusion_matrix
|
|
|
10 |
|
11 |
+
# Make sure the model is loaded only once in the deployment environment
|
12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
|
14 |
+
# Assuming model path is provided by Hugging Face Spaces
|
15 |
+
model_path = "./models" # Store model weights inside the space directory
|
16 |
+
os.makedirs(model_path, exist_ok=True)
|
17 |
|
18 |
+
# Load the trained MobileNetV2 model from Hugging Face Hub
|
19 |
+
def load_model():
|
20 |
processor = AutoImageProcessor.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification")
|
21 |
model = AutoModelForImageClassification.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification").to(device)
|
22 |
+
model.eval() # Set the model to evaluation mode
|
23 |
+
return processor, model
|
24 |
+
|
25 |
+
processor, model = load_model()
|
26 |
|
27 |
+
# Define the class names - These should match the labels in the dataset
|
28 |
+
class_names = ['Healthy', 'Disease_1', 'Disease_2', 'Disease_3'] # Update with your actual classes
|
29 |
+
|
30 |
+
def predict(image):
|
31 |
if isinstance(image, str):
|
32 |
image = Image.open(image).convert("RGB")
|
33 |
+
|
34 |
inputs = processor(images=image, return_tensors="pt").to(device)
|
35 |
+
|
36 |
with torch.no_grad():
|
37 |
logits = model(**inputs).logits
|
38 |
+
predicted_class_idx = logits.argmax(-1).item()
|
39 |
+
predicted_class = class_names[predicted_class_idx]
|
40 |
+
|
41 |
+
return predicted_class
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
+
# Detailed Wikipedia info
|
44 |
+
from urllib.parse import quote
|
45 |
+
import requests
|
46 |
|
47 |
+
def get_detailed_wikipedia_info(query):
|
48 |
try:
|
49 |
+
# Step 1: Search for the article
|
50 |
+
search_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={quote(query)}&format=json"
|
51 |
+
search_response = requests.get(search_url).json()
|
52 |
+
search_results = search_response.get("query", {}).get("search", [])
|
53 |
+
|
54 |
+
if not search_results:
|
55 |
+
return query, "No Wikipedia pages found."
|
56 |
+
|
57 |
+
# Get the top result title
|
58 |
+
top_title = search_results[0]["title"]
|
59 |
+
|
60 |
+
# Step 2: Get full page content (plaintext extract)
|
61 |
+
extract_url = f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=&explaintext=&titles={quote(top_title)}&format=json"
|
62 |
+
extract_response = requests.get(extract_url).json()
|
63 |
+
|
64 |
+
page_data = extract_response.get("query", {}).get("pages", {})
|
65 |
+
page = next(iter(page_data.values()))
|
66 |
+
extract_text = page.get("extract", "No detailed info found.")
|
67 |
+
|
68 |
+
# Step 3: Format output with Markdown link
|
69 |
+
page_link = f"https://en.wikipedia.org/wiki/{quote(top_title.replace(' ', '_'))}"
|
70 |
+
info = (
|
71 |
+
f"### 🌿 **{top_title}**\n\n"
|
72 |
+
f"{extract_text.strip()}\n\n"
|
73 |
+
f"🔗 [Click here to read more on Wikipedia]({page_link})"
|
74 |
+
)
|
75 |
+
|
76 |
+
return top_title, info
|
77 |
+
|
|
|
|
|
78 |
except Exception as e:
|
79 |
+
return query, f"Error fetching info: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
+
# Wrapped predict function
|
82 |
def wrapped_predict(image):
|
83 |
+
# Step 1: Use your local ML model to predict the disease name
|
84 |
disease_name = predict(image)
|
85 |
+
|
86 |
+
# Step 2: Use the disease name to query detailed Wikipedia info
|
87 |
+
disease_api_name, disease_info = get_detailed_wikipedia_info(disease_name)
|
88 |
+
|
89 |
return disease_name, disease_info
|
90 |
|
91 |
+
# Gradio Interface for Web Deployment
|
92 |
def launch_web():
|
93 |
interface = gr.Interface(
|
94 |
fn=wrapped_predict,
|
95 |
inputs=gr.Image(type="pil", label="Upload Leaf Image"),
|
96 |
+
outputs=[
|
97 |
+
gr.Label(label="Predicted Disease"), # For displaying the disease name
|
98 |
+
gr.Textbox(label="Disease Information") # For displaying the detailed information
|
99 |
+
],
|
100 |
title="Plant Disease Detection",
|
101 |
+
description="Upload a leaf image to detect the disease."
|
102 |
)
|
103 |
interface.launch(share=True, debug=True)
|
104 |
|