Ujeshhh's picture
Create app.py
89ee91c verified
raw
history blame
4.2 kB
import gradio as gr
import google.generativeai as genai
import os
# Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
# Gemini Prompt Template
prompt_template = """
You are a compassionate mental health support chatbot. Engage in a supportive conversation with the user based on their input: {user_input}.
- Provide empathetic, sensitive responses.
- If signs of distress are detected, suggest coping strategies like deep breathing or mindfulness.
- Recommend professional resources or helplines if appropriate, such as the National Suicide Prevention Lifeline (1-800-273-8255) or MentalHealth.gov.
- Keep responses concise, warm, and encouraging.
"""
# Initialize Gemini model
model = genai.GenerativeModel("gemini-1.5-flash",
generation_config={"temperature": 0.7, "max_output_tokens": 200})
# Chatbot function
def chatbot_function(message, history, mood):
# Initialize history if None
if history is None:
history = []
# Append mood to history if provided
if mood and mood != "Select mood (optional)":
history.append([f"I'm feeling {mood.lower()}.", None])
# Append user message to history
history.append([message, None])
# Create prompt with user input
prompt = prompt_template.format(user_input=message)
# Generate response
try:
response = model.generate_content(prompt)
response_text = response.text
except Exception as e:
response_text = "I'm here for you. Could you share a bit more so I can support you better?"
# Update history with bot response
history[-1][1] = response_text
# Format history for display
chat_display = ""
for user_msg, bot_msg in history:
if user_msg:
chat_display += f"**You**: {user_msg}\n\n"
if bot_msg:
chat_display += f"**Bot**: {bot_msg}\n\n"
return chat_display, history
# Emergency resources function
def show_emergency_resources():
return """
**Crisis Support:**
- National Suicide Prevention Lifeline: 1-800-273-8255
- Crisis Text Line: Text HOME to 741741
- [MentalHealth.gov](https://www.mentalhealth.gov/)
"""
# Gradio Interface
with gr.Blocks(title="Mental Health Support Chatbot") as demo:
gr.Markdown("# Mental Health Support Chatbot")
gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
# Mood Indicator
mood = gr.Dropdown(
choices=["Select mood (optional)", "Happy", "Sad", "Anxious", "Stressed", "Other"],
label="How are you feeling today? (Optional)"
)
# Chat Interface
chatbot = gr.Textbox(
label="Conversation",
value="",
interactive=False,
lines=10
)
user_input = gr.Textbox(
placeholder="Type your message here...",
label="Your Message"
)
# Buttons
with gr.Row():
submit_btn = gr.Button("Send")
clear_btn = gr.Button("Clear Chat")
# Emergency Resources
emergency_btn = gr.Button("Emergency Resources")
emergency_output = gr.Markdown("")
# State to store chat history
history = gr.State()
# Event Handlers
submit_btn.click(
fn=chatbot_function,
inputs=[user_input, history, mood],
outputs=[chatbot, history]
)
user_input.submit(
fn=chatbot_function,
inputs=[user_input, history, mood],
outputs=[chatbot, history]
)
clear_btn.click(
fn=lambda: ("", []),
inputs=None,
outputs=[chatbot, history]
)
emergency_btn.click(
fn=show_emergency_resources,
inputs=None,
outputs=emergency_output
)
# Resource Links
gr.Markdown("""
---
**Helpful Resources:**
- [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org/)
- [MentalHealth.gov](https://www.mentalhealth.gov/)
- [Crisis Text Line](https://www.crisistextline.org/)
""")
# Launch (not needed for Hugging Face, included for local testing)
if __name__ == "__main__":
demo.launch()