Spaces:
Sleeping
Sleeping
modified
Browse files
app.py
CHANGED
|
@@ -2,163 +2,133 @@ from groq import Groq
|
|
| 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 |
-
|
| 9 |
-
|
| 10 |
-
# Set up logger
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
logger.setLevel(logging.DEBUG)
|
| 13 |
-
console_handler = logging.StreamHandler()
|
| 14 |
-
file_handler = logging.FileHandler('chatbot_log.log')
|
| 15 |
-
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 16 |
-
console_handler.setFormatter(formatter)
|
| 17 |
-
file_handler.setFormatter(formatter)
|
| 18 |
-
logger.addHandler(console_handler)
|
| 19 |
-
logger.addHandler(file_handler)
|
| 20 |
-
|
| 21 |
-
# Initialize Groq Client
|
| 22 |
client = Groq(api_key=os.getenv("GROQ_API_KEY_2"))
|
| 23 |
|
| 24 |
# client = Groq(
|
| 25 |
# api_key="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",
|
| 26 |
# )
|
| 27 |
|
| 28 |
-
# Function to encode the image
|
| 29 |
-
def encode_image(uploaded_image):
|
| 30 |
-
try:
|
| 31 |
-
logger.debug("Encoding image...")
|
| 32 |
-
buffered = BytesIO()
|
| 33 |
-
uploaded_image.save(buffered, format="PNG") # Ensure the correct format
|
| 34 |
-
logger.debug("Image encoding complete.")
|
| 35 |
-
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 36 |
-
except Exception as e:
|
| 37 |
-
logger.error(f"Error encoding image: {e}")
|
| 38 |
-
raise
|
| 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 |
-
messages=messages,
|
| 70 |
-
)
|
| 71 |
-
logger.info("Image processed successfully.")
|
| 72 |
-
else:
|
| 73 |
-
# Process text input
|
| 74 |
-
logger.info("Processing text input...")
|
| 75 |
-
messages = [
|
| 76 |
-
{"role": "system", "content": "You are Dr. HealthBuddy, a professional virtual doctor chatbot."},
|
| 77 |
-
{"role": "user", "content": user_input},
|
| 78 |
-
]
|
| 79 |
-
response = client.chat.completions.create(
|
| 80 |
-
model="llama-3.2-11b-vision-preview",
|
| 81 |
-
messages=messages,
|
| 82 |
-
)
|
| 83 |
-
logger.info("Text processed successfully.")
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
logger.debug(f"LLM reply: {LLM_reply}")
|
| 88 |
|
| 89 |
-
|
| 90 |
-
chat_history.append(("Bot", LLM_reply))
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
tts = gTTS(LLM_reply, lang='en')
|
| 95 |
tts.save(audio_file)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# Return the chat history (all Q&A) and the audio file
|
| 99 |
-
return [(entry[0], entry[1]) for entry in chat_history], audio_file
|
| 100 |
|
| 101 |
except Exception as e:
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
|
| 107 |
-
# Gradio Interface
|
| 108 |
-
def chatbot_ui():
|
| 109 |
-
chat_history = [] # Initialize empty chat history for the session
|
| 110 |
|
|
|
|
|
|
|
| 111 |
with gr.Blocks() as demo:
|
| 112 |
gr.Markdown("# Healthcare Chatbot Doctor")
|
| 113 |
|
| 114 |
-
#
|
| 115 |
with gr.Row():
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
inputs=[user_input, uploaded_image],
|
| 140 |
-
outputs=[chatbot, audio_output, user_input],
|
| 141 |
)
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
outputs=[chatbot, audio_output, user_input],
|
| 148 |
)
|
| 149 |
|
| 150 |
-
#
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
return demo
|
| 159 |
|
| 160 |
|
| 161 |
-
# Launch the
|
| 162 |
chatbot_ui().launch(server_name="0.0.0.0", server_port=7860)
|
| 163 |
|
| 164 |
#chatbot_ui().launch(server_name="localhost", server_port=7860)
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from gtts import gTTS
|
| 4 |
import uuid
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
+
|
| 7 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
client = Groq(api_key=os.getenv("GROQ_API_KEY_2"))
|
| 9 |
|
| 10 |
# client = Groq(
|
| 11 |
# api_key="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",
|
| 12 |
# )
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
def initialize_messages():
|
| 16 |
+
return [{"role": "system",
|
| 17 |
+
"content": '''You are Dr. HealthBuddy, a highly experienced and professional virtual doctor chatbot with over 40 years of expertise across all medical fields. You provide health-related information, symptom guidance, lifestyle tips, and actionable solutions using a dataset to reference common symptoms and conditions. Your goal is to offer concise, empathetic, and knowledgeable responses tailored to each patient’s needs.
|
| 18 |
+
|
| 19 |
+
You only respond to health-related inquiries and strive to provide the best possible guidance. Your responses should include clear explanations, actionable steps, and when necessary, advise patients to seek in-person care from a healthcare provider for a proper diagnosis or treatment. Maintain a friendly, professional, and empathetic tone in all your interactions.
|
| 20 |
+
|
| 21 |
+
*Prompt Template:*
|
| 22 |
+
- *Input*: Patient’s health concerns, including symptoms, questions, or specific issues they mention.
|
| 23 |
+
- *Response*: Start with a polite acknowledgment of the patient’s concern. Provide a clear, concise explanation and suggest practical, actionable steps based on the dataset. If needed, advise on when to consult a healthcare provider.
|
| 24 |
+
|
| 25 |
+
*Examples:*
|
| 26 |
+
|
| 27 |
+
- *User:* "I have skin rash and itching. What could it be?"
|
| 28 |
+
*Response:* "According to the data, skin rash and itching are common symptoms of conditions like fungal infections. You can try keeping the affected area dry and clean, and using over-the-counter antifungal creams. If the rash persists or worsens, please consult a dermatologist."
|
| 29 |
+
|
| 30 |
+
- *User:* "What might cause nodal skin eruptions?"
|
| 31 |
+
*Response:* "Nodal skin eruptions could be linked to conditions such as fungal infections. It's best to monitor the symptoms and avoid scratching. For a proper diagnosis, consider visiting a healthcare provider."
|
| 32 |
+
|
| 33 |
+
- *User:* "I am a 22-year-old female diagnosed with hypothyroidism. I've gained 10 kg recently. What should I do?"
|
| 34 |
+
*Response:* "Hi. You have done well managing your hypothyroidism. For effective weight loss, focus on a balanced diet rich in vegetables, lean proteins, and whole grains. Pair this with regular exercise like brisk walking or yoga. Also, consult your endocrinologist to ensure your thyroid levels are well-controlled. Let me know if you have more questions."
|
| 35 |
+
|
| 36 |
+
- *User:* "I’ve been feeling discomfort between my shoulder blades after sitting for long periods. What could this be?"
|
| 37 |
+
*Response:* "Hello. The discomfort between your shoulder blades could be related to posture or strain. Try adjusting your sitting position and consider ergonomic changes to your workspace. Over-the-counter pain relievers or hot compresses may help. If the pain persists, consult an orthopedic specialist for further evaluation."
|
| 38 |
+
|
| 39 |
+
Always ensure the tone remains compassionate, and offer educational insights while stressing that you are not a substitute for professional medical advice. Encourage users to consult a healthcare provider for any serious or persistent health concerns.'''
|
| 40 |
+
}]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
messages_prmt = initialize_messages()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
def customLLMBot(user_input,history):
|
| 46 |
+
global messages_prmt
|
|
|
|
| 47 |
|
| 48 |
+
messages_prmt.append({"role": "user", "content": user_input})
|
|
|
|
| 49 |
|
| 50 |
+
response = client.chat.completions.create(
|
| 51 |
+
messages=messages_prmt,
|
| 52 |
+
model="llama3-8b-8192",
|
| 53 |
+
)
|
| 54 |
+
print(response)
|
| 55 |
+
LLM_reply = response.choices[0].message.content
|
| 56 |
+
messages_prmt.append({"role": "assistant", "content": LLM_reply})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
audio_file = f"response_{uuid.uuid4().hex}.mp3"
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
tts = gTTS(LLM_reply, lang='en')
|
| 64 |
tts.save(audio_file)
|
| 65 |
+
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
except Exception as e:
|
| 68 |
+
return f"Error generating audio: {str(e)}", None
|
| 69 |
+
|
| 70 |
+
# Return user input and bot response in tuple format
|
| 71 |
+
return [(user_input,LLM_reply)],audio_file
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
|
| 76 |
+
def chatbot_ui():
|
| 77 |
with gr.Blocks() as demo:
|
| 78 |
gr.Markdown("# Healthcare Chatbot Doctor")
|
| 79 |
|
| 80 |
+
# Use inline styles if you want custom width for user input
|
| 81 |
with gr.Row():
|
| 82 |
+
chatbot = gr.Chatbot(label="English Responses")
|
| 83 |
+
|
| 84 |
+
user_input = gr.Textbox(label="Ask anything related to your health condition",
|
| 85 |
+
placeholder="Enter your symptoms here...",
|
| 86 |
+
elem_id="user-input",
|
| 87 |
+
lines=1)
|
| 88 |
+
|
| 89 |
+
with gr.Row():
|
| 90 |
+
|
| 91 |
+
submit_btn = gr.Button("Submit") # Submit button with a send icon
|
| 92 |
+
clear_btn = gr.Button("Clear")
|
| 93 |
+
|
| 94 |
+
with gr.Row():
|
| 95 |
+
audio_output = gr.Audio(label="Audio Response")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# Combine submit button and Enter key functionality
|
| 101 |
+
submit_action = submit_btn.click(
|
| 102 |
+
customLLMBot,
|
| 103 |
+
inputs=[user_input],
|
| 104 |
+
outputs=[chatbot, audio_output],
|
|
|
|
|
|
|
| 105 |
)
|
| 106 |
|
| 107 |
+
user_input_action = user_input.submit(
|
| 108 |
+
customLLMBot,
|
| 109 |
+
inputs=[user_input],
|
| 110 |
+
outputs=[chatbot, audio_output],
|
|
|
|
| 111 |
)
|
| 112 |
|
| 113 |
+
# Reset the textbox after submission
|
| 114 |
+
for action in [submit_action, user_input_action]:
|
| 115 |
+
action.then(
|
| 116 |
+
lambda: "", # Clear input box
|
| 117 |
+
inputs=[],
|
| 118 |
+
outputs=user_input,
|
| 119 |
+
)
|
| 120 |
|
| 121 |
+
# Clear button functionality
|
| 122 |
+
clear_btn.click(
|
| 123 |
+
lambda: ([], "", None, [], None),
|
| 124 |
+
inputs=[],
|
| 125 |
+
outputs=[chatbot, user_input, audio_output],
|
| 126 |
+
)
|
| 127 |
|
| 128 |
return demo
|
| 129 |
|
| 130 |
|
| 131 |
+
# Launch the chatbot UI
|
| 132 |
chatbot_ui().launch(server_name="0.0.0.0", server_port=7860)
|
| 133 |
|
| 134 |
#chatbot_ui().launch(server_name="localhost", server_port=7860)
|