SarowarSaurav commited on
Commit
a933af8
·
verified ·
1 Parent(s): f984f23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -56
app.py CHANGED
@@ -1,81 +1,90 @@
1
  import os
2
- import gradio as gr
3
  import openai
4
- import torch
5
- from torchvision import transforms
6
  from PIL import Image
7
- import requests
8
- from io import BytesIO
9
 
10
  # Set your OpenAI API key here or use environment variables
11
  openai.api_key = "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"
12
 
13
- # Load a pre-trained model for leaf disease detection
14
- # For demonstration, we'll use a generic ResNet model fine-tuned for classification
15
- # Replace the model path with your specific model trained for leaf diseases
16
- model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True)
17
- model.eval()
18
-
19
- # Define image transformations
20
- preprocess = transforms.Compose([
21
- transforms.Resize(256),
22
- transforms.CenterCrop(224),
23
- transforms.ToTensor(),
24
- transforms.Normalize(
25
- mean=[0.485, 0.456, 0.406], # Standard ImageNet means
26
- std=[0.229, 0.224, 0.225] # Standard ImageNet stds
27
- )
28
- ])
29
-
30
- # Load class labels (You should replace this with your specific disease classes)
31
- # For demonstration, we'll use ImageNet labels
32
- LABELS_URL = "https://s3.amazonaws.com/outcome-blog/imagenet/labels.json"
33
- response = requests.get(LABELS_URL)
34
- labels = {int(key): value for key, value in response.json().items()}
35
-
36
- def detect_disease(image):
37
- # Preprocess the image
38
- img = preprocess(image).unsqueeze(0) # Add batch dimension
39
-
40
- # Perform inference
41
- with torch.no_grad():
42
- outputs = model(img)
43
- _, predicted = torch.max(outputs, 1)
44
- class_id = predicted.item()
45
- disease = labels.get(class_id, "Unknown Disease")
46
-
47
- if disease == "Unknown Disease":
48
- return disease, "Sorry, the disease could not be identified. Please consult a local agricultural extension office."
49
-
50
- # Generate remedies using OpenAI's ChatGPT
51
- prompt = f"The following disease has been detected on a plant leaf: {disease}. Please provide detailed remedies and treatment options for this disease."
52
 
 
 
 
53
  try:
54
- completion = openai.ChatCompletion.create(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  model="gpt-4",
56
  messages=[
57
- {"role": "system", "content": "You are a helpful agricultural expert."},
58
- {"role": "user", "content": prompt}
59
  ],
60
  temperature=0.7,
61
  max_tokens=500
62
  )
63
- remedies = completion.choices[0].message.content.strip()
64
- except Exception as e:
65
- remedies = "An error occurred while fetching remedies. Please try again later."
66
 
67
- return disease, remedies
 
 
 
 
 
68
 
69
  # Define the Gradio interface
70
  iface = gr.Interface(
71
- fn=detect_disease,
72
- inputs=gr.inputs.Image(type="pil", label="Upload Leaf Image"),
73
  outputs=[
74
- gr.outputs.Textbox(label="Detected Disease"),
75
- gr.outputs.Textbox(label="Remedies")
76
  ],
77
  title="Leaf Disease Detector",
78
- description="Upload an image of a leaf, and the system will detect the disease and provide remedies."
79
  )
80
 
81
  if __name__ == "__main__":
 
1
  import os
 
2
  import openai
3
+ import gradio as gr
 
4
  from PIL import Image
5
+ import io
6
+ import base64
7
 
8
  # Set your OpenAI API key here or use environment variables
9
  openai.api_key = "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"
10
 
11
+ def detect_disease_and_get_remedies(image):
12
+ """
13
+ Detects leaf disease from the uploaded image and provides remedies.
14
+
15
+ Args:
16
+ image (PIL.Image): Uploaded leaf image.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ Returns:
19
+ Tuple[str, str]: Detected disease and corresponding remedies.
20
+ """
21
  try:
22
+ # Convert PIL Image to bytes
23
+ buffered = io.BytesIO()
24
+ image.save(buffered, format="JPEG")
25
+ img_bytes = buffered.getvalue()
26
+
27
+ # Encode image to base64
28
+ img_base64 = base64.b64encode(img_bytes).decode('utf-8')
29
+
30
+ # Create a system prompt to guide the model
31
+ system_prompt = "You are an agricultural expert specializing in plant diseases."
32
+
33
+ # Step 1: Detect Disease
34
+ disease_prompt = (
35
+ "Analyze the following image of a plant leaf and identify any diseases present. "
36
+ "Provide only the name of the disease without additional explanation.\n\n"
37
+ "Image (base64 encoded): {}\n\nDisease:".format(img_base64)
38
+ )
39
+
40
+ # Send the image to OpenAI's ChatCompletion API for disease detection
41
+ response = openai.ChatCompletion.create(
42
+ model="gpt-4-vision", # Assuming GPT-4 with vision capabilities
43
+ messages=[
44
+ {"role": "system", "content": system_prompt},
45
+ {"role": "user", "content": disease_prompt}
46
+ ],
47
+ temperature=0
48
+ )
49
+
50
+ disease = response.choices[0].message['content'].strip()
51
+
52
+ if not disease or disease.lower() in ["no disease detected", "healthy"]:
53
+ return "No Disease Detected", "The leaf appears to be healthy. Maintain regular plant care to prevent future issues."
54
+
55
+ # Step 2: Get Remedies for the Detected Disease
56
+ remedy_prompt = (
57
+ "Provide detailed remedies and treatment options for the following plant leaf disease: {}. "
58
+ "Include both chemical and organic treatment methods if applicable.".format(disease)
59
+ )
60
+
61
+ remedy_response = openai.ChatCompletion.create(
62
  model="gpt-4",
63
  messages=[
64
+ {"role": "system", "content": "You are a knowledgeable agricultural advisor."},
65
+ {"role": "user", "content": remedy_prompt}
66
  ],
67
  temperature=0.7,
68
  max_tokens=500
69
  )
 
 
 
70
 
71
+ remedies = remedy_response.choices[0].message['content'].strip()
72
+
73
+ return disease, remedies
74
+
75
+ except Exception as e:
76
+ return "Error", f"An error occurred: {str(e)}"
77
 
78
  # Define the Gradio interface
79
  iface = gr.Interface(
80
+ fn=detect_disease_and_get_remedies,
81
+ inputs=gr.Image(type="pil", label="Upload Leaf Image"),
82
  outputs=[
83
+ gr.Textbox(label="Detected Disease"),
84
+ gr.Textbox(label="Remedies")
85
  ],
86
  title="Leaf Disease Detector",
87
+ description="Upload an image of a leaf, and the system will detect any diseases present and provide remedies."
88
  )
89
 
90
  if __name__ == "__main__":