Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,78 +1,146 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
# =====
|
| 4 |
-
#
|
| 5 |
-
def model_A(image):
|
| 6 |
-
return "Model A predicts: [Example Disease A]"
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
def
|
| 14 |
-
#
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def ai_assistant_v1(image, prediction):
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def ai_assistant_v2(image, prediction):
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
# ===== Process Function
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 =
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 =
|
| 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
|
| 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
|
| 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
|
| 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" #
|
| 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
|
| 151 |
theme_choice.change(fn=update_css, inputs=theme_choice, outputs=css_injector)
|
| 152 |
|
| 153 |
-
#
|
| 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],
|