Spaces:
Sleeping
Sleeping
project added
Browse files
app.py
CHANGED
@@ -1,247 +1,4 @@
|
|
1 |
-
#
|
2 |
-
# import gradio as gr
|
3 |
-
# from gtts import gTTS
|
4 |
-
# import uuid
|
5 |
-
# import base64
|
6 |
-
# from io import BytesIO
|
7 |
-
# import os
|
8 |
-
# import logging
|
9 |
-
# import spacy
|
10 |
-
# from transformers import pipeline
|
11 |
-
# import torch
|
12 |
-
# import numpy as np
|
13 |
-
# from torchvision import transforms
|
14 |
-
# from PIL import Image
|
15 |
-
# import pathlib
|
16 |
-
|
17 |
-
# # Pathlib adjustment for Windows compatibility
|
18 |
-
# temp = pathlib.PosixPath
|
19 |
-
# pathlib.PosixPath = pathlib.WindowsPath
|
20 |
-
|
21 |
-
# # Set up logger
|
22 |
-
# logger = logging.getLogger(__name__)
|
23 |
-
# logger.setLevel(logging.DEBUG)
|
24 |
-
# console_handler = logging.StreamHandler()
|
25 |
-
# file_handler = logging.FileHandler('chatbot_log.log')
|
26 |
-
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
27 |
-
# console_handler.setFormatter(formatter)
|
28 |
-
# file_handler.setFormatter(formatter)
|
29 |
-
# logger.addHandler(console_handler)
|
30 |
-
# logger.addHandler(file_handler)
|
31 |
-
|
32 |
-
# # Initialize Groq Client
|
33 |
-
# client = Groq(api_key=os.getenv("GROQ_API_KEY_2"))
|
34 |
-
|
35 |
-
# # Initialize spaCy NLP model for named entity recognition (NER)
|
36 |
-
# nlp = spacy.load("en_core_web_sm")
|
37 |
-
|
38 |
-
# # Initialize sentiment analysis model using Hugging Face
|
39 |
-
# sentiment_analyzer = pipeline("sentiment-analysis")
|
40 |
-
|
41 |
-
# # Load pre-trained YOLOv5 model
|
42 |
-
# def load_yolov5_model():
|
43 |
-
# model = torch.hub.load(
|
44 |
-
# 'ultralytics/yolov5',
|
45 |
-
# 'custom',
|
46 |
-
# path='models/best.pt'
|
47 |
-
# )
|
48 |
-
# model.eval()
|
49 |
-
# return model
|
50 |
-
|
51 |
-
# model = load_yolov5_model()
|
52 |
-
|
53 |
-
# # Function to preprocess user input for better NLP understanding
|
54 |
-
# def preprocess_input(user_input):
|
55 |
-
# user_input = user_input.strip().lower()
|
56 |
-
# return user_input
|
57 |
-
|
58 |
-
# # Function for sentiment analysis (optional)
|
59 |
-
# def analyze_sentiment(user_input):
|
60 |
-
# result = sentiment_analyzer(user_input)
|
61 |
-
# return result[0]['label']
|
62 |
-
|
63 |
-
# # Function to extract medical entities from input using NER
|
64 |
-
# symptoms = [
|
65 |
-
# "fever", "cough", "headache", "nausea", "pain", "fatigue", "dizziness",
|
66 |
-
# "shortness of breath", "sore throat", "runny nose", "congestion", "diarrhea",
|
67 |
-
# "vomiting", "chills", "sweating", "loss of appetite", "insomnia",
|
68 |
-
# "itching", "rash", "swelling", "bleeding", "burning sensation",
|
69 |
-
# "weakness", "tingling", "numbness", "muscle cramps", "joint pain",
|
70 |
-
# "blurred vision", "double vision", "dry eyes", "sensitivity to light",
|
71 |
-
# "difficulty breathing", "palpitations", "chest pain", "back pain",
|
72 |
-
# "stomach ache", "abdominal pain", "weight loss", "weight gain",
|
73 |
-
# "frequent urination", "difficulty urinating", "anxiety", "depression",
|
74 |
-
# "irritability", "confusion", "memory loss", "bruising"
|
75 |
-
# ]
|
76 |
-
# diseases = [
|
77 |
-
# "diabetes", "cancer", "asthma", "flu", "pneumonia", "hypertension",
|
78 |
-
# "arthritis", "bronchitis", "migraine", "stroke", "heart attack",
|
79 |
-
# "coronary artery disease", "tuberculosis", "malaria", "dengue",
|
80 |
-
# "hepatitis", "anemia", "thyroid disease", "eczema", "psoriasis",
|
81 |
-
# "osteoporosis", "parkinson's", "alzheimer's", "depression",
|
82 |
-
# "anxiety disorder", "schizophrenia", "epilepsy", "bipolar disorder",
|
83 |
-
# "chronic kidney disease", "liver cirrhosis", "HIV", "AIDS",
|
84 |
-
# "covid-19", "cholera", "smallpox", "measles", "mumps",
|
85 |
-
# "rubella", "whooping cough", "obesity", "GERD", "IBS",
|
86 |
-
# "celiac disease", "ulcerative colitis", "Crohn's disease",
|
87 |
-
# "sleep apnea", "hypothyroidism", "hyperthyroidism"
|
88 |
-
# ]
|
89 |
-
|
90 |
-
# def extract_medical_entities(user_input):
|
91 |
-
# user_input = preprocess_input(user_input)
|
92 |
-
# medical_entities = []
|
93 |
-
# for word in user_input.split():
|
94 |
-
# if word in symptoms or word in diseases:
|
95 |
-
# medical_entities.append(word)
|
96 |
-
# return medical_entities
|
97 |
-
|
98 |
-
# # Function to encode the image
|
99 |
-
# def encode_image(uploaded_image):
|
100 |
-
# try:
|
101 |
-
# logger.debug("Encoding image...")
|
102 |
-
# buffered = BytesIO()
|
103 |
-
# uploaded_image.save(buffered, format="PNG")
|
104 |
-
# logger.debug("Image encoding complete.")
|
105 |
-
# return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
106 |
-
# except Exception as e:
|
107 |
-
# logger.error(f"Error encoding image: {e}")
|
108 |
-
# raise
|
109 |
-
|
110 |
-
# # Initialize messages
|
111 |
-
# def initialize_messages():
|
112 |
-
# return [{"role": "system", "content": '''You are Dr. HealthBuddy, a professional, empathetic, and knowledgeable virtual doctor chatbot.'''}]
|
113 |
-
|
114 |
-
# messages = initialize_messages()
|
115 |
-
|
116 |
-
# # Function for image prediction using YOLOv5
|
117 |
-
# def predict_image(image):
|
118 |
-
# try:
|
119 |
-
# if image is None:
|
120 |
-
# return "Error: No image uploaded.", "No description available."
|
121 |
-
|
122 |
-
# # Resize the image to match the model's expected input size
|
123 |
-
# image_resized = image.resize((224, 224))
|
124 |
-
|
125 |
-
# # Transform the image for the model
|
126 |
-
# transform = transforms.Compose([
|
127 |
-
# transforms.ToTensor(),
|
128 |
-
# transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
129 |
-
# ])
|
130 |
-
# im = transform(image_resized).unsqueeze(0) # Add batch dimension (BCHW)
|
131 |
-
|
132 |
-
# # Get predictions
|
133 |
-
# with torch.no_grad():
|
134 |
-
# output = model(im) # Raw model output (logits)
|
135 |
-
|
136 |
-
# # Apply softmax to get confidence scores
|
137 |
-
# softmax = torch.nn.Softmax(dim=1)
|
138 |
-
# probs = softmax(output)
|
139 |
-
|
140 |
-
# # Get the predicted class and its confidence score
|
141 |
-
# predicted_class_id = torch.argmax(probs, dim=1).item()
|
142 |
-
# confidence_score = probs[0, predicted_class_id].item()
|
143 |
-
|
144 |
-
# # Get predicted class name if available
|
145 |
-
# if hasattr(model, 'names'):
|
146 |
-
# class_name = model.names[predicted_class_id]
|
147 |
-
# prediction_result = f"Predicted Class: {class_name}\nConfidence: {confidence_score:.4f}"
|
148 |
-
# description = get_description(class_name) # Function to get description
|
149 |
-
# else:
|
150 |
-
# prediction_result = f"Predicted Class ID: {predicted_class_id}\nConfidence: {confidence_score:.4f}"
|
151 |
-
# description = "No description available."
|
152 |
-
|
153 |
-
# return prediction_result, description
|
154 |
-
|
155 |
-
# except Exception as e:
|
156 |
-
# logger.error(f"Error in image prediction: {e}")
|
157 |
-
# return f"An error occurred during image prediction: {e}", "No description available."
|
158 |
-
|
159 |
-
# # Function to get description based on predicted class
|
160 |
-
# def get_description(class_name):
|
161 |
-
# descriptions = {
|
162 |
-
# "bcc": "Basal cell carcinoma (BCC) is a type of skin cancer that begins in the basal cells. It often appears as a slightly transparent bump on the skin, though it can take other forms. BCC grows slowly and is unlikely to spread to other parts of the body, but early treatment is important to prevent damage to surrounding tissues.",
|
163 |
-
# "atopic": "Atopic dermatitis is a chronic skin condition characterized by itchy, inflamed skin. It is common in individuals with a family history of allergies or asthma.",
|
164 |
-
# "acne": "Acne is a skin condition that occurs when hair follicles become clogged with oil and dead skin cells. It often causes pimples, blackheads, and whiteheads, and is most common among teenagers.",
|
165 |
-
# }
|
166 |
-
# return descriptions.get(class_name.lower(), "No description available.")
|
167 |
-
|
168 |
-
# # Gradio Interface
|
169 |
-
# def chatbot_ui():
|
170 |
-
# with gr.Blocks() as demo:
|
171 |
-
# gr.Markdown("# Healthcare Chatbot Doctor")
|
172 |
-
# chat_history = gr.State([])
|
173 |
-
|
174 |
-
# with gr.Row():
|
175 |
-
# with gr.Column(scale=3):
|
176 |
-
# chatbot = gr.Chatbot(label="Responses", elem_id="chatbot")
|
177 |
-
# user_input = gr.Textbox(
|
178 |
-
# label="Ask a health-related question",
|
179 |
-
# placeholder="Describe your symptoms...",
|
180 |
-
# elem_id="user-input",
|
181 |
-
# lines=1,
|
182 |
-
# )
|
183 |
-
# with gr.Column(scale=1):
|
184 |
-
# uploaded_image = gr.Image(label="Upload an Image", type="pil")
|
185 |
-
# submit_btn = gr.Button("Submit")
|
186 |
-
# clear_btn = gr.Button("Clear")
|
187 |
-
# audio_output = gr.Audio(label="Audio Response")
|
188 |
-
|
189 |
-
# with gr.Row():
|
190 |
-
# with gr.Column():
|
191 |
-
# gr.Markdown("### Upload Image for Prediction")
|
192 |
-
# prediction_image = gr.Image(label="Upload Image", type="pil")
|
193 |
-
# predict_btn = gr.Button("Predict")
|
194 |
-
|
195 |
-
# with gr.Column():
|
196 |
-
# gr.Markdown("### Prediction Result")
|
197 |
-
# prediction_output = gr.Textbox(label="Result", interactive=False)
|
198 |
-
# gr.Markdown("### Description")
|
199 |
-
# description_output = gr.Textbox(label="Description", interactive=False)
|
200 |
-
# clear_prediction_btn = gr.Button("Clear Prediction")
|
201 |
-
|
202 |
-
# def handle_submit(user_query, image, history):
|
203 |
-
# logger.info("User submitted a query.")
|
204 |
-
# response, audio = customLLMBot(user_query, image, history)
|
205 |
-
# return response, audio, None, "", history
|
206 |
-
|
207 |
-
# def clear_prediction(prediction_image, prediction_output, description_output):
|
208 |
-
# return None, "", ""
|
209 |
-
|
210 |
-
# user_input.submit(
|
211 |
-
# handle_submit,
|
212 |
-
# inputs=[user_input, uploaded_image, chat_history],
|
213 |
-
# outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
214 |
-
# )
|
215 |
-
|
216 |
-
# submit_btn.click(
|
217 |
-
# handle_submit,
|
218 |
-
# inputs=[user_input, uploaded_image, chat_history],
|
219 |
-
# outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
220 |
-
# )
|
221 |
-
|
222 |
-
# clear_btn.click(
|
223 |
-
# lambda: ([], "", None, []),
|
224 |
-
# inputs=[],
|
225 |
-
# outputs=[chatbot, user_input, uploaded_image, chat_history],
|
226 |
-
# )
|
227 |
-
|
228 |
-
# predict_btn.click(
|
229 |
-
# predict_image,
|
230 |
-
# inputs=[prediction_image],
|
231 |
-
# outputs=[prediction_output, description_output],
|
232 |
-
# )
|
233 |
-
|
234 |
-
# clear_prediction_btn.click(
|
235 |
-
# clear_prediction,
|
236 |
-
# inputs=[prediction_image, prediction_output, description_output],
|
237 |
-
# outputs=[prediction_image, prediction_output, description_output],
|
238 |
-
# )
|
239 |
-
|
240 |
-
# return demo
|
241 |
-
|
242 |
-
# # Launch the interface
|
243 |
-
# chatbot_ui().launch(server_name="0.0.0.0", server_port=7860)
|
244 |
-
|
245 |
from groq import Groq
|
246 |
import gradio as gr
|
247 |
from gtts import gTTS
|
@@ -253,11 +10,15 @@ import logging
|
|
253 |
import spacy
|
254 |
from transformers import pipeline
|
255 |
import torch
|
|
|
256 |
import numpy as np
|
257 |
from torchvision import transforms
|
258 |
-
from PIL import Image
|
259 |
import pathlib
|
260 |
|
|
|
|
|
|
|
|
|
261 |
# Set up logger
|
262 |
logger = logging.getLogger(__name__)
|
263 |
logger.setLevel(logging.DEBUG)
|
@@ -272,31 +33,45 @@ logger.addHandler(file_handler)
|
|
272 |
# Initialize Groq Client
|
273 |
client = Groq(api_key=os.getenv("GROQ_API_KEY_2"))
|
274 |
|
275 |
-
# Initialize
|
276 |
-
|
277 |
-
from spacy.util import get_package_path
|
278 |
-
|
279 |
-
try:
|
280 |
-
model_path = get_package_path("en_core_web_sm")
|
281 |
-
nlp = spacy.load(model_path)
|
282 |
-
print("Model loaded using absolute path!")
|
283 |
-
except Exception as e:
|
284 |
-
print(f"Error: {e}")
|
285 |
|
|
|
|
|
286 |
|
287 |
# Initialize sentiment analysis model using Hugging Face
|
288 |
sentiment_analyzer = pipeline("sentiment-analysis")
|
289 |
|
290 |
-
|
|
|
|
|
291 |
def load_yolov5_model():
|
|
|
292 |
model = torch.hub.load(
|
293 |
-
'ultralytics/yolov5',
|
294 |
-
'custom',
|
295 |
-
path=
|
|
|
296 |
)
|
297 |
-
model.eval()
|
298 |
return model
|
299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
300 |
model = load_yolov5_model()
|
301 |
|
302 |
# Function to preprocess user input for better NLP understanding
|
@@ -365,11 +140,22 @@ messages = initialize_messages()
|
|
365 |
# Function for image prediction using YOLOv5
|
366 |
def predict_image(image):
|
367 |
try:
|
|
|
368 |
if image is None:
|
369 |
return "Error: No image uploaded.", "No description available."
|
370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
371 |
# Resize the image to match the model's expected input size
|
372 |
-
image_resized =
|
373 |
|
374 |
# Transform the image for the model
|
375 |
transform = transforms.Compose([
|
@@ -411,6 +197,7 @@ def get_description(class_name):
|
|
411 |
"bcc": "Basal cell carcinoma (BCC) is a type of skin cancer that begins in the basal cells. It often appears as a slightly transparent bump on the skin, though it can take other forms. BCC grows slowly and is unlikely to spread to other parts of the body, but early treatment is important to prevent damage to surrounding tissues.",
|
412 |
"atopic": "Atopic dermatitis is a chronic skin condition characterized by itchy, inflamed skin. It is common in individuals with a family history of allergies or asthma.",
|
413 |
"acne": "Acne is a skin condition that occurs when hair follicles become clogged with oil and dead skin cells. It often causes pimples, blackheads, and whiteheads, and is most common among teenagers.",
|
|
|
414 |
}
|
415 |
return descriptions.get(class_name.lower(), "No description available.")
|
416 |
|
@@ -418,10 +205,13 @@ def get_description(class_name):
|
|
418 |
def chatbot_ui():
|
419 |
with gr.Blocks() as demo:
|
420 |
gr.Markdown("# Healthcare Chatbot Doctor")
|
|
|
|
|
421 |
chat_history = gr.State([])
|
422 |
|
|
|
423 |
with gr.Row():
|
424 |
-
with gr.Column(scale=3):
|
425 |
chatbot = gr.Chatbot(label="Responses", elem_id="chatbot")
|
426 |
user_input = gr.Textbox(
|
427 |
label="Ask a health-related question",
|
@@ -429,57 +219,71 @@ def chatbot_ui():
|
|
429 |
elem_id="user-input",
|
430 |
lines=1,
|
431 |
)
|
432 |
-
with gr.Column(scale=1):
|
433 |
uploaded_image = gr.Image(label="Upload an Image", type="pil")
|
434 |
submit_btn = gr.Button("Submit")
|
435 |
clear_btn = gr.Button("Clear")
|
436 |
audio_output = gr.Audio(label="Audio Response")
|
437 |
|
|
|
438 |
with gr.Row():
|
|
|
439 |
with gr.Column():
|
440 |
gr.Markdown("### Upload Image for Prediction")
|
441 |
prediction_image = gr.Image(label="Upload Image", type="pil")
|
442 |
predict_btn = gr.Button("Predict")
|
443 |
|
|
|
444 |
with gr.Column():
|
445 |
gr.Markdown("### Prediction Result")
|
446 |
prediction_output = gr.Textbox(label="Result", interactive=False)
|
|
|
|
|
447 |
gr.Markdown("### Description")
|
448 |
description_output = gr.Textbox(label="Description", interactive=False)
|
|
|
|
|
449 |
clear_prediction_btn = gr.Button("Clear Prediction")
|
450 |
|
|
|
451 |
def handle_submit(user_query, image, history):
|
452 |
logger.info("User submitted a query.")
|
453 |
response, audio = customLLMBot(user_query, image, history)
|
454 |
return response, audio, None, "", history
|
455 |
|
|
|
456 |
def clear_prediction(prediction_image, prediction_output, description_output):
|
457 |
return None, "", ""
|
458 |
|
|
|
459 |
user_input.submit(
|
460 |
handle_submit,
|
461 |
inputs=[user_input, uploaded_image, chat_history],
|
462 |
outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
463 |
)
|
464 |
|
|
|
465 |
submit_btn.click(
|
466 |
handle_submit,
|
467 |
inputs=[user_input, uploaded_image, chat_history],
|
468 |
outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
469 |
)
|
470 |
|
|
|
471 |
clear_btn.click(
|
472 |
lambda: ([], "", None, []),
|
473 |
inputs=[],
|
474 |
outputs=[chatbot, user_input, uploaded_image, chat_history],
|
475 |
)
|
476 |
|
|
|
477 |
predict_btn.click(
|
478 |
predict_image,
|
479 |
inputs=[prediction_image],
|
480 |
-
outputs=[prediction_output, description_output],
|
481 |
)
|
482 |
|
|
|
483 |
clear_prediction_btn.click(
|
484 |
clear_prediction,
|
485 |
inputs=[prediction_image, prediction_output, description_output],
|
@@ -489,4 +293,7 @@ def chatbot_ui():
|
|
489 |
return demo
|
490 |
|
491 |
# Launch the interface
|
492 |
-
chatbot_ui().launch(server_name="
|
|
|
|
|
|
|
|
1 |
+
# Import necessary libraries
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from groq import Groq
|
3 |
import gradio as gr
|
4 |
from gtts import gTTS
|
|
|
10 |
import spacy
|
11 |
from transformers import pipeline
|
12 |
import torch
|
13 |
+
import cv2
|
14 |
import numpy as np
|
15 |
from torchvision import transforms
|
|
|
16 |
import pathlib
|
17 |
|
18 |
+
# Pathlib adjustment for Windows compatibility
|
19 |
+
temp = pathlib.PosixPath
|
20 |
+
pathlib.PosixPath = pathlib.WindowsPath
|
21 |
+
|
22 |
# Set up logger
|
23 |
logger = logging.getLogger(__name__)
|
24 |
logger.setLevel(logging.DEBUG)
|
|
|
33 |
# Initialize Groq Client
|
34 |
client = Groq(api_key=os.getenv("GROQ_API_KEY_2"))
|
35 |
|
36 |
+
# Initialize Groq Client
|
37 |
+
#client = Groq(api_key="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")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
# Initialize spaCy NLP model for named entity recognition (NER)
|
40 |
+
nlp = spacy.load("en_core_web_sm")
|
41 |
|
42 |
# Initialize sentiment analysis model using Hugging Face
|
43 |
sentiment_analyzer = pipeline("sentiment-analysis")
|
44 |
|
45 |
+
import torch
|
46 |
+
import os
|
47 |
+
|
48 |
def load_yolov5_model():
|
49 |
+
# Load model from Hugging Face Hub or local path
|
50 |
model = torch.hub.load(
|
51 |
+
'ultralytics/yolov5', # Use the official YOLOv5 repo
|
52 |
+
'custom',
|
53 |
+
path='models/best.pt', # Relative path to the model file
|
54 |
+
source='local' # Change to 'github' if loading from the official repo
|
55 |
)
|
|
|
56 |
return model
|
57 |
|
58 |
+
# Example usage
|
59 |
+
if __name__ == "__main__":
|
60 |
+
model = load_yolov5_model()
|
61 |
+
print("Model loaded successfully!")
|
62 |
+
|
63 |
+
|
64 |
+
# Load pre-trained YOLOv5 model
|
65 |
+
# def load_yolov5_model():
|
66 |
+
# model = torch.hub.load(
|
67 |
+
# r'C:\Users\RESHMA R B\OneDrive\Documents\Desktop\project_without_malayalam\chatbot2\yolov5',
|
68 |
+
# 'custom',
|
69 |
+
# path=r"C:\Users\RESHMA R B\OneDrive\Documents\Desktop\project_without_malayalam\chatbot2\models\best.pt",
|
70 |
+
# source="local"
|
71 |
+
# )
|
72 |
+
# model.eval()
|
73 |
+
# return model
|
74 |
+
|
75 |
model = load_yolov5_model()
|
76 |
|
77 |
# Function to preprocess user input for better NLP understanding
|
|
|
140 |
# Function for image prediction using YOLOv5
|
141 |
def predict_image(image):
|
142 |
try:
|
143 |
+
# Debug: Check if the image is None
|
144 |
if image is None:
|
145 |
return "Error: No image uploaded.", "No description available."
|
146 |
|
147 |
+
# Convert PIL image to NumPy array
|
148 |
+
image_np = np.array(image) # Convert PIL image to NumPy array
|
149 |
+
|
150 |
+
# Handle grayscale images
|
151 |
+
if len(image_np.shape) == 2: # Grayscale image
|
152 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
|
153 |
+
|
154 |
+
# Convert RGB to BGR (OpenCV uses BGR by default)
|
155 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
156 |
+
|
157 |
# Resize the image to match the model's expected input size
|
158 |
+
image_resized = cv2.resize(image_np, (224, 224))
|
159 |
|
160 |
# Transform the image for the model
|
161 |
transform = transforms.Compose([
|
|
|
197 |
"bcc": "Basal cell carcinoma (BCC) is a type of skin cancer that begins in the basal cells. It often appears as a slightly transparent bump on the skin, though it can take other forms. BCC grows slowly and is unlikely to spread to other parts of the body, but early treatment is important to prevent damage to surrounding tissues.",
|
198 |
"atopic": "Atopic dermatitis is a chronic skin condition characterized by itchy, inflamed skin. It is common in individuals with a family history of allergies or asthma.",
|
199 |
"acne": "Acne is a skin condition that occurs when hair follicles become clogged with oil and dead skin cells. It often causes pimples, blackheads, and whiteheads, and is most common among teenagers.",
|
200 |
+
# Add more descriptions as needed
|
201 |
}
|
202 |
return descriptions.get(class_name.lower(), "No description available.")
|
203 |
|
|
|
205 |
def chatbot_ui():
|
206 |
with gr.Blocks() as demo:
|
207 |
gr.Markdown("# Healthcare Chatbot Doctor")
|
208 |
+
|
209 |
+
# State for user chat history
|
210 |
chat_history = gr.State([])
|
211 |
|
212 |
+
# Layout for chatbot and input box alignment
|
213 |
with gr.Row():
|
214 |
+
with gr.Column(scale=3): # Main column for chatbot
|
215 |
chatbot = gr.Chatbot(label="Responses", elem_id="chatbot")
|
216 |
user_input = gr.Textbox(
|
217 |
label="Ask a health-related question",
|
|
|
219 |
elem_id="user-input",
|
220 |
lines=1,
|
221 |
)
|
222 |
+
with gr.Column(scale=1): # Side column for image and buttons
|
223 |
uploaded_image = gr.Image(label="Upload an Image", type="pil")
|
224 |
submit_btn = gr.Button("Submit")
|
225 |
clear_btn = gr.Button("Clear")
|
226 |
audio_output = gr.Audio(label="Audio Response")
|
227 |
|
228 |
+
# New section for image prediction (left and right layout)
|
229 |
with gr.Row():
|
230 |
+
# Left side: Upload image
|
231 |
with gr.Column():
|
232 |
gr.Markdown("### Upload Image for Prediction")
|
233 |
prediction_image = gr.Image(label="Upload Image", type="pil")
|
234 |
predict_btn = gr.Button("Predict")
|
235 |
|
236 |
+
# Right side: Prediction result and description
|
237 |
with gr.Column():
|
238 |
gr.Markdown("### Prediction Result")
|
239 |
prediction_output = gr.Textbox(label="Result", interactive=False)
|
240 |
+
|
241 |
+
# Description column
|
242 |
gr.Markdown("### Description")
|
243 |
description_output = gr.Textbox(label="Description", interactive=False)
|
244 |
+
|
245 |
+
# Clear button for prediction result (below description box)
|
246 |
clear_prediction_btn = gr.Button("Clear Prediction")
|
247 |
|
248 |
+
# Define actions
|
249 |
def handle_submit(user_query, image, history):
|
250 |
logger.info("User submitted a query.")
|
251 |
response, audio = customLLMBot(user_query, image, history)
|
252 |
return response, audio, None, "", history
|
253 |
|
254 |
+
# Clear prediction result and image
|
255 |
def clear_prediction(prediction_image, prediction_output, description_output):
|
256 |
return None, "", ""
|
257 |
|
258 |
+
# Submit on pressing Enter key
|
259 |
user_input.submit(
|
260 |
handle_submit,
|
261 |
inputs=[user_input, uploaded_image, chat_history],
|
262 |
outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
263 |
)
|
264 |
|
265 |
+
# Submit on button click
|
266 |
submit_btn.click(
|
267 |
handle_submit,
|
268 |
inputs=[user_input, uploaded_image, chat_history],
|
269 |
outputs=[chatbot, audio_output, uploaded_image, user_input, chat_history],
|
270 |
)
|
271 |
|
272 |
+
# Action for clearing all fields
|
273 |
clear_btn.click(
|
274 |
lambda: ([], "", None, []),
|
275 |
inputs=[],
|
276 |
outputs=[chatbot, user_input, uploaded_image, chat_history],
|
277 |
)
|
278 |
|
279 |
+
# Action for image prediction
|
280 |
predict_btn.click(
|
281 |
predict_image,
|
282 |
inputs=[prediction_image],
|
283 |
+
outputs=[prediction_output, description_output], # Update both outputs
|
284 |
)
|
285 |
|
286 |
+
# Action for clearing prediction result and image
|
287 |
clear_prediction_btn.click(
|
288 |
clear_prediction,
|
289 |
inputs=[prediction_image, prediction_output, description_output],
|
|
|
293 |
return demo
|
294 |
|
295 |
# Launch the interface
|
296 |
+
#chatbot_ui().launch(server_name="localhost", server_port=7860)
|
297 |
+
|
298 |
+
# Launch the interface
|
299 |
+
chatbot_ui().launch(server_name="0.0.0.0", server_port=7860)
|