Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,47 +1,130 @@
|
|
1 |
import gradio as gr
|
2 |
import google.generativeai as genai
|
3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
# Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
|
6 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
# Initialize Gemini model
|
18 |
model = genai.GenerativeModel("gemini-1.5-flash",
|
19 |
generation_config={"temperature": 0.7, "max_output_tokens": 200})
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
# Chatbot function
|
22 |
-
def chatbot_function(message, history, mood):
|
23 |
-
# Initialize history if None
|
24 |
if history is None:
|
25 |
history = []
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
# Append mood to history if provided
|
28 |
if mood and mood != "Select mood (optional)":
|
29 |
history.append([f"I'm feeling {mood.lower()}.", None])
|
30 |
|
31 |
-
# Append user message
|
32 |
history.append([message, None])
|
33 |
|
34 |
-
#
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
# Generate response
|
38 |
try:
|
39 |
response = model.generate_content(prompt)
|
40 |
response_text = response.text
|
41 |
-
except Exception
|
42 |
response_text = "I'm here for you. Could you share a bit more so I can support you better?"
|
43 |
|
44 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
history[-1][1] = response_text
|
46 |
|
47 |
# Format history for display
|
@@ -54,7 +137,30 @@ def chatbot_function(message, history, mood):
|
|
54 |
|
55 |
return chat_display, history
|
56 |
|
57 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
def show_emergency_resources():
|
59 |
return """
|
60 |
**Crisis Support:**
|
@@ -63,8 +169,23 @@ def show_emergency_resources():
|
|
63 |
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
64 |
"""
|
65 |
|
66 |
-
# Gradio Interface
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
gr.Markdown("# Mental Health Support Chatbot")
|
69 |
gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
|
70 |
|
@@ -74,6 +195,20 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
74 |
label="How are you feeling today? (Optional)"
|
75 |
)
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
# Chat Interface
|
78 |
chatbot = gr.Textbox(
|
79 |
label="Conversation",
|
@@ -95,18 +230,32 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
95 |
emergency_btn = gr.Button("Emergency Resources")
|
96 |
emergency_output = gr.Markdown("")
|
97 |
|
98 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
history = gr.State()
|
100 |
|
101 |
# Event Handlers
|
102 |
submit_btn.click(
|
103 |
fn=chatbot_function,
|
104 |
-
inputs=[user_input, history, mood],
|
105 |
outputs=[chatbot, history]
|
106 |
)
|
107 |
user_input.submit(
|
108 |
fn=chatbot_function,
|
109 |
-
inputs=[user_input, history, mood],
|
110 |
outputs=[chatbot, history]
|
111 |
)
|
112 |
clear_btn.click(
|
@@ -119,6 +268,21 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
119 |
inputs=None,
|
120 |
outputs=emergency_output
|
121 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
|
123 |
# Resource Links
|
124 |
gr.Markdown("""
|
@@ -129,6 +293,6 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
129 |
- [Crisis Text Line](https://www.crisistextline.org/)
|
130 |
""")
|
131 |
|
132 |
-
# Launch (
|
133 |
if __name__ == "__main__":
|
134 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import google.generativeai as genai
|
3 |
import os
|
4 |
+
import json
|
5 |
+
from datetime import datetime
|
6 |
+
import plotly.express as px
|
7 |
+
import pandas as pd
|
8 |
+
from langdetect import detect
|
9 |
+
import random
|
10 |
|
11 |
# Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
|
12 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
13 |
|
14 |
+
# Coping Strategies Library
|
15 |
+
coping_strategies = {
|
16 |
+
"happy": [
|
17 |
+
"Keep the positivity flowing! Try writing down three things you’re grateful for today.",
|
18 |
+
"Share your joy! Call a friend or loved one to spread the good vibes."
|
19 |
+
],
|
20 |
+
"sad": [
|
21 |
+
"It’s okay to feel this way. Try a gentle activity like listening to calming music or taking a short walk.",
|
22 |
+
"Write down your thoughts in a journal to process what’s on your mind."
|
23 |
+
],
|
24 |
+
"anxious": [
|
25 |
+
"Take slow, deep breaths: inhale for 4 seconds, hold for 4, exhale for 4.",
|
26 |
+
"Try a grounding exercise: name 5 things you see, 4 you can touch, 3 you hear, 2 you smell, 1 you taste."
|
27 |
+
],
|
28 |
+
"stressed": [
|
29 |
+
"Pause for a moment and stretch your body to release tension.",
|
30 |
+
"Break tasks into smaller steps and tackle one at a time."
|
31 |
+
],
|
32 |
+
"other": [
|
33 |
+
"Reflect on what’s on your mind with a quick mindfulness moment: focus on your breath for 60 seconds.",
|
34 |
+
"Engage in a favorite hobby to lift your spirits."
|
35 |
+
]
|
36 |
+
}
|
37 |
+
|
38 |
+
# Regional Resources
|
39 |
+
regional_resources = {
|
40 |
+
"USA": [
|
41 |
+
"National Suicide Prevention Lifeline: 1-800-273-8255",
|
42 |
+
"Crisis Text Line: Text HOME to 741741",
|
43 |
+
"[MentalHealth.gov](https://www.mentalhealth.gov/)"
|
44 |
+
],
|
45 |
+
"India": [
|
46 |
+
"Vandrevala Foundation: 1860-2662-345",
|
47 |
+
"AASRA Suicide Prevention: +91-9820466726",
|
48 |
+
"[iCall Helpline](https://icallhelpline.org/)"
|
49 |
+
],
|
50 |
+
"UK": [
|
51 |
+
"Samaritans: 116 123",
|
52 |
+
"Shout Crisis Text Line: Text SHOUT to 85258",
|
53 |
+
"[Mind UK](https://www.mind.org.uk/)"
|
54 |
+
],
|
55 |
+
"Global": [
|
56 |
+
"Befrienders Worldwide: [Find a helpline](https://befrienders.org/)",
|
57 |
+
"[WHO Mental Health Resources](https://www.who.int/health-topics/mental-health)"
|
58 |
+
]
|
59 |
+
}
|
60 |
|
61 |
# Initialize Gemini model
|
62 |
model = genai.GenerativeModel("gemini-1.5-flash",
|
63 |
generation_config={"temperature": 0.7, "max_output_tokens": 200})
|
64 |
|
65 |
+
# Mood journal storage (in-memory for simplicity, persists in session)
|
66 |
+
if "mood_journal" not in gr.State():
|
67 |
+
gr.State()["mood_journal"] = []
|
68 |
+
|
69 |
+
# Feedback storage (in-memory, could be saved to file)
|
70 |
+
if "feedback" not in gr.State():
|
71 |
+
gr.State()["feedback"] = []
|
72 |
+
|
73 |
# Chatbot function
|
74 |
+
def chatbot_function(message, history, mood, conversation_mode, region):
|
|
|
75 |
if history is None:
|
76 |
history = []
|
77 |
|
78 |
+
# Multilingual Support: Detect input language
|
79 |
+
try:
|
80 |
+
lang = detect(message) if message.strip() else "en"
|
81 |
+
except:
|
82 |
+
lang = "en"
|
83 |
+
|
84 |
# Append mood to history if provided
|
85 |
if mood and mood != "Select mood (optional)":
|
86 |
history.append([f"I'm feeling {mood.lower()}.", None])
|
87 |
|
88 |
+
# Append user message
|
89 |
history.append([message, None])
|
90 |
|
91 |
+
# Themed Conversation Modes: Adjust tone
|
92 |
+
tone_instruction = {
|
93 |
+
"Calm": "Respond in a soothing, gentle tone to promote relaxation.",
|
94 |
+
"Motivational": "Use an uplifting, encouraging tone to inspire confidence.",
|
95 |
+
"Neutral": "Maintain a balanced, empathetic tone."
|
96 |
+
}.get(conversation_mode, "Maintain a balanced, empathetic tone.")
|
97 |
+
|
98 |
+
# Prepare prompt
|
99 |
+
prompt = f"""
|
100 |
+
You are a compassionate mental health support chatbot. Engage in a supportive conversation with the user based on their input: {message}.
|
101 |
+
- Provide empathetic, sensitive responses in the user's language (detected as {lang}).
|
102 |
+
- {tone_instruction}
|
103 |
+
- If signs of distress are detected, suggest coping strategies relevant to their mood or input.
|
104 |
+
- Recommend professional resources tailored to the user's region ({region}).
|
105 |
+
- Keep responses concise, warm, and encouraging.
|
106 |
+
"""
|
107 |
|
108 |
# Generate response
|
109 |
try:
|
110 |
response = model.generate_content(prompt)
|
111 |
response_text = response.text
|
112 |
+
except Exception:
|
113 |
response_text = "I'm here for you. Could you share a bit more so I can support you better?"
|
114 |
|
115 |
+
# Add coping strategy if mood is provided
|
116 |
+
if mood and mood != "Select mood (optional)":
|
117 |
+
mood_key = mood.lower()
|
118 |
+
if mood_key in coping_strategies:
|
119 |
+
strategy = random.choice(coping_strategies[mood_key])
|
120 |
+
response_text += f"\n\n**Coping Strategy**: {strategy}"
|
121 |
+
|
122 |
+
# Add regional resources
|
123 |
+
region_key = region if region in regional_resources else "Global"
|
124 |
+
resources = "\n\n**Recommended Resources**:\n" + "\n".join(regional_resources[region_key])
|
125 |
+
response_text += resources
|
126 |
+
|
127 |
+
# Update history
|
128 |
history[-1][1] = response_text
|
129 |
|
130 |
# Format history for display
|
|
|
137 |
|
138 |
return chat_display, history
|
139 |
|
140 |
+
# Mood journal function
|
141 |
+
def log_mood(mood):
|
142 |
+
if mood and mood != "Select mood (optional)":
|
143 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
144 |
+
gr.State()["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
145 |
+
return "Mood logged successfully!"
|
146 |
+
return "Please select a mood to log."
|
147 |
+
|
148 |
+
# Mood trend visualization
|
149 |
+
def show_mood_trends():
|
150 |
+
if not gr.State()["mood_journal"]:
|
151 |
+
return "No moods logged yet."
|
152 |
+
df = pd.DataFrame(gr.State()["mood_journal"])
|
153 |
+
fig = px.line(df, x="timestamp", y="mood", title="Mood Trends Over Time", markers=True)
|
154 |
+
return fig
|
155 |
+
|
156 |
+
# Feedback function
|
157 |
+
def submit_feedback(feedback_text, rating):
|
158 |
+
if feedback_text or rating:
|
159 |
+
gr.State()["feedback"].append({"text": feedback_text, "rating": rating, "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
|
160 |
+
return "Thank you for your feedback!"
|
161 |
+
return "Please provide feedback or a rating."
|
162 |
+
|
163 |
+
# Emergency resources
|
164 |
def show_emergency_resources():
|
165 |
return """
|
166 |
**Crisis Support:**
|
|
|
169 |
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
170 |
"""
|
171 |
|
172 |
+
# Gradio Interface with Dark/Light Mode
|
173 |
+
css = """
|
174 |
+
body { transition: background-color 0.3s, color 0.3s; }
|
175 |
+
.light-mode { background-color: #ffffff; color: #000000; }
|
176 |
+
.dark-mode { background-color: #1a1a1a; color: #ffffff; }
|
177 |
+
button, input, select, textarea { border-radius: 8px; margin: 5px; }
|
178 |
+
"""
|
179 |
+
with gr.Blocks(css=css, title="Mental Health Support Chatbot") as demo:
|
180 |
+
# Theme Toggle
|
181 |
+
theme_state = gr.State(value="light")
|
182 |
+
def toggle_theme(theme):
|
183 |
+
new_theme = "dark" if theme == "light" else "light"
|
184 |
+
return new_theme, f".{new_theme}-mode"
|
185 |
+
theme_btn = gr.Button("Toggle Dark/Light Mode")
|
186 |
+
theme_output = gr.HTML(value=".light-mode")
|
187 |
+
theme_btn.click(toggle_theme, inputs=theme_state, outputs=[theme_state, theme_output])
|
188 |
+
|
189 |
gr.Markdown("# Mental Health Support Chatbot")
|
190 |
gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
|
191 |
|
|
|
195 |
label="How are you feeling today? (Optional)"
|
196 |
)
|
197 |
|
198 |
+
# Conversation Mode
|
199 |
+
conversation_mode = gr.Radio(
|
200 |
+
choices=["Neutral", "Calm", "Motivational"],
|
201 |
+
label="Conversation Style",
|
202 |
+
value="Neutral"
|
203 |
+
)
|
204 |
+
|
205 |
+
# Region Selector
|
206 |
+
region = gr.Dropdown(
|
207 |
+
choices=["USA", "India", "UK", "Global"],
|
208 |
+
label="Select your region for tailored resources",
|
209 |
+
value="Global"
|
210 |
+
)
|
211 |
+
|
212 |
# Chat Interface
|
213 |
chatbot = gr.Textbox(
|
214 |
label="Conversation",
|
|
|
230 |
emergency_btn = gr.Button("Emergency Resources")
|
231 |
emergency_output = gr.Markdown("")
|
232 |
|
233 |
+
# Mood Journal
|
234 |
+
with gr.Accordion("Mood Journal"):
|
235 |
+
log_mood_btn = gr.Button("Log Mood")
|
236 |
+
mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
|
237 |
+
mood_trend_btn = gr.Button("Show Mood Trends")
|
238 |
+
mood_trend_output = gr.Plot()
|
239 |
+
|
240 |
+
# Feedback
|
241 |
+
with gr.Accordion("Provide Feedback"):
|
242 |
+
feedback_text = gr.Textbox(label="Your Feedback (Optional)", placeholder="How can we improve?")
|
243 |
+
feedback_rating = gr.Slider(minimum=1, maximum=5, step=1, label="Rate this interaction")
|
244 |
+
feedback_btn = gr.Button("Submit Feedback")
|
245 |
+
feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
|
246 |
+
|
247 |
+
# State
|
248 |
history = gr.State()
|
249 |
|
250 |
# Event Handlers
|
251 |
submit_btn.click(
|
252 |
fn=chatbot_function,
|
253 |
+
inputs=[user_input, history, mood, conversation_mode, region],
|
254 |
outputs=[chatbot, history]
|
255 |
)
|
256 |
user_input.submit(
|
257 |
fn=chatbot_function,
|
258 |
+
inputs=[user_input, history, mood, conversation_mode, region],
|
259 |
outputs=[chatbot, history]
|
260 |
)
|
261 |
clear_btn.click(
|
|
|
268 |
inputs=None,
|
269 |
outputs=emergency_output
|
270 |
)
|
271 |
+
log_mood_btn.click(
|
272 |
+
fn=log_mood,
|
273 |
+
inputs=mood,
|
274 |
+
outputs=mood_log_output
|
275 |
+
)
|
276 |
+
mood_trend_btn.click(
|
277 |
+
fn=show_mood_trends,
|
278 |
+
inputs=None,
|
279 |
+
outputs=mood_trend_output
|
280 |
+
)
|
281 |
+
feedback_btn.click(
|
282 |
+
fn=submit_feedback,
|
283 |
+
inputs=[feedback_text, feedback_rating],
|
284 |
+
outputs=feedback_output
|
285 |
+
)
|
286 |
|
287 |
# Resource Links
|
288 |
gr.Markdown("""
|
|
|
293 |
- [Crisis Text Line](https://www.crisistextline.org/)
|
294 |
""")
|
295 |
|
296 |
+
# Launch (for local testing)
|
297 |
if __name__ == "__main__":
|
298 |
demo.launch()
|