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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -73
app.py CHANGED
@@ -1,91 +1,69 @@
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__":
91
- iface.launch()
 
 
 
1
  import gradio as gr
2
+ from azure.ai.inference import ChatCompletionsClient
3
+ from azure.ai.inference.models import (
4
+ SystemMessage,
5
+ UserMessage,
6
+ TextContentItem,
7
+ ImageContentItem,
8
+ ImageUrl,
9
+ ImageDetailLevel,
10
+ )
11
+ from azure.core.credentials import AzureKeyCredential
12
 
13
+ # Azure API credentials
14
+ token = "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"
15
+ endpoint = "https://models.inference.ai.azure.com"
16
+ model_name = "Llama-3.2-90B-Vision-Instruct"
17
 
18
+ # Initialize the ChatCompletionsClient
19
+ client = ChatCompletionsClient(
20
+ endpoint=endpoint,
21
+ credential=AzureKeyCredential(token),
22
+ )
23
 
24
+ # Define the function to handle the image and get predictions
25
+ def analyze_leaf_disease(image):
 
26
  try:
27
+ # Convert the uploaded image to a compatible format (e.g., save it locally)
28
+ image.save("uploaded_image.jpg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # Prepare and send the request to the Azure API
31
+ response = client.complete(
 
 
 
 
 
 
 
 
 
32
  messages=[
33
+ SystemMessage(
34
+ content="You are a helpful assistant that describes leaf disease in detail."
35
+ ),
36
+ UserMessage(
37
+ content=[
38
+ TextContentItem(text="What's the leaf disease in this image?"),
39
+ ImageContentItem(
40
+ image_url=ImageUrl.load(
41
+ image_file="uploaded_image.jpg",
42
+ image_format="jpg",
43
+ detail=ImageDetailLevel.LOW,
44
+ )
45
+ ),
46
+ ],
47
+ ),
48
  ],
49
+ model=model_name,
 
50
  )
51
 
52
+ # Extract and return the response content
53
+ return response.choices[0].message.content
 
54
 
55
  except Exception as e:
56
+ return f"An error occurred: {e}"
57
 
58
  # Define the Gradio interface
59
+ interface = gr.Interface(
60
+ fn=analyze_leaf_disease,
61
+ inputs=gr.Image(type="file", label="Upload an Image of a Leaf"),
62
+ outputs="text",
 
 
 
63
  title="Leaf Disease Detector",
64
+ description="Upload an image of a leaf, and this tool will identify the disease affecting it.",
65
  )
66
 
67
+ # Launch the interface
68
  if __name__ == "__main__":
69
+ interface.launch()