SANDEEPRAMPRASAD commited on
Commit
8610e5e
ยท
verified ยท
1 Parent(s): d6e3f1f

Upload 4 files

Browse files
Files changed (4) hide show
  1. .env +2 -0
  2. .gitignore +5 -0
  3. app.py +243 -0
  4. requirements.txt +3 -0
.env ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ XAI_API_KEY=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
2
+
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ venv/
2
+ .env
3
+ __pycache__/
4
+ *.pyc
5
+ .ipynb_checkpoints/
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ from dotenv import load_dotenv
4
+ import os
5
+ import random
6
+ from datetime import datetime
7
+
8
+ import warnings
9
+ warnings.filterwarnings("ignore", category=FutureWarning)
10
+
11
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
12
+ # xAI SDK import
13
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
14
+ from xai_sdk import Client
15
+ from xai_sdk.chat import system, user
16
+
17
+ # Load environment variables
18
+ load_dotenv(encoding="utf-8")
19
+ XAI_API_KEY = os.getenv("XAI_API_KEY")
20
+
21
+ # Page configuration
22
+ st.set_page_config(
23
+ page_title="Mental Health Companion",
24
+ page_icon="๐ŸŒฑ",
25
+ layout="centered"
26
+ )
27
+
28
+ # Custom CSS for better UI
29
+ st.markdown("""
30
+ <style>
31
+ .stChatMessage {
32
+ padding: 1rem;
33
+ border-radius: 0.5rem;
34
+ }
35
+ .crisis-warning {
36
+ background-color: #fff3cd;
37
+ border: 2px solid #ffc107;
38
+ padding: 1rem;
39
+ border-radius: 0.5rem;
40
+ margin: 1rem 0;
41
+ }
42
+ </style>
43
+ """, unsafe_allow_html=True)
44
+
45
+ # Initialize session state
46
+ if "messages" not in st.session_state:
47
+ st.session_state.messages = []
48
+
49
+ # Simple default mood (handled by Grok instead of transformers)
50
+ if "mood" not in st.session_state:
51
+ st.session_state.mood = "neutral"
52
+ st.session_state.confidence = 0.5
53
+
54
+ # Initialize xAI client
55
+ if XAI_API_KEY:
56
+ try:
57
+ client = Client(api_key=XAI_API_KEY)
58
+ except Exception as e:
59
+ st.error(f"Error initializing xAI client: {e}")
60
+ st.stop()
61
+ else:
62
+ st.error("โš ๏ธ XAI_API_KEY not found. Please add it to your .env file.")
63
+ st.stop()
64
+
65
+ # Enhanced relaxation tips with categories
66
+ relaxation_tips = {
67
+ "breathing": [
68
+ "Box breathing: Inhale for 4 seconds, hold for 4, exhale for 4, hold for 4. Repeat 3-5 times.",
69
+ "4-7-8 breathing: Breathe in for 4 counts, hold for 7, exhale slowly for 8.",
70
+ ],
71
+ "physical": [
72
+ "Try progressive muscle relaxation: Tense and relax each muscle group from toes to head.",
73
+ "Do some gentle stretches or yoga poses for 5-10 minutes.",
74
+ "Go for a short walk, even if it's just around your room or building.",
75
+ ],
76
+ "mindfulness": [
77
+ "Practice the 5-4-3-2-1 grounding technique: Name 5 things you see, 4 you can touch, 3 you hear, 2 you smell, 1 you taste.",
78
+ "Spend 5 minutes on mindful breathing, focusing only on your breath.",
79
+ "Try a brief guided meditation using a free app or YouTube.",
80
+ ],
81
+ "creative": [
82
+ "Journal your thoughts: Write freely for 5-10 minutes without editing.",
83
+ "Listen to calming music or nature sounds.",
84
+ "Color, draw, or engage in any creative activity you enjoy.",
85
+ ],
86
+ "social": [
87
+ "Reach out to a friend or family member for a quick chat.",
88
+ "Join a study group or student organization to connect with peers.",
89
+ "Consider talking to a counselor at your school's wellness center.",
90
+ ]
91
+ }
92
+
93
+ # Crisis keywords detection
94
+ crisis_keywords = [
95
+ "suicide", "kill myself", "end it all", "want to die",
96
+ "no reason to live", "better off dead", "hurt myself"
97
+ ]
98
+
99
+ def detect_crisis(text):
100
+ """Detect potential crisis situations"""
101
+ text_lower = text.lower()
102
+ return any(keyword in text_lower for keyword in crisis_keywords)
103
+
104
+ def get_random_tips(num=2):
105
+ """Get random relaxation tips from different categories"""
106
+ tips = []
107
+ categories = random.sample(list(relaxation_tips.keys()), min(num, len(relaxation_tips)))
108
+ for category in categories:
109
+ tips.append(random.choice(relaxation_tips[category]))
110
+ return tips
111
+
112
+ # Header
113
+ st.title("๐ŸŒฑ Mental Health Companion")
114
+ st.markdown("*A supportive space for students navigating stress, anxiety, and life's challenges*")
115
+
116
+ # Sidebar with resources
117
+ with st.sidebar:
118
+ st.header("๐Ÿ“š Resources")
119
+ st.markdown("""
120
+ ### Crisis Support (24/7)
121
+ - ๐Ÿ‡ฎ๐Ÿ‡ณ **Vandrevala Foundation**: 1860-2662-345
122
+ - ๐Ÿ‡ฎ๐Ÿ‡ณ **iCall**: 9152987821
123
+ - ๐ŸŒ **International**: Find local helplines
124
+
125
+ ### Student Wellness Tips
126
+ - Maintain a regular sleep schedule
127
+ - Take study breaks every 45-60 minutes
128
+ - Stay connected with friends and family
129
+ - Exercise regularly, even if just 15 minutes
130
+ - Seek help early from campus counseling
131
+
132
+ ### About This Bot
133
+ This chatbot uses AI to provide emotional support
134
+ and coping strategies. It's not a replacement for
135
+ professional mental health care.
136
+ """)
137
+
138
+ if st.button("๐Ÿ”„ Clear Chat History"):
139
+ st.session_state.messages = []
140
+ st.rerun()
141
+
142
+ # Display chat history
143
+ for message in st.session_state.messages:
144
+ with st.chat_message(message["role"]):
145
+ st.markdown(message["content"])
146
+
147
+ # User input
148
+ user_input = st.chat_input("Share what's on your mind...")
149
+
150
+ if user_input:
151
+ # Check for crisis situation
152
+ if detect_crisis(user_input):
153
+ st.markdown("""
154
+ <div class="crisis-warning">
155
+ <h3>๐Ÿ†˜ Immediate Support Available</h3>
156
+ <p>I'm concerned about what you've shared. Please reach out to a crisis counselor immediately:</p>
157
+ <ul>
158
+ <li><strong>India - Vandrevala Foundation</strong>: 1860-2662-345 (24/7)</li>
159
+ <li><strong>India - iCall</strong>: 9152987821 (Mon-Sat, 8am-10pm)</li>
160
+ <li><strong>Your campus counseling center</strong></li>
161
+ </ul>
162
+ <p>You don't have to face this alone. Professional help is available and things can get better.</p>
163
+ </div>
164
+ """, unsafe_allow_html=True)
165
+ st.stop()
166
+
167
+ # Add user message to history & display
168
+ st.session_state.messages.append({"role": "user", "content": user_input})
169
+ with st.chat_message("user"):
170
+ st.markdown(user_input)
171
+
172
+
173
+ # Default mood (sentiment handled implicitly)
174
+ mood = st.session_state.get("mood", "neutral")
175
+ confidence = st.session_state.get("confidence", 0.5)
176
+
177
+
178
+
179
+ # Prepare prompt (now as messages list)
180
+ system_prompt = f"""
181
+ You are a compassionate mental health support chatbot for students.
182
+
183
+ Guidelines:
184
+ 1. Show empathy and validate their feelings
185
+ 2. Be warm, supportive, and non-judgmental
186
+ 3. Use encouraging language appropriate for students
187
+ 4. If the mood seems negative, acknowledge their struggle
188
+ 5. Offer hope and perspective when appropriate
189
+ 6. Keep responses conversational and under 120 words
190
+ 7. Do NOT provide medical diagnosis or treatment
191
+ 8. If issues seem serious, gently suggest professional support
192
+ 9. Use "I" statements to make it personal (e.g., "I hear you")
193
+
194
+ Detected emotional tone: {mood} (confidence: {confidence:.2f})
195
+ """.strip()
196
+
197
+ messages = [
198
+ system(system_prompt),
199
+ user(user_input)
200
+ ]
201
+
202
+ # Generate response
203
+ with st.spinner("๐Ÿ’ญ Thinking..."):
204
+ try:
205
+ chat = client.chat.create(model="grok-4") # or "grok-beta", "grok-3", etc.
206
+ for msg in messages:
207
+ chat.append(msg)
208
+
209
+ response = chat.sample()
210
+ bot_response = response.content.strip()
211
+
212
+ # Add practical tips for negative sentiment
213
+ if mood == 'negative' and confidence > 0.6:
214
+ tips = get_random_tips(2)
215
+ bot_response += "\n\n**Quick coping strategies to try:**\n"
216
+ for i, tip in enumerate(tips, 1):
217
+ bot_response += f"{i}. {tip}\n"
218
+
219
+ # Add timestamp (optional)
220
+ timestamp = datetime.now().strftime("%I:%M %p")
221
+ # bot_response += f"\n\n<small>{timestamp}</small>"
222
+
223
+ except Exception:
224
+ bot_response = (
225
+ "โš ๏ธ I'm temporarily unable to connect to the AI service right now.\n\n"
226
+ "That said, I still want to support you. If you're feeling overwhelmed, "
227
+ "consider reaching out to someone you trust or your campus counseling services.\n\n"
228
+ "Youโ€™re not alone, and help is available ๐Ÿ’™"
229
+ )
230
+
231
+
232
+ # Add bot response to history & display
233
+ st.session_state.messages.append({"role": "assistant", "content": bot_response})
234
+ with st.chat_message("assistant"):
235
+ st.markdown(bot_response)
236
+
237
+ # Footer
238
+ st.markdown("---")
239
+ st.caption(
240
+ "๐Ÿ’™ Remember: This chatbot is a support tool, not a replacement for "
241
+ "professional mental health care. If you're in crisis, please contact "
242
+ "emergency services or a crisis hotline immediately."
243
+ )
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ streamlit>=1.49.0
2
+ xai-sdk==1.5.0
3
+ python-dotenv==1.0.1