Spaces:
Sleeping
Sleeping
File size: 2,887 Bytes
3051b4e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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 74 75 76 77 78 79 80 81 82 83 |
import os
import gradio as gr
import openai
import torch
from torchvision import transforms
from PIL import Image
import requests
from io import BytesIO
# Set your OpenAI API key here or use environment variables
openai.api_key = os.getenv("OPENAI_API_KEY")
# Load a pre-trained model for leaf disease detection
# For demonstration, we'll use a generic ResNet model fine-tuned for classification
# Replace the model path with your specific model trained for leaf diseases
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True)
model.eval()
# Define image transformations
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], # Standard ImageNet means
std=[0.229, 0.224, 0.225] # Standard ImageNet stds
)
])
# Load class labels (You should replace this with your specific disease classes)
# For demonstration, we'll use ImageNet labels
LABELS_URL = "https://s3.amazonaws.com/outcome-blog/imagenet/labels.json"
response = requests.get(LABELS_URL)
labels = {int(key): value for key, value in response.json().items()}
def detect_disease(image):
# Preprocess the image
img = preprocess(image).unsqueeze(0) # Add batch dimension
# Perform inference
with torch.no_grad():
outputs = model(img)
_, predicted = torch.max(outputs, 1)
class_id = predicted.item()
disease = labels.get(class_id, "Unknown Disease")
if disease == "Unknown Disease":
return disease, "Sorry, the disease could not be identified. Please consult a local agricultural extension office."
# Generate remedies using OpenAI's ChatGPT
prompt = f"The following disease has been detected on a plant leaf: {disease}. Please provide detailed remedies and treatment options for this disease."
try:
completion = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful agricultural expert."},
{"role": "user", "content": prompt}
],
temperature=0.7,
max_tokens=500
)
remedies = completion.choices[0].message.content.strip()
except Exception as e:
remedies = "An error occurred while fetching remedies. Please try again later."
return disease, remedies
# Define the Gradio interface
iface = gr.Interface(
fn=detect_disease,
inputs=gr.inputs.Image(type="pil", label="Upload Leaf Image"),
outputs=[
gr.outputs.Textbox(label="Detected Disease"),
gr.outputs.Textbox(label="Remedies")
],
title="Leaf Disease Detector",
description="Upload an image of a leaf, and the system will detect the disease and provide remedies."
)
if __name__ == "__main__":
iface.launch()
|