Emmanuel Frimpong Asante
commited on
Commit
·
6b85e51
1
Parent(s):
211868f
update space
Browse files
app.py
CHANGED
@@ -1,258 +1,249 @@
|
|
1 |
-
# File: app.py
|
2 |
-
|
3 |
-
# Import necessary libraries
|
4 |
import os
|
5 |
-
import
|
6 |
-
from
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
from
|
|
|
11 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
12 |
-
from flask import Flask, render_template, request, redirect, url_for, session
|
13 |
-
from celery import Celery
|
14 |
-
import time
|
15 |
-
import threading
|
16 |
-
import gunicorn.app.base
|
17 |
-
from six import iteritems
|
18 |
-
|
19 |
-
# Setup logging for better monitoring
|
20 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
21 |
-
logger = logging.getLogger(__name__)
|
22 |
-
|
23 |
-
# Flask app setup
|
24 |
-
app = Flask(__name__)
|
25 |
-
app.secret_key = os.environ.get("SECRET_KEY", "default_secret_key")
|
26 |
|
27 |
-
#
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
33 |
|
34 |
-
# MongoDB Setup for
|
|
|
35 |
MONGO_URI = os.environ.get("MONGO_URI")
|
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 |
try:
|
78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
except Exception as e:
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
# Initialize the bot instance
|
97 |
-
|
98 |
-
bot = PoultryFarmBot(
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
tokenizer =
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
logger.info("Adding padding token to tokenizer.")
|
117 |
-
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
118 |
-
model.resize_token_embeddings(len(tokenizer))
|
119 |
-
logger.info("Model and tokenizer loaded successfully.")
|
120 |
-
model_loading_event.set() # Set the event to indicate that the model is loaded
|
121 |
-
except Exception as e:
|
122 |
-
logger.error(f"Failed to load Llama 3.2 model or tokenizer: {e}")
|
123 |
-
model_loading_event.set() # Set the event even if loading fails to prevent indefinite waiting
|
124 |
-
raise RuntimeError("Could not load the Llama 3.2 model or tokenizer. Please check the configuration.")
|
125 |
-
|
126 |
-
# Authentication function
|
127 |
-
def authenticate_user(username, password):
|
128 |
-
"""
|
129 |
-
Authenticate a user with username and password.
|
130 |
-
|
131 |
-
Args:
|
132 |
-
username (str): Username for authentication.
|
133 |
-
password (str): Password for authentication.
|
134 |
-
|
135 |
-
Returns:
|
136 |
-
bool: True if authentication is successful, False otherwise.
|
137 |
-
"""
|
138 |
-
logger.info(f"Authenticating user: {username}")
|
139 |
-
user = bot.authenticate_user(username, password)
|
140 |
-
if user:
|
141 |
-
logger.info(f"Authentication successful for user: {username}")
|
142 |
-
return True, user
|
143 |
-
else:
|
144 |
-
logger.warning(f"Authentication failed for user: {username}")
|
145 |
-
return False, None
|
146 |
-
|
147 |
-
# Registration function
|
148 |
-
def register_user(username, password):
|
149 |
-
"""
|
150 |
-
Register a new user with username and password.
|
151 |
-
|
152 |
-
Args:
|
153 |
-
username (str): Username for registration.
|
154 |
-
password (str): Password for registration.
|
155 |
-
|
156 |
-
Returns:
|
157 |
-
bool: True if registration is successful, False otherwise.
|
158 |
-
"""
|
159 |
-
logger.info(f"Registering user: {username}")
|
160 |
try:
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
except Exception as e:
|
169 |
-
|
170 |
-
return
|
171 |
-
|
172 |
-
#
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
session['username'] = username
|
183 |
-
|
184 |
-
# Start loading the model asynchronously after successful login
|
185 |
-
logger.info("Starting model loading asynchronously.")
|
186 |
-
load_model_and_tokenizer.apply_async()
|
187 |
-
|
188 |
-
return redirect(url_for('chatbot'))
|
189 |
-
else:
|
190 |
-
logger.warning("Authentication failed for user: %s", username)
|
191 |
-
return render_template('login.html', error="Invalid username or password.")
|
192 |
-
return render_template('login.html')
|
193 |
-
|
194 |
-
@app.route('/register', methods=['GET', 'POST'])
|
195 |
-
def register():
|
196 |
-
if request.method == 'POST':
|
197 |
-
username = request.form['username']
|
198 |
-
password = request.form['password']
|
199 |
-
logger.info(f"Registration attempt for user: {username}")
|
200 |
-
success = register_user(username, password)
|
201 |
-
if success:
|
202 |
-
logger.info("Registration successful for user: %s", username)
|
203 |
-
return redirect(url_for('login'))
|
204 |
else:
|
205 |
-
|
206 |
-
return
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
#
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
if __name__ == "__main__":
|
247 |
-
|
248 |
-
|
249 |
-
options = {
|
250 |
-
'bind': '%s:%s' % ('0.0.0.0', '5000'),
|
251 |
-
'workers': 2, # Set number of worker processes
|
252 |
-
'threads': 4, # Set number of threads per worker
|
253 |
-
'timeout': 120, # Set timeout for workers
|
254 |
-
}
|
255 |
-
StandaloneApplication(app, options).run()
|
256 |
-
except Exception as e:
|
257 |
-
logger.error(f"Failed to launch Flask server: {e}")
|
258 |
-
raise RuntimeError("Could not launch the Flask server. Please check the application setup.")
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import tensorflow as tf
|
3 |
+
from keras.models import load_model
|
4 |
+
import gradio as gr
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
from huggingface_hub import login
|
8 |
+
from pymongo import MongoClient
|
9 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Ensure the Hugging Face token is set
|
12 |
+
tok = os.environ.get('HF_Token')
|
13 |
+
if tok:
|
14 |
+
print("Logging in to Hugging Face with provided token...")
|
15 |
+
login(token=tok, add_to_git_credential=True)
|
16 |
+
print("Login successful.")
|
17 |
+
else:
|
18 |
+
print("Warning: Hugging Face token not found in environment variables.")
|
19 |
|
20 |
+
# MongoDB Setup (for inventory, record-keeping, etc.)
|
21 |
+
print("Setting up MongoDB connection...")
|
22 |
MONGO_URI = os.environ.get("MONGO_URI")
|
23 |
+
client = MongoClient(MONGO_URI)
|
24 |
+
db = client.poultry_farm # Database
|
25 |
+
print("MongoDB connection established.")
|
26 |
+
|
27 |
+
# Check GPU availability for TensorFlow
|
28 |
+
print("Checking TensorFlow setup...")
|
29 |
+
print("TensorFlow version:", tf.__version__)
|
30 |
+
print("Eager execution:", tf.executing_eagerly())
|
31 |
+
print("TensorFlow GPU Available:", tf.config.list_physical_devices('GPU'))
|
32 |
+
|
33 |
+
# Set TensorFlow to use mixed precision with available GPU
|
34 |
+
from tensorflow.keras import mixed_precision
|
35 |
+
if len(tf.config.list_physical_devices('GPU')) > 0:
|
36 |
+
# Set mixed precision policy to use float16 for better performance on GPU
|
37 |
+
policy = mixed_precision.Policy('mixed_float16')
|
38 |
+
mixed_precision.set_global_policy(policy)
|
39 |
+
print("Using mixed precision with GPU")
|
40 |
+
else:
|
41 |
+
print("Using CPU without mixed precision")
|
42 |
+
|
43 |
+
# Load TensorFlow/Keras models with GPU support if available, otherwise use CPU
|
44 |
+
try:
|
45 |
+
# Select device based on GPU availability
|
46 |
+
device_name = '/GPU:0' if len(tf.config.list_physical_devices('GPU')) > 0 else '/CPU:0'
|
47 |
+
print(f"Loading models on {device_name}...")
|
48 |
+
with tf.device(device_name):
|
49 |
+
# Load the poultry disease detection model
|
50 |
+
my_model = load_model('models/disease_model.h5', compile=True)
|
51 |
+
print("Disease detection model loaded successfully.")
|
52 |
+
# Load the authentication model
|
53 |
+
auth_model = load_model('models/auth_model.h5', compile=True)
|
54 |
+
print("Authentication model loaded successfully.")
|
55 |
+
print(f"Models loaded successfully on {device_name}.")
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Error loading models: {e}")
|
58 |
+
|
59 |
+
# Updated Disease names and recommendations based on fecal analysis
|
60 |
+
name_disease = {0: 'Coccidiosis', 1: 'Healthy', 2: 'New Castle Disease', 3: 'Salmonella'}
|
61 |
+
result = {0: 'Critical', 1: 'No issue', 2: 'Critical', 3: 'Critical'}
|
62 |
+
recommend = {
|
63 |
+
0: 'Panadol',
|
64 |
+
1: 'You have no need Medicine',
|
65 |
+
2: 'Percetamol',
|
66 |
+
3: 'Ponston'
|
67 |
+
}
|
68 |
+
|
69 |
+
class PoultryFarmBot:
|
70 |
+
def __init__(self):
|
71 |
+
self.db = db # MongoDB database for future use
|
72 |
+
print("PoultryFarmBot initialized with MongoDB connection.")
|
73 |
+
|
74 |
+
# Image Preprocessing for Fecal Disease Detection
|
75 |
+
def preprocess_image(self, image):
|
76 |
try:
|
77 |
+
print("Preprocessing image for disease detection...")
|
78 |
+
# Resize the image to match model input size (224x224)
|
79 |
+
image_check = cv2.resize(image, (224, 224))
|
80 |
+
# Add batch dimension to the image array
|
81 |
+
image_check = np.expand_dims(image_check, axis=0)
|
82 |
+
print("Image preprocessing successful.")
|
83 |
+
return image_check
|
84 |
except Exception as e:
|
85 |
+
print(f"Error in image preprocessing: {e}")
|
86 |
+
return None
|
87 |
+
|
88 |
+
# Predict Disease from Fecal Image
|
89 |
+
def predict(self, image):
|
90 |
+
print("Starting disease prediction...")
|
91 |
+
# Preprocess the image before prediction
|
92 |
+
image_check = self.preprocess_image(image)
|
93 |
+
if image_check is None:
|
94 |
+
print("Image preprocessing failed.")
|
95 |
+
return "Image preprocessing failed.", None, None, None
|
96 |
+
|
97 |
+
# Predict using the fecal disease detection model
|
98 |
+
try:
|
99 |
+
print("Running model prediction...")
|
100 |
+
indx = my_model.predict(image_check).argmax()
|
101 |
+
print(f"Prediction complete. Predicted index: {indx}")
|
102 |
+
name = name_disease.get(indx, "Unknown disease")
|
103 |
+
status = result.get(indx, "unknown condition")
|
104 |
+
recom = recommend.get(indx, "no recommendation available")
|
105 |
+
|
106 |
+
# Generate additional information about the disease using Llama 2
|
107 |
+
detailed_response = self.generate_disease_response(name, status, recom)
|
108 |
+
print("Generated detailed response using Llama 2.")
|
109 |
+
return detailed_response, name, status, recom
|
110 |
+
except Exception as e:
|
111 |
+
print(f"Error during prediction: {e}")
|
112 |
+
return "Error during prediction.", None, None, None
|
113 |
+
|
114 |
+
# Generate a detailed response using Llama 2 for disease information and recommendations
|
115 |
+
def generate_disease_response(self, disease_name, status, recommendation):
|
116 |
+
print("Generating detailed disease response...")
|
117 |
+
# Create a prompt for Llama 3 to generate detailed disease information
|
118 |
+
prompt = (
|
119 |
+
f"The disease detected is {disease_name}, classified as {status}. "
|
120 |
+
f"Recommended action: {recommendation}. "
|
121 |
+
f"Here is some information about {disease_name}: causes, symptoms, and treatment methods "
|
122 |
+
"to effectively manage this condition on a poultry farm."
|
123 |
+
)
|
124 |
+
response = llama2_response(prompt)
|
125 |
+
# Post-process to remove the prompt if accidentally included in the response
|
126 |
+
final_response = response.replace(prompt, "").strip()
|
127 |
+
print("Detailed disease response generated.")
|
128 |
+
return final_response
|
129 |
+
|
130 |
+
# Diagnose Disease Using Fecal Image
|
131 |
+
def diagnose_disease(self, image):
|
132 |
+
print("Diagnosing disease from provided image...")
|
133 |
+
# Ensure image is valid and has elements
|
134 |
+
if image is not None and image.size > 0:
|
135 |
+
return self.predict(image)
|
136 |
+
print("Invalid image provided.")
|
137 |
+
return "Please provide an image of poultry fecal matter for disease detection.", None, None, None
|
138 |
|
139 |
# Initialize the bot instance
|
140 |
+
print("Initializing PoultryFarmBot instance...")
|
141 |
+
bot = PoultryFarmBot()
|
142 |
+
|
143 |
+
# Load Llama 2 model and tokenizer for text generation
|
144 |
+
print("Loading Llama 3.2 model and tokenizer...")
|
145 |
+
model_name = "meta-llama/Llama-3.2-1B"
|
146 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
147 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
148 |
+
print("Llama 3.2 model and tokenizer loaded successfully.")
|
149 |
+
|
150 |
+
# Set the padding token to EOS token or add a new padding token
|
151 |
+
if tokenizer.pad_token is None:
|
152 |
+
print("Adding pad token to tokenizer...")
|
153 |
+
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
154 |
+
model.resize_token_embeddings(len(tokenizer))
|
155 |
+
print("Pad token added and model resized.")
|
156 |
+
|
157 |
+
# Define Llama 2 response generation
|
158 |
+
def llama2_response(user_input):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
try:
|
160 |
+
print("Generating response using Llama 2...")
|
161 |
+
# Tokenize user input for the Llama 2 model
|
162 |
+
inputs = tokenizer(user_input, return_tensors="pt", truncation=True, max_length=150, padding=True)
|
163 |
+
# Generate a response using the Llama 2 model
|
164 |
+
outputs = model.generate(
|
165 |
+
inputs["input_ids"],
|
166 |
+
max_length=150,
|
167 |
+
do_sample=True,
|
168 |
+
temperature=0.7,
|
169 |
+
pad_token_id=tokenizer.pad_token_id, # Use the newly set padding token
|
170 |
+
attention_mask=inputs["attention_mask"]
|
171 |
+
)
|
172 |
+
|
173 |
+
# Decode and return the response
|
174 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
175 |
+
print("Response generated successfully.")
|
176 |
+
return response
|
177 |
except Exception as e:
|
178 |
+
print(f"Error generating response: {e}")
|
179 |
+
return f"Error generating response: {str(e)}"
|
180 |
+
|
181 |
+
# Main chatbot function: handles both generative AI and disease detection
|
182 |
+
def chatbot_response(image, text):
|
183 |
+
print("Received user input for chatbot response...")
|
184 |
+
# If an image is provided, perform disease detection
|
185 |
+
if image is not None:
|
186 |
+
print("Image provided, attempting disease diagnosis...")
|
187 |
+
diagnosis, name, status, recom = bot.diagnose_disease(image)
|
188 |
+
if name and status and recom:
|
189 |
+
print("Diagnosis complete, returning detailed response.")
|
190 |
+
return diagnosis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
else:
|
192 |
+
print("Diagnosis failed or incomplete, returning diagnostic message only.")
|
193 |
+
return diagnosis # Return only the diagnostic message if no disease found
|
194 |
+
else:
|
195 |
+
print("No image provided, using Llama 3.2 for text response...")
|
196 |
+
# Use Llama 2 for more accurate responses to user text queries
|
197 |
+
return llama2_response(text)
|
198 |
+
|
199 |
+
# Gradio interface styling and layout with ChatGPT-like theme
|
200 |
+
print("Setting up Gradio interface...")
|
201 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", neutral_hue="slate")) as chatbot_interface:
|
202 |
+
gr.Markdown("# 🐔 Poultry Management Chatbot")
|
203 |
+
gr.Markdown(
|
204 |
+
"This chatbot can help you manage your poultry with conversational AI. Upload an image of poultry fecal matter for disease detection or just ask questions!"
|
205 |
+
)
|
206 |
+
|
207 |
+
with gr.Row():
|
208 |
+
with gr.Column(scale=1):
|
209 |
+
# Image input for poultry feces (optional)
|
210 |
+
fecal_image = gr.Image(
|
211 |
+
label="Upload Image of Poultry Feces (Optional)",
|
212 |
+
type="numpy",
|
213 |
+
elem_id="image-upload",
|
214 |
+
show_label=True,
|
215 |
+
)
|
216 |
+
with gr.Column(scale=2):
|
217 |
+
# Text input for user questions
|
218 |
+
user_input = gr.Textbox(
|
219 |
+
label="Type your question or chat with the assistant",
|
220 |
+
placeholder="Ask a question about poultry management...",
|
221 |
+
lines=3,
|
222 |
+
elem_id="user-input",
|
223 |
+
)
|
224 |
+
|
225 |
+
# Output box to display chatbot responses
|
226 |
+
output_box = gr.Textbox(
|
227 |
+
label="Response",
|
228 |
+
placeholder="The response will appear here...",
|
229 |
+
interactive=False,
|
230 |
+
lines=10,
|
231 |
+
elem_id="output-box",
|
232 |
+
)
|
233 |
+
|
234 |
+
# Submit button to trigger response generation
|
235 |
+
submit_button = gr.Button(
|
236 |
+
"Submit",
|
237 |
+
variant="primary",
|
238 |
+
elem_id="submit-button"
|
239 |
+
)
|
240 |
+
submit_button.click(
|
241 |
+
fn=chatbot_response,
|
242 |
+
inputs=[fecal_image, user_input],
|
243 |
+
outputs=[output_box]
|
244 |
+
)
|
245 |
+
|
246 |
+
# Launch the Gradio interface
|
247 |
if __name__ == "__main__":
|
248 |
+
print("Launching Gradio interface...")
|
249 |
+
chatbot_interface.queue().launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|