Ujeshhh commited on
Commit
89ee91c
·
verified ·
1 Parent(s): a55fbf4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -0
app.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Gemini Prompt Template
9
+ prompt_template = """
10
+ You are a compassionate mental health support chatbot. Engage in a supportive conversation with the user based on their input: {user_input}.
11
+ - Provide empathetic, sensitive responses.
12
+ - If signs of distress are detected, suggest coping strategies like deep breathing or mindfulness.
13
+ - Recommend professional resources or helplines if appropriate, such as the National Suicide Prevention Lifeline (1-800-273-8255) or MentalHealth.gov.
14
+ - Keep responses concise, warm, and encouraging.
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 to history
32
+ history.append([message, None])
33
+
34
+ # Create prompt with user input
35
+ prompt = prompt_template.format(user_input=message)
36
+
37
+ # Generate response
38
+ try:
39
+ response = model.generate_content(prompt)
40
+ response_text = response.text
41
+ except Exception as e:
42
+ response_text = "I'm here for you. Could you share a bit more so I can support you better?"
43
+
44
+ # Update history with bot response
45
+ history[-1][1] = response_text
46
+
47
+ # Format history for display
48
+ chat_display = ""
49
+ for user_msg, bot_msg in history:
50
+ if user_msg:
51
+ chat_display += f"**You**: {user_msg}\n\n"
52
+ if bot_msg:
53
+ chat_display += f"**Bot**: {bot_msg}\n\n"
54
+
55
+ return chat_display, history
56
+
57
+ # Emergency resources function
58
+ def show_emergency_resources():
59
+ return """
60
+ **Crisis Support:**
61
+ - National Suicide Prevention Lifeline: 1-800-273-8255
62
+ - Crisis Text Line: Text HOME to 741741
63
+ - [MentalHealth.gov](https://www.mentalhealth.gov/)
64
+ """
65
+
66
+ # Gradio Interface
67
+ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
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
+
71
+ # Mood Indicator
72
+ mood = gr.Dropdown(
73
+ choices=["Select mood (optional)", "Happy", "Sad", "Anxious", "Stressed", "Other"],
74
+ label="How are you feeling today? (Optional)"
75
+ )
76
+
77
+ # Chat Interface
78
+ chatbot = gr.Textbox(
79
+ label="Conversation",
80
+ value="",
81
+ interactive=False,
82
+ lines=10
83
+ )
84
+ user_input = gr.Textbox(
85
+ placeholder="Type your message here...",
86
+ label="Your Message"
87
+ )
88
+
89
+ # Buttons
90
+ with gr.Row():
91
+ submit_btn = gr.Button("Send")
92
+ clear_btn = gr.Button("Clear Chat")
93
+
94
+ # Emergency Resources
95
+ emergency_btn = gr.Button("Emergency Resources")
96
+ emergency_output = gr.Markdown("")
97
+
98
+ # State to store chat history
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(
113
+ fn=lambda: ("", []),
114
+ inputs=None,
115
+ outputs=[chatbot, history]
116
+ )
117
+ emergency_btn.click(
118
+ fn=show_emergency_resources,
119
+ inputs=None,
120
+ outputs=emergency_output
121
+ )
122
+
123
+ # Resource Links
124
+ gr.Markdown("""
125
+ ---
126
+ **Helpful Resources:**
127
+ - [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org/)
128
+ - [MentalHealth.gov](https://www.mentalhealth.gov/)
129
+ - [Crisis Text Line](https://www.crisistextline.org/)
130
+ """)
131
+
132
+ # Launch (not needed for Hugging Face, included for local testing)
133
+ if __name__ == "__main__":
134
+ demo.launch()