Jeff28 commited on
Commit
56deb05
ยท
verified ยท
1 Parent(s): 822c8b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -36
app.py CHANGED
@@ -1,78 +1,146 @@
 
1
  import gradio as gr
 
 
 
 
2
 
3
- # ===== Dummy Model & Utility Functions =====
4
- # Model A (for versions 1.x)
5
- def model_A(image):
6
- return "Model A predicts: [Example Disease A]"
7
 
8
- # Model B (for versions 2.x)
9
- def model_B(image):
10
- return "Model B predicts: [Example Disease B]"
 
11
 
12
- # Dummy classifier: Checks if image is a tomato leaf.
13
- def classifier(image):
14
- # Replace with actual classification logic.
15
- return "Tomato Leaf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # Dummy AI assistants for each model type.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def ai_assistant_v1(image, prediction):
19
- return "Advice from AI Assistant v1: Ensure proper irrigation and pest monitoring."
 
 
 
 
 
 
 
20
 
21
  def ai_assistant_v2(image, prediction):
22
- return "Advice from AI Assistant v2: Consider organic pesticides and crop rotation."
 
 
 
 
 
 
 
23
 
24
- # ===== Process Function for Versioned Logic =====
25
  def process_version(image, version):
26
  if image is None:
27
  return "No image provided."
28
 
29
  # --- Version 1.x (Model A) ---
30
  if version == "1.1":
31
- # Model A only + link to notebook
32
- result = model_A(image)
33
  return f"Model A Prediction: {result}\n\n[View Model A Training Notebook](https://huggingface.co/your-model-a-notebook)"
34
 
35
  elif version == "1.2":
36
- # Model A + AI Assistant
37
- result = model_A(image)
38
  advice = ai_assistant_v1(image, result)
39
  return f"Model A Prediction: {result}\nAdvice: {advice}"
40
 
41
  elif version == "1.3":
42
- # Classifier + Model A + AI Assistant
43
- cls_result = classifier(image)
44
  if cls_result != "Tomato Leaf":
45
  return "Classifier: The image is not a tomato leaf. Please try again."
46
- result = model_A(image)
47
  advice = ai_assistant_v1(image, result)
48
  return (f"Classifier: {cls_result}\nModel A Prediction: {result}\nAdvice: {advice}\n\n"
49
  f"[View Model A & Classifier Training Notebook](https://huggingface.co/your-model-a-classifier-notebook)")
50
 
51
  # --- Version 2.x (Model B) ---
52
  elif version == "2.1":
53
- # Model B only + link to notebook
54
- result = model_B(image)
55
  return f"Model B Prediction: {result}\n\n[View Model B Training Notebook](https://huggingface.co/your-model-b-notebook)"
56
 
57
  elif version == "2.2":
58
- # Model B + AI Assistant
59
- result = model_B(image)
60
  advice = ai_assistant_v2(image, result)
61
  return f"Model B Prediction: {result}\nAdvice: {advice}"
62
 
63
  elif version == "2.3":
64
- # Classifier + Model B + AI Assistant
65
- cls_result = classifier(image)
66
  if cls_result != "Tomato Leaf":
67
  return "Classifier: The image is not a tomato leaf. Please try again."
68
- result = model_B(image)
69
  advice = ai_assistant_v2(image, result)
70
  return (f"Classifier: {cls_result}\nModel B Prediction: {result}\nAdvice: {advice}\n\n"
71
  f"[View Model B & Classifier Training Notebook](https://huggingface.co/your-model-b-classifier-notebook)")
 
72
  else:
73
  return "Invalid version selected."
74
 
75
- # ===== Helper to Select Between Uploaded & Camera Image =====
76
  def combine_images(uploaded, camera):
77
  return camera if camera is not None else uploaded
78
 
@@ -99,11 +167,11 @@ def update_css(theme):
99
 
100
  # ===== Gradio Interface =====
101
  with gr.Blocks() as demo:
102
- # Hidden element for injecting CSS (initially Light theme)
103
  css_injector = gr.HTML(update_css("Light"))
104
 
105
  gr.Markdown("# ๐ŸŒฟ FarmVi8ion โ€“ AI-powered Crop Monitoring")
106
- gr.Markdown("Detect tomato leaf diseases and get AI-driven advice for your crops.")
107
 
108
  with gr.Row():
109
  # ----- Left Column (โ‰ˆ30%) -----
@@ -131,13 +199,12 @@ with gr.Blocks() as demo:
131
  - Model B & Classifier: [Training Notebook](https://huggingface.co/your-model-b-classifier-notebook)
132
  """
133
  )
134
-
135
  # ----- Right Column (โ‰ˆ70%) -----
136
  with gr.Column(scale=2):
137
  image_input = gr.Image(
138
  label="๐Ÿ“‚ Upload Tomato Leaf Image",
139
  type="pil",
140
- tool="editor" # enables basic image editing (crop, zoom, rotate)
141
  )
142
  camera_input = gr.Image(
143
  label="๐Ÿ“ธ Use Camera (Live Preview)",
@@ -147,10 +214,10 @@ with gr.Blocks() as demo:
147
 
148
  output = gr.Textbox(label="๐Ÿ“ Diagnosis & Advice", lines=8)
149
 
150
- # Update CSS dynamically based on theme choice
151
  theme_choice.change(fn=update_css, inputs=theme_choice, outputs=css_injector)
152
 
153
- # Process image on submit (combining uploaded & camera image)
154
  submit.click(
155
  fn=lambda uploaded, camera, ver: process_version(combine_images(uploaded, camera), ver),
156
  inputs=[image_input, camera_input, version],
 
1
+ import os
2
  import gradio as gr
3
+ import numpy as np
4
+ import requests
5
+ from tensorflow.keras.models import load_model
6
+ from PIL import Image
7
 
8
+ # ===== Hugging Face API Token =====
9
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN") # Ensure this is set in your environment
 
 
10
 
11
+ # ===== Load Trained Models =====
12
+ model_a = load_model("modela.h5")
13
+ model_b = load_model("modelb.h5")
14
+ classifier_model = load_model("classifier.h5")
15
 
16
+ # ===== Preprocessing Function =====
17
+ def preprocess_image(image, target_size=(224, 224)):
18
+ # Ensure the image is resized and normalized.
19
+ if isinstance(image, Image.Image):
20
+ img = image.resize(target_size)
21
+ else:
22
+ img = Image.fromarray(image).resize(target_size)
23
+ img_array = np.array(img) / 255.0
24
+ img_array = np.expand_dims(img_array, axis=0)
25
+ return img_array
26
+
27
+ # ===== Prediction Functions =====
28
+ def predict_model_a(image):
29
+ img = preprocess_image(image)
30
+ pred = model_a.predict(img)
31
+ # Replace with your own mapping from predictions to disease names.
32
+ return "Disease A detected" if np.argmax(pred) == 1 else "No disease"
33
+
34
+ def predict_model_b(image):
35
+ img = preprocess_image(image)
36
+ pred = model_b.predict(img)
37
+ return "Disease B detected" if np.argmax(pred) == 1 else "No disease"
38
+
39
+ def predict_classifier(image):
40
+ img = preprocess_image(image)
41
+ pred = classifier_model.predict(img)
42
+ # Assume classifier returns class 1 for a tomato leaf.
43
+ return "Tomato Leaf" if np.argmax(pred) == 1 else "Not Tomato Leaf"
44
+
45
+ # ===== Hugging Face Inference API Calls =====
46
+ def call_llama2(prompt):
47
+ """Call the Llama 2-7B Chat model on Hugging Face for conversational advice."""
48
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
49
+ payload = {"inputs": prompt, "parameters": {"max_new_tokens": 100}}
50
+ url = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf"
51
+ response = requests.post(url, headers=headers, json=payload)
52
+ if response.status_code == 200:
53
+ result = response.json()
54
+ if isinstance(result, list) and "generated_text" in result[0]:
55
+ return result[0]["generated_text"]
56
+ else:
57
+ return "No response from Llama 2."
58
+ else:
59
+ return f"Error calling Llama 2 API: {response.status_code}"
60
 
61
+ def call_openassistant(prompt):
62
+ """Call an OpenAssistant model on Hugging Face for conversational advice."""
63
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
64
+ payload = {"inputs": prompt, "parameters": {"max_new_tokens": 100}}
65
+ url = "https://api-inference.huggingface.co/models/OpenAssistant/oasst-sft-7-llama"
66
+ response = requests.post(url, headers=headers, json=payload)
67
+ if response.status_code == 200:
68
+ result = response.json()
69
+ if isinstance(result, list) and "generated_text" in result[0]:
70
+ return result[0]["generated_text"]
71
+ else:
72
+ return "No response from OpenAssistant."
73
+ else:
74
+ return f"Error calling OpenAssistant API: {response.status_code}"
75
+
76
+ # ===== AI Assistant Functions =====
77
  def ai_assistant_v1(image, prediction):
78
+ # Use Llama 2-7B Chat (Model A version)
79
+ if "No disease" in prediction:
80
+ prompt = ("You are an agricultural advisor. The tomato crop appears healthy. "
81
+ "Provide additional preventive tips and good practices for maintaining crop health.")
82
+ else:
83
+ prompt = (f"You are an agricultural advisor. A disease has been detected: {prediction}. "
84
+ "Provide detailed advice on how to manage and curb this disease, and explain more about it in simple terms.")
85
+ return call_llama2(prompt)
86
 
87
  def ai_assistant_v2(image, prediction):
88
+ # Use OpenAssistant (Model B version)
89
+ if "No disease" in prediction:
90
+ prompt = ("You are an agricultural advisor. The tomato crop appears healthy. "
91
+ "Offer additional preventive tips and guidelines for maintaining a healthy crop.")
92
+ else:
93
+ prompt = (f"You are an agricultural advisor. A disease has been detected: {prediction}. "
94
+ "Provide actionable steps and detailed advice on how to control and manage this disease in tomato crops.")
95
+ return call_openassistant(prompt)
96
 
97
+ # ===== Process Function Based on Version =====
98
  def process_version(image, version):
99
  if image is None:
100
  return "No image provided."
101
 
102
  # --- Version 1.x (Model A) ---
103
  if version == "1.1":
104
+ result = predict_model_a(image)
 
105
  return f"Model A Prediction: {result}\n\n[View Model A Training Notebook](https://huggingface.co/your-model-a-notebook)"
106
 
107
  elif version == "1.2":
108
+ result = predict_model_a(image)
 
109
  advice = ai_assistant_v1(image, result)
110
  return f"Model A Prediction: {result}\nAdvice: {advice}"
111
 
112
  elif version == "1.3":
113
+ cls_result = predict_classifier(image)
 
114
  if cls_result != "Tomato Leaf":
115
  return "Classifier: The image is not a tomato leaf. Please try again."
116
+ result = predict_model_a(image)
117
  advice = ai_assistant_v1(image, result)
118
  return (f"Classifier: {cls_result}\nModel A Prediction: {result}\nAdvice: {advice}\n\n"
119
  f"[View Model A & Classifier Training Notebook](https://huggingface.co/your-model-a-classifier-notebook)")
120
 
121
  # --- Version 2.x (Model B) ---
122
  elif version == "2.1":
123
+ result = predict_model_b(image)
 
124
  return f"Model B Prediction: {result}\n\n[View Model B Training Notebook](https://huggingface.co/your-model-b-notebook)"
125
 
126
  elif version == "2.2":
127
+ result = predict_model_b(image)
 
128
  advice = ai_assistant_v2(image, result)
129
  return f"Model B Prediction: {result}\nAdvice: {advice}"
130
 
131
  elif version == "2.3":
132
+ cls_result = predict_classifier(image)
 
133
  if cls_result != "Tomato Leaf":
134
  return "Classifier: The image is not a tomato leaf. Please try again."
135
+ result = predict_model_b(image)
136
  advice = ai_assistant_v2(image, result)
137
  return (f"Classifier: {cls_result}\nModel B Prediction: {result}\nAdvice: {advice}\n\n"
138
  f"[View Model B & Classifier Training Notebook](https://huggingface.co/your-model-b-classifier-notebook)")
139
+
140
  else:
141
  return "Invalid version selected."
142
 
143
+ # ===== Helper Function to Choose Between Uploaded & Camera Image =====
144
  def combine_images(uploaded, camera):
145
  return camera if camera is not None else uploaded
146
 
 
167
 
168
  # ===== Gradio Interface =====
169
  with gr.Blocks() as demo:
170
+ # Hidden element for CSS injection (initially Light theme)
171
  css_injector = gr.HTML(update_css("Light"))
172
 
173
  gr.Markdown("# ๐ŸŒฟ FarmVi8ion โ€“ AI-powered Crop Monitoring")
174
+ gr.Markdown("Detect tomato leaf diseases and get actionable advice on how to curb them.")
175
 
176
  with gr.Row():
177
  # ----- Left Column (โ‰ˆ30%) -----
 
199
  - Model B & Classifier: [Training Notebook](https://huggingface.co/your-model-b-classifier-notebook)
200
  """
201
  )
 
202
  # ----- Right Column (โ‰ˆ70%) -----
203
  with gr.Column(scale=2):
204
  image_input = gr.Image(
205
  label="๐Ÿ“‚ Upload Tomato Leaf Image",
206
  type="pil",
207
+ tool="editor" # Enables cropping, zooming, and rotating.
208
  )
209
  camera_input = gr.Image(
210
  label="๐Ÿ“ธ Use Camera (Live Preview)",
 
214
 
215
  output = gr.Textbox(label="๐Ÿ“ Diagnosis & Advice", lines=8)
216
 
217
+ # Update CSS dynamically based on theme selection.
218
  theme_choice.change(fn=update_css, inputs=theme_choice, outputs=css_injector)
219
 
220
+ # When submit is clicked, combine image inputs and process the selected version.
221
  submit.click(
222
  fn=lambda uploaded, camera, ver: process_version(combine_images(uploaded, camera), ver),
223
  inputs=[image_input, camera_input, version],