Reshmarb commited on
Commit
4dc0555
·
1 Parent(s): c87c4af
Files changed (1) hide show
  1. app.py +96 -126
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
- import logging
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
- # Function to handle text and image inputs
41
- def customLLMBot(user_input, uploaded_image, chat_history):
42
- try:
43
- logger.info("Processing input...")
44
-
45
- # Append user input to the chat history
46
- chat_history.append(("User", user_input))
47
-
48
- if uploaded_image is not None:
49
- # Encode the image to base64
50
- base64_image = encode_image(uploaded_image)
51
-
52
- # Log the image size and type
53
- logger.debug(f"Image received, size: {len(base64_image)} bytes")
54
-
55
- # Create a message specifically for image prompts
56
- messages = [
57
- {
58
- "role": "user",
59
- "content": [
60
- {"type": "text", "text": "What's in this image?"},
61
- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}]
62
- }
63
- ]
64
-
65
- logger.info("Sending image to Groq API for processing...")
66
- # Send the image message to the Groq API
67
- response = client.chat.completions.create(
68
- model="llama-3.2-11b-vision-preview",
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
- # Extract the reply
86
- LLM_reply = response.choices[0].message.content
87
- logger.debug(f"LLM reply: {LLM_reply}")
88
 
89
- # Append the bot's response to the chat history
90
- chat_history.append(("Bot", LLM_reply))
91
 
92
- # Generate audio for response
93
- audio_file = f"response_{uuid.uuid4().hex}.mp3"
 
 
 
 
 
 
 
 
 
 
 
94
  tts = gTTS(LLM_reply, lang='en')
95
  tts.save(audio_file)
96
- logger.info(f"Audio response saved as {audio_file}")
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
- # Handle errors gracefully
103
- logger.error(f"Error in customLLMBot function: {e}")
104
- return [("User", f"An error occurred: {e}")], None
 
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
- # Layout for chatbot and input box alignment
115
  with gr.Row():
116
- with gr.Column(scale=3): # Main column for chatbot
117
- chatbot = gr.Chatbot(label="Responses", elem_id="chatbot")
118
- user_input = gr.Textbox(
119
- label="Ask a health-related question",
120
- placeholder="Describe your symptoms...",
121
- elem_id="user-input",
122
- lines=1,
123
- )
124
- with gr.Column(scale=1): # Side column for image and buttons
125
- uploaded_image = gr.Image(label="Upload an Image", type="pil")
126
- submit_btn = gr.Button("Submit")
127
- clear_btn = gr.Button("Clear")
128
- audio_output = gr.Audio(label="Audio Response")
129
-
130
- # Define actions
131
- def handle_submit(user_query, image):
132
- logger.info("User submitted a query.")
133
- response, audio = customLLMBot(user_query, image, chat_history)
134
- return response, audio, ""
135
-
136
- # Submit on pressing Enter key
137
- user_input.submit(
138
- handle_submit,
139
- inputs=[user_input, uploaded_image],
140
- outputs=[chatbot, audio_output, user_input],
141
  )
142
 
143
- # Submit on button click
144
- submit_btn.click(
145
- handle_submit,
146
- inputs=[user_input, uploaded_image],
147
- outputs=[chatbot, audio_output, user_input],
148
  )
149
 
150
- # Action for clearing all fields and resetting chat history
151
- def clear_chat():
152
- nonlocal chat_history
153
- chat_history = [] # Reset chat history for new session
154
- return [], "", None, None
 
 
155
 
156
- clear_btn.click(clear_chat, inputs=[], outputs=[chatbot, user_input, uploaded_image, audio_output])
 
 
 
 
 
157
 
158
  return demo
159
 
160
 
161
- # Launch the interface
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)