File size: 10,270 Bytes
f2f35b4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
#!/usr/bin/env python3
"""
MINIMAL Hugging Face Spaces Entry Point - Guaranteed to Work
Simple mental health chatbot with basic keyword responses
"""
import gradio as gr
import os
import json
from datetime import datetime
import threading
import time
# Set environment variables for Hugging Face Spaces
os.environ['HUGGINGFACE_SPACES'] = '1'
os.environ['GRADIO_SERVER_NAME'] = '0.0.0.0'
os.environ['GRADIO_SERVER_PORT'] = '7860'
# Simple keyword-based responses for mental health support
MENTAL_HEALTH_RESPONSES = {
'crisis': [
"I'm concerned about what you're sharing. Please reach out to emergency services if you're in immediate danger.",
"Your safety is important. Consider contacting: National Suicide Prevention Lifeline: 988",
"Please talk to a mental health professional, trusted friend, or family member right away."
],
'depression': [
"I hear that you're going through a difficult time. Depression is treatable, and you don't have to face this alone.",
"It's important to reach out for professional support. Consider speaking with a counselor or therapist.",
"Small steps can help - try to maintain a routine, get some sunlight, and connect with supportive people."
],
'anxiety': [
"Anxiety can feel overwhelming, but there are effective ways to manage it.",
"Try some deep breathing exercises: breathe in for 4 counts, hold for 4, breathe out for 6.",
"Consider grounding techniques: name 5 things you can see, 4 you can touch, 3 you can hear."
],
'stress': [
"Stress is a normal response, but chronic stress needs attention.",
"Consider what might help: exercise, meditation, talking to someone, or adjusting your workload.",
"Remember to take breaks and practice self-care."
],
'default': [
"Thank you for sharing that with me. How are you feeling right now?",
"I'm here to listen. Can you tell me more about what's on your mind?",
"It's important to talk about these things. What would be most helpful for you right now?"
]
}
def get_simple_response(message):
"""Generate a simple keyword-based response"""
message_lower = message.lower()
# Crisis keywords
crisis_words = ['suicide', 'kill myself', 'end it all', 'hurt myself', 'self harm', 'die', 'death']
if any(word in message_lower for word in crisis_words):
return MENTAL_HEALTH_RESPONSES['crisis'][0]
# Depression keywords
depression_words = ['depressed', 'depression', 'sad', 'hopeless', 'worthless', 'empty']
if any(word in message_lower for word in depression_words):
return MENTAL_HEALTH_RESPONSES['depression'][0]
# Anxiety keywords
anxiety_words = ['anxious', 'anxiety', 'worried', 'panic', 'nervous', 'fear']
if any(word in message_lower for word in anxiety_words):
return MENTAL_HEALTH_RESPONSES['anxiety'][0]
# Stress keywords
stress_words = ['stress', 'stressed', 'overwhelmed', 'pressure', 'burned out']
if any(word in message_lower for word in stress_words):
return MENTAL_HEALTH_RESPONSES['stress'][0]
# Default response
return MENTAL_HEALTH_RESPONSES['default'][0]
def chat_interface(message, history):
"""Simple chat interface for Gradio"""
if not message.strip():
return history
# Add user message
history.append([message, None])
# Generate response
response = get_simple_response(message)
# Add bot response
history[-1][1] = response
return history
def create_assessment_form():
"""Create a simple mental health assessment"""
questions = [
"How often have you felt down, depressed, or hopeless in the past 2 weeks?",
"How often have you felt little interest or pleasure in doing things?",
"How often have you felt nervous, anxious, or on edge?",
"How often have you been unable to stop or control worrying?",
"How would you rate your overall mental health today?"
]
options = ["Not at all", "Several days", "More than half the days", "Nearly every day"]
return questions, options
def process_assessment(*responses):
"""Process simple assessment responses"""
if not any(responses):
return "Please answer at least one question to get results."
# Simple scoring
scores = [["Not at all", "Several days", "More than half the days", "Nearly every day"].index(r)
if r in ["Not at all", "Several days", "More than half the days", "Nearly every day"]
else 0 for r in responses if r]
total_score = sum(scores)
max_possible = len(scores) * 3
if total_score <= max_possible * 0.3:
result = "Your responses suggest minimal mental health concerns."
elif total_score <= max_possible * 0.6:
result = "Your responses suggest mild to moderate mental health concerns."
else:
result = "Your responses suggest significant mental health concerns."
result += "\n\nRemember: This is not a professional diagnosis. Please consider speaking with a mental health professional for proper evaluation and support."
return result
# Create the Gradio interface
with gr.Blocks(title="Mental Health AI Assistant", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π§ Mental Health AI Assistant
**A supportive space for mental health conversations and basic assessments.**
*Disclaimer: This is not a substitute for professional mental health care.
If you're in crisis, please contact emergency services or a mental health hotline.*
""")
with gr.Tab("π¬ Chat"):
gr.Markdown("### Have a conversation about your mental health")
chatbot = gr.Chatbot(
height=400,
placeholder="Start a conversation about how you're feeling..."
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message here...",
container=False,
scale=4
)
send_btn = gr.Button("Send", scale=1, variant="primary")
# Chat functionality
msg.submit(chat_interface, [msg, chatbot], [chatbot])
send_btn.click(chat_interface, [msg, chatbot], [chatbot])
msg.submit(lambda: "", None, [msg])
send_btn.click(lambda: "", None, [msg])
with gr.Tab("π Quick Assessment"):
gr.Markdown("### Brief Mental Health Check")
gr.Markdown("*Answer a few questions to get insights about your mental wellbeing.*")
questions, options = create_assessment_form()
responses = []
for i, question in enumerate(questions[:4]): # First 4 questions
response = gr.Radio(
choices=options,
label=f"Q{i+1}: {question}",
value=None
)
responses.append(response)
# Overall health question
overall_health = gr.Radio(
choices=["Excellent", "Very Good", "Good", "Fair", "Poor"],
label="Q5: How would you rate your overall mental health today?",
value=None
)
responses.append(overall_health)
assess_btn = gr.Button("Get Assessment Results", variant="primary")
results = gr.Textbox(
label="Assessment Results",
lines=8,
interactive=False
)
assess_btn.click(
process_assessment,
inputs=responses,
outputs=results
)
with gr.Tab("π Resources"):
gr.Markdown("""
### π Crisis Resources
**If you're in immediate danger:**
- **Emergency Services**: Call 911 (US) or your local emergency number
- **National Suicide Prevention Lifeline**: 988 (US)
- **Crisis Text Line**: Text HOME to 741741
### π₯ Professional Help
- **Psychology Today**: Find therapists near you
- **National Alliance on Mental Illness (NAMI)**: 1-800-950-NAMI
- **Substance Abuse Helpline**: 1-800-662-4357
### π§ Self-Help Tools
- **Mindfulness Apps**: Headspace, Calm, Insight Timer
- **Breathing Exercises**: 4-7-8 technique, box breathing
- **Grounding Techniques**: 5-4-3-2-1 sensory method
### π Educational Resources
- **Mental Health America**: mhanational.org
- **National Institute of Mental Health**: nimh.nih.gov
- **WHO Mental Health**: who.int/mental_health
""")
with gr.Tab("βΉοΈ About"):
gr.Markdown("""
### About This Application
This is a **minimal version** of the Mental Health AI Assistant, designed to provide:
- Basic conversational support using keyword matching
- Simple mental health assessments
- Crisis resource information
- Educational materials
### π Privacy & Safety
- Your conversations are not stored permanently
- No personal data is collected
- All interactions are processed locally
### β οΈ Important Disclaimer
**This application is NOT a replacement for professional mental health care.**
- It does not provide medical diagnosis or treatment
- It cannot handle mental health emergencies
- Always consult qualified healthcare providers for serious concerns
### π Technology
- Built with Gradio for the interface
- Deployed on Hugging Face Spaces
- Uses simple keyword-based responses
---
*If you need immediate help, please contact emergency services or a mental health crisis line.*
""")
# Launch the application
if __name__ == "__main__":
print("π Starting Minimal Mental Health AI Assistant...")
print("π Running on Hugging Face Spaces")
print("π Ready to provide basic mental health support")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_api=False
)
|