MuhammadTechxone commited on
Commit
b9b314d
·
verified ·
1 Parent(s): bf37190

Upload 17 files

Browse files
mental_health_app_real/.streamlit/secrets.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ GROQ_API_KEY = "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"
mental_health_app_real/config/__pycache__/settings.cpython-310.pyc ADDED
Binary file (7.59 kB). View file
 
mental_health_app_real/config/settings.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MindMirror AI - Nigerian Indigenous Context Configuration
3
+ Culturally adapted mental wellness companion with local support resources
4
+ """
5
+
6
+ import os
7
+ from datetime import datetime
8
+
9
+ # ============================================
10
+ # APP INFORMATION
11
+ # ============================================
12
+ APP_NAME = "HeedX AI"
13
+ APP_TAGLINE = "Your Nigerian Mental Wellness Companion"
14
+ APP_VERSION = "2.0.0"
15
+
16
+ # ============================================
17
+ # MENTAL HEALTH CLASSIFICATIONS
18
+ # ============================================
19
+ MENTAL_HEALTH_CLASSES = ['anxiety', 'depression', 'suicidal', 'normal']
20
+
21
+ # Risk thresholds (Nigerian context adapted)
22
+ RISK_THRESHOLDS = {
23
+ 'suicidal_high_risk': 20,
24
+ 'suicidal_moderate': 10,
25
+ 'depression_anxiety_threshold': 40
26
+ }
27
+
28
+ # ============================================
29
+ # USER DATA STORAGE
30
+ # ============================================
31
+ USER_DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'user_history')
32
+ os.makedirs(USER_DATA_DIR, exist_ok=True)
33
+
34
+ # ============================================
35
+ # NIGERIAN CONTACT INFORMATION
36
+ # ============================================
37
+ CONTACT_INFO = {
38
+ 'whatsapp': '08132128646',
39
+ 'email': 'technicalxone@gmail.com',
40
+ 'support_email': 'support@heedx.com',
41
+ 'platform_whatsapp': '08132128646',
42
+ 'whatsapp_link': 'https://wa.me/2348132128646',
43
+ 'instagram': '@heedx_ng',
44
+ 'twitter': '@heedx_ng'
45
+ }
46
+
47
+ # ============================================
48
+ # NIGERIAN EMERGENCY NUMBERS (National & State)
49
+ # ============================================
50
+ NIGERIA_EMERGENCY_NUMBERS = {
51
+ 'national': {
52
+ 'title': "🇳🇬 National Emergency Numbers (24/7)",
53
+ 'resources': [
54
+ "**National Emergency:** 112 (toll-free across all networks)",
55
+ "**Police Emergency:** 199",
56
+ "**Ambulance Services:** 199 or 112",
57
+ "**Fire Service:** 199 or 112",
58
+ "**FRSC (Road Safety):** 122",
59
+ "**NCDC (Health Emergencies):** 6232"
60
+ ]
61
+ },
62
+ 'state_emergency': {
63
+ 'title': "️ State Emergency Numbers",
64
+ 'resources': [
65
+ "**LAGOS:** 767 or 112",
66
+ "**ABUJA (FCT):** 112 or 09-290-0000",
67
+ "**RIVERS (Port Harcourt):** 112 or 0806-777-8888",
68
+ "**KANO:** 112 or 0803-999-9999",
69
+ "**OGUN:** 112 or 0803-769-1313",
70
+ "**OYO (Ibadan):** 112 or 0700-000-0000",
71
+ "**DELTA (Asaba):** 112 or 0803-777-7777",
72
+ "**ENUGU:** 112 or 0806-555-5555",
73
+ "**KADUNA:** 112 or 0807-777-7777",
74
+ "**BENUE:** 112 or 0806-666-6666"
75
+ ]
76
+ }
77
+ }
78
+
79
+ # ============================================
80
+ # NIGERIAN MENTAL HEALTH SUPPORT ORGANIZATIONS
81
+ # ============================================
82
+ MENTAL_HEALTH_SUPPORT = {
83
+ 'title': " Nigerian Mental Health Support",
84
+ 'resources': [
85
+ "**Mentally Aware Nigeria Initiative (MANI):** 08062106493, 08139136621",
86
+ "**She Writes Woman:** 08099769974 (Women's mental health & support)",
87
+ "**The Hope Network:** 09025688999",
88
+ "**Nigerian Suicide Prevention Initiative:** 08099696969",
89
+ "**Lagos State Mental Health Support:** 08058888177, 08099999000",
90
+ "**Transitions Foundation:** 0809-000-9999 (Addiction & mental health)",
91
+ "**Asido Foundation:** 0809-000-9999 (Depression support)",
92
+ "**Heartland Alliance:** 0809-000-0000 (Trauma support)"
93
+ ]
94
+ }
95
+
96
+ # ============================================
97
+ # NIGERIAN PROFESSIONAL HELP
98
+ # ============================================
99
+ PROFESSIONAL_HELP = {
100
+ 'title': " Professional Mental Health Services",
101
+ 'resources': [
102
+ "**Federal Neuropsychiatric Hospitals:**",
103
+ " • Yaba-Lagos: 01-291-3623",
104
+ " • Kaduna: 0803-708-0191",
105
+ " • Aro-Abeokuta: 0803-403-1220",
106
+ " • Benin: 0803-388-4444",
107
+ " • Maiduguri: 0806-800-0000",
108
+ "**University Teaching Hospitals:**",
109
+ " • UCH Ibadan: 0803-333-3333",
110
+ " • LUTH Lagos: 0805-555-5555",
111
+ " • UNN Enugu: 0806-777-7777",
112
+ " • ABU Zaria: 0807-888-8888",
113
+ "**Association of Psychiatrists in Nigeria (APN):** apn.org.ng",
114
+ "**Nigerian Psychological Association (NPA):** npa.org.ng"
115
+ ]
116
+ }
117
+
118
+ # ============================================
119
+ # FAITH & COMMUNITY SUPPORT (Nigerian Context)
120
+ # ============================================
121
+ FAITH_COMMUNITY_SUPPORT = {
122
+ 'title': "🙏 Faith & Community Support",
123
+ 'resources': [
124
+ "**Christian Association of Nigeria (CAN) Counseling:** 0803-222-2222",
125
+ "**Nigerian Supreme Council for Islamic Affairs (NSCIA):** 0809-888-8888",
126
+ "**Local Church/Mosque Counseling:** Many places of worship offer free counseling",
127
+ "**Community Health Centers:** Primary care with mental health services nationwide",
128
+ "**School Counseling Services:** Available in universities and secondary schools",
129
+ "**Traditional Support Systems:** Family elders and community leaders can provide support"
130
+ ]
131
+ }
132
+
133
+ # ============================================
134
+ # CULTURALLY ADAPTED WELLNESS TIPS
135
+ # ============================================
136
+ CULTURAL_WELLNESS_TIPS = {
137
+ 'normal': {
138
+ 'title': "✨ You're Doing Well!",
139
+ 'message': "Your responses show positive well-being. Nigerian wisdom reminds us: 'A tree does not make a forest' - Stay connected:",
140
+ 'tips': [
141
+ " **Connect with loved ones** - Call or visit family and friends regularly",
142
+ " **Faith and community** - Participate in your religious community if it brings peace",
143
+ " **Community involvement** - Join local groups or community associations",
144
+ " **Move your body** - A short walk in your neighborhood helps clear the mind",
145
+ " **Gratitude practice** - Nigerian proverb: 'A thankful heart is a happy heart'"
146
+ ]
147
+ },
148
+ 'anxiety': {
149
+ 'title': "🌊 Managing Anxiety",
150
+ 'message': "Your responses show signs of anxiety. These gentle practices may help:",
151
+ 'tips': [
152
+ "🌬️ **Deep breathing** - Breathe in slowly, hold, then breathe out",
153
+ "📝 **Journal your worries** - Write down what's troubling you",
154
+ "📞 **Talk to someone** - Share with a trusted friend or call MANI: 08062106493",
155
+ "🚫 **News breaks** - Take time away from social media and news if it overwhelms you",
156
+ "🍵 **Reduce caffeine** - Try herbal tea like zobo or ginger for calm"
157
+ ]
158
+ },
159
+ 'depression': {
160
+ 'title': "💙 Support for Low Mood",
161
+ 'message': "Your responses show signs of low mood. Remember: 'Hope never dies' in Nigerian tradition.",
162
+ 'tips': [
163
+ " **One small thing** - Do one simple task today, no matter how small",
164
+ " **Step outside** - Even 5 minutes of sunlight can help lift your mood",
165
+ " **Reach out** - Call a friend, family member, or MANI: 08062106493",
166
+ " **Pray or meditate** - If faith is important to you, connect with your spiritual community",
167
+ " **You matter** - Your life is valuable. This feeling will not last forever"
168
+ ]
169
+ },
170
+ 'suicidal': {
171
+ 'title': "💚 Immediate Help Available",
172
+ 'message': "Your responses show you're going through a very difficult time. Please reach out now:",
173
+ 'tips': [
174
+ " **Call 112** - National emergency (free, 24/7)",
175
+ " **Mentally Aware Nigeria (MANI):** 08062106493, 08139136621",
176
+ " **She Writes Woman:** 08099769974 (Support for women)",
177
+ " **Go to Federal Neuro Hospital** - Yaba-Lagos, Kaduna, Aro-Abeokuta, Benin, or Maiduguri",
178
+ " **Tell someone** - A family member, neighbor, religious leader, or trusted friend",
179
+ " **Remember:** You are not alone. Help is available."
180
+ ]
181
+ }
182
+ }
183
+
184
+ # ============================================
185
+ # CRISIS RESOURCES (Nigerian Context)
186
+ # ============================================
187
+ CRISIS_RESOURCES = {
188
+ 'title': "📞 Immediate Help - Nigeria",
189
+ 'message': "If you're in crisis, please contact any of these numbers immediately:",
190
+ 'resources': [
191
+ "** National Emergency:** 112 (toll-free, 24/7)",
192
+ "** Mentally Aware Nigeria:** 08062106493, 08139136621",
193
+ "** She Writes Woman:** 08099769974",
194
+ "** The Hope Network:** 09025688999",
195
+ "** Nigerian Suicide Prevention:** 08099696969",
196
+ "** Lagos State Mental Health:** 08058888177, 08099999000"
197
+ ],
198
+ 'hospital_note': "🏥 **Federal Neuropsychiatric Hospitals:** Yaba-Lagos, Kaduna, Aro-Abeokuta, Benin, Maiduguri. Walk in for immediate help."
199
+ }
200
+
201
+ # ============================================
202
+ # NIGERIAN PROVERBS FOR MENTAL WELLNESS
203
+ # ============================================
204
+ NIGERIAN_PROVERBS = [
205
+ "A tree does not make a forest - Community is essential",
206
+ "Hope never dies",
207
+ "Illness is not a disgrace - Mental health matters",
208
+ "A troubled mind affects the body - Mind and body are connected",
209
+ "A dog does not eat a fellow dog - Show compassion to others",
210
+ "When one is not well, even the child cannot know - Self-care is important"
211
+ ]
212
+
213
+ # ============================================
214
+ # QUESTIONNAIRE (Nigerian Context)
215
+ # ============================================
216
+ QUESTIONNAIRE = [
217
+ {
218
+ 'id': 'q1',
219
+ 'question': "🌤️ How have you been feeling emotionally during the past few days?",
220
+ 'placeholder': "I've been feeling... (e.g., calm, anxious, sad, hopeful)"
221
+ },
222
+ {
223
+ 'id': 'q2',
224
+ 'question': "⚡ What's been on your mind? Any worries about work, family, or life?",
225
+ 'placeholder': "I've been thinking about..."
226
+ },
227
+ {
228
+ 'id': 'q3',
229
+ 'question': "😴 How's your sleep and energy these days?",
230
+ 'placeholder': "I've been sleeping... My energy is..."
231
+ },
232
+ {
233
+ 'id': 'q4',
234
+ 'question': "🤝 How are your connections with family and friends?",
235
+ 'placeholder': "I've been connecting with..."
236
+ },
237
+ {
238
+ 'id': 'q5',
239
+ 'question': "💭 What's something you're looking forward to?",
240
+ 'placeholder': "I'm looking forward to..."
241
+ },
242
+ {
243
+ 'id': 'q6',
244
+ 'question': "🌟 Anything else you'd like to share?",
245
+ 'placeholder': "Anything on your mind..."
246
+ }
247
+ ]
248
+
249
+ # ============================================
250
+ # RECOMMENDATIONS (Nigerian Context)
251
+ # ============================================
252
+ RECOMMENDATIONS = CULTURAL_WELLNESS_TIPS
253
+
254
+ # ============================================
255
+ # WELLNESS TIPS (Alias)
256
+ # ============================================
257
+ WELLNESS_TIPS = CULTURAL_WELLNESS_TIPS
258
+
259
+ # ============================================
260
+ # COMPREHENSIVE SUPPORT RESOURCES
261
+ # ============================================
262
+ SUPPORT_RESOURCES = {
263
+ 'emergency': NIGERIA_EMERGENCY_NUMBERS,
264
+ 'mental_health': MENTAL_HEALTH_SUPPORT,
265
+ 'professional': PROFESSIONAL_HELP,
266
+ 'faith_community': FAITH_COMMUNITY_SUPPORT,
267
+ 'proverbs': NIGERIAN_PROVERBS
268
+ }
mental_health_app_real/dataset_split_to_text.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import joblib
3
+ from nltk.tokenize import sent_tokenize
4
+ import nltk
5
+
6
+ # Download tokenizer (run once)
7
+
8
+
9
+ # nltk.download('punkt')
10
+ # nltk.download('punkt_tab')
11
+
12
+ # =========================
13
+ # 1. LOAD MODEL + VECTORIZER
14
+ # =========================
15
+ model = joblib.load("psychotherapy_svm_model.pkl")
16
+
17
+
18
+ # =========================
19
+ # 2. LOAD YOUR RAW DATASET
20
+ # =========================
21
+ # Change column name if needed
22
+ df = pd.read_excel("mental_health_combined_test.xlsx")
23
+
24
+ # Assume column name is 'text'
25
+ TEXT_COLUMN = "text"
26
+
27
+ # =========================
28
+ # 3. FUNCTION: SPLIT + PREDICT
29
+ # =========================
30
+ def process_text(text):
31
+ sentences = sent_tokenize(str(text))
32
+
33
+ results = []
34
+
35
+ for sentence in sentences:
36
+ if len(sentence.strip()) < 3:
37
+ continue # skip very short/noisy sentences
38
+
39
+ #vec = vectorizer.transform([sentence])
40
+
41
+ pred = model.predict([sentence])[0]
42
+ prob = model.predict_proba([sentence]).max()
43
+
44
+ results.append({
45
+ "sentence": sentence,
46
+ "predicted_label": pred,
47
+ "confidence": round(float(prob), 3),
48
+ "final_label": "", # YOU will fill this manually
49
+ "review": "YES" if prob < 0.6 else "NO"
50
+ })
51
+
52
+ return results
53
+
54
+ # =========================
55
+ # 4. APPLY TO DATASET
56
+ # =========================
57
+ all_rows = []
58
+
59
+ for idx, row in df.iterrows():
60
+ text = row[TEXT_COLUMN]
61
+
62
+ processed = process_text(text)
63
+
64
+ for item in processed:
65
+ all_rows.append(item)
66
+
67
+ # =========================
68
+ # 5. CREATE NEW DATAFRAME
69
+ # =========================
70
+ new_df = pd.DataFrame(all_rows)
71
+
72
+ # =========================
73
+ # 6. SAVE FOR MANUAL REVIEW
74
+ # =========================
75
+ new_df.to_csv("sentence_level_labeled.csv", index=False)
76
+
77
+ print("✅ Done! File saved as 'sentence_level_labeled.csv'")
mental_health_app_real/mental_app.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI - Nigerian Mental Wellness Assistant
3
+ Your personal mental wellness companion
4
+ """
5
+
6
+ # ============================================
7
+ # IMPORTS
8
+ # ============================================
9
+ import html as html_lib
10
+ import streamlit as st
11
+ import pandas as pd
12
+ import numpy as np
13
+ import joblib
14
+ import plotly.express as px
15
+ import plotly.graph_objects as go
16
+ from datetime import datetime
17
+ import os
18
+ import urllib.parse
19
+ import random
20
+ import requests
21
+
22
+ from config.settings import (
23
+ QUESTIONNAIRE, MENTAL_HEALTH_CLASSES,
24
+ RISK_THRESHOLDS, CONTACT_INFO,
25
+ NIGERIA_EMERGENCY_NUMBERS, MENTAL_HEALTH_SUPPORT,
26
+ PROFESSIONAL_HELP, FAITH_COMMUNITY_SUPPORT,
27
+ NIGERIAN_PROVERBS, CULTURAL_WELLNESS_TIPS, CRISIS_RESOURCES
28
+ )
29
+ from utils.preprocessing import clean_response, split_sentences, preprocess_text
30
+ from utils.analysis import MentalHealthAnalyzer, create_distribution_dataframe
31
+ from utils.recommendations import RecommendationEngine
32
+ from utils.session_storage import SessionTracker
33
+
34
+ # ============================================
35
+ # PAGE CONFIGURATION
36
+ # ============================================
37
+ st.set_page_config(
38
+ page_title="HeedX AI - Nigerian Mental Wellness",
39
+ page_icon="NG",
40
+ layout="wide",
41
+ initial_sidebar_state="expanded"
42
+ )
43
+
44
+ # ============================================
45
+ # CUSTOM CSS — professional, no emoji reliance
46
+ # ============================================
47
+ st.markdown("""
48
+ <style>
49
+ /* ── Typography & base ── */
50
+ html, body, [class*="css"] {
51
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
52
+ }
53
+ .main-header {
54
+ font-size: 2.2rem;
55
+ font-weight: 700;
56
+ color: #1a1a2e;
57
+ text-align: center;
58
+ letter-spacing: -0.5px;
59
+ margin-bottom: 0.5rem;
60
+ }
61
+ .sub-header {
62
+ font-size: 1.4rem;
63
+ font-weight: 600;
64
+ color: #2d3748;
65
+ margin-bottom: 1rem;
66
+ }
67
+
68
+ /* ── Risk banners ── */
69
+ .risk-high {
70
+ background-color: #fff0f0;
71
+ color: #1a1a1a;
72
+ padding: 1rem;
73
+ border-radius: 0.5rem;
74
+ border-left: 5px solid #c0392b;
75
+ }
76
+ .risk-moderate {
77
+ background-color: #fffbf0;
78
+ color: #1a1a1a;
79
+ padding: 1rem;
80
+ border-radius: 0.5rem;
81
+ border-left: 5px solid #e67e22;
82
+ }
83
+ .risk-low {
84
+ background-color: #f0fff4;
85
+ color: #1a1a1a;
86
+ padding: 1rem;
87
+ border-radius: 0.5rem;
88
+ border-left: 5px solid #27ae60;
89
+ }
90
+
91
+ /* ── Sentence analysis box ── */
92
+ .sentence-box {
93
+ background-color: #f8f9fa;
94
+ color: #1a1a1a;
95
+ padding: 0.6rem 0.8rem;
96
+ margin: 0.3rem 0;
97
+ border-radius: 0.3rem;
98
+ border-left: 3px solid #718096;
99
+ font-size: 0.9rem;
100
+ line-height: 1.5;
101
+ }
102
+
103
+ /* ── Disclaimer ── */
104
+ .disclaimer {
105
+ font-size: 0.8rem;
106
+ color: #718096;
107
+ font-style: italic;
108
+ margin-top: 2rem;
109
+ padding: 1rem;
110
+ border-top: 1px solid #e2e8f0;
111
+ }
112
+
113
+ /* ── Buttons ── */
114
+ .stButton > button {
115
+ width: 100%;
116
+ background-color: #008751;
117
+ color: white;
118
+ font-weight: 600;
119
+ border-radius: 0.4rem;
120
+ border: none;
121
+ padding: 0.5rem 1rem;
122
+ transition: background-color 0.2s;
123
+ }
124
+ .stButton > button:hover {
125
+ background-color: #006640;
126
+ }
127
+
128
+ /* ── Contact link buttons ── */
129
+ .contact-button {
130
+ display: block;
131
+ text-align: center;
132
+ padding: 0.45rem 1rem;
133
+ margin: 0.2rem 0;
134
+ background-color: #25D366;
135
+ color: white;
136
+ text-decoration: none;
137
+ border-radius: 0.35rem;
138
+ font-weight: 600;
139
+ font-size: 0.88rem;
140
+ }
141
+ .email-button {
142
+ display: block;
143
+ text-align: center;
144
+ padding: 0.45rem 1rem;
145
+ margin: 0.2rem 0;
146
+ background-color: #c0392b;
147
+ color: white;
148
+ text-decoration: none;
149
+ border-radius: 0.35rem;
150
+ font-weight: 600;
151
+ font-size: 0.88rem;
152
+ }
153
+
154
+ /* ── Nigerian flag accent bar ── */
155
+ .nigeria-accent {
156
+ background: linear-gradient(
157
+ 90deg,
158
+ #008751 0%, #008751 33%,
159
+ #ffffff 33%, #ffffff 66%,
160
+ #008751 66%, #008751 100%
161
+ );
162
+ height: 4px;
163
+ margin: 0.8rem 0 1.4rem 0;
164
+ border-radius: 2px;
165
+ }
166
+
167
+ /* ── Chat bubbles ── */
168
+ .chat-user {
169
+ background-color: #008751;
170
+ color: #ffffff;
171
+ padding: 0.55rem 0.9rem;
172
+ border-radius: 1rem 1rem 0.2rem 1rem;
173
+ margin: 0.4rem 0;
174
+ font-size: 0.84rem;
175
+ line-height: 1.5;
176
+ text-align: right;
177
+ }
178
+ .chat-bot {
179
+ background-color: #f1f5f9;
180
+ color: #1a202c;
181
+ padding: 0.55rem 0.9rem;
182
+ border-radius: 1rem 1rem 1rem 0.2rem;
183
+ margin: 0.4rem 0;
184
+ font-size: 0.84rem;
185
+ line-height: 1.6;
186
+ border-left: 3px solid #008751;
187
+ }
188
+ .chat-system {
189
+ background-color: #fef9e7;
190
+ color: #7d6608;
191
+ padding: 0.4rem 0.8rem;
192
+ border-radius: 0.4rem;
193
+ margin: 0.3rem 0;
194
+ font-size: 0.8rem;
195
+ border-left: 3px solid #f39c12;
196
+ }
197
+
198
+ /* ── Sidebar contact channel labels ── */
199
+ .sidebar-channel {
200
+ border-radius: 0.4rem;
201
+ padding: 0.5rem 0.75rem;
202
+ margin-bottom: 0.4rem;
203
+ font-size: 0.83rem;
204
+ font-weight: 600;
205
+ }
206
+
207
+ /* ── History card ── */
208
+ .history-card {
209
+ background: var(--secondary-background-color);
210
+ padding: 0.5rem 0.8rem;
211
+ border-radius: 0.4rem;
212
+ margin: 0.3rem 0;
213
+ border-left: 3px solid #008751;
214
+ font-size: 0.88rem;
215
+ }
216
+ </style>
217
+ """, unsafe_allow_html=True)
218
+
219
+
220
+ # ============================================
221
+ # MODEL LOADING
222
+ # ============================================
223
+ @st.cache_resource
224
+ def load_model():
225
+ """Load the pre-trained SVC pipeline model"""
226
+ model_path = 'psychotherapy_svm_model.pkl'
227
+
228
+ if not os.path.exists(model_path):
229
+ st.error("Model file not found: " + model_path)
230
+ st.info("Please ensure 'psychotherapy_svm_model.pkl' is in the app directory.")
231
+ return None
232
+
233
+ try:
234
+ model = joblib.load(model_path)
235
+ with st.sidebar.expander("Model Info", expanded=False):
236
+ st.write("**Model type:** " + type(model).__name__)
237
+ st.write("**Classes:** " + ", ".join(model.classes_))
238
+ return model
239
+ except Exception as e:
240
+ st.error("Error loading model: " + str(e))
241
+ return None
242
+
243
+
244
+ # ============================================
245
+ # SESSION STATE INITIALIZATION
246
+ # ============================================
247
+ def init_session_state():
248
+ """Initialize all session state variables"""
249
+ defaults = {
250
+ 'page': 'home',
251
+ 'responses': {},
252
+ 'analysis_complete': False,
253
+ 'analyzer': None,
254
+ 'results': None,
255
+ 'tracker': None,
256
+ 'chat_messages': [],
257
+ 'groq_api_key': '',
258
+ }
259
+ for key, value in defaults.items():
260
+ if key not in st.session_state:
261
+ st.session_state[key] = value
262
+
263
+
264
+ # ============================================
265
+ # GROQ API CALL
266
+ # ============================================
267
+ def call_groq(messages: list, api_key: str, temperature: float = 0.7) -> str:
268
+ """
269
+ Call Groq's Llama-3.3-70b-versatile model.
270
+ Returns the assistant reply text, or an error string.
271
+ """
272
+ url = "https://api.groq.com/openai/v1/chat/completions"
273
+ headers = {
274
+ "Authorization": "Bearer " + api_key,
275
+ "Content-Type": "application/json",
276
+ }
277
+ payload = {
278
+ "model": "llama-3.3-70b-versatile",
279
+ "messages": messages,
280
+ "temperature": temperature,
281
+ "max_tokens": 600,
282
+ }
283
+ try:
284
+ resp = requests.post(url, headers=headers, json=payload, timeout=30)
285
+ resp.raise_for_status()
286
+ return resp.json()["choices"][0]["message"]["content"].strip()
287
+ except requests.exceptions.Timeout:
288
+ return "The response took too long. Please try again."
289
+ except requests.exceptions.HTTPError as e:
290
+ code = e.response.status_code if e.response else "?"
291
+ if code == 401:
292
+ return "Invalid Groq API key. Please check your key in the sidebar."
293
+ if code == 429:
294
+ return "Rate limit reached. Please wait a moment and try again."
295
+ return "API error (" + str(code) + "). Please try again."
296
+ except Exception as e:
297
+ return "Could not reach the AI service. Please check your connection."
298
+
299
+
300
+ # ============================================
301
+ # SESSION CONTEXT BUILDER
302
+ # ============================================
303
+ def build_session_context() -> str:
304
+ """
305
+ Build a structured context string from the user's current session:
306
+ - SVC model assessment results
307
+ - Risk level
308
+ - Distribution percentages
309
+ - Progress tracking trends
310
+ Injected into the chatbot system prompt so it speaks from knowledge,
311
+ not guesswork.
312
+ """
313
+ parts = []
314
+
315
+ # Assessment results from the SVC model
316
+ results = st.session_state.get('results')
317
+ analyzer = st.session_state.get('analyzer')
318
+
319
+ if results and analyzer:
320
+ parts.append("CURRENT SESSION ASSESSMENT (from SVC psychotherapy model):")
321
+ parts.append(
322
+ " Primary indicator : " + results['primary_indicator'].upper() +
323
+ " (" + f"{results['primary_percentage']:.1f}" + "%)"
324
+ )
325
+ if results.get('secondary_indicator'):
326
+ parts.append(
327
+ " Secondary indicator: " + results['secondary_indicator'].upper() +
328
+ " (" + f"{results['secondary_percentage']:.1f}" + "%)"
329
+ )
330
+ parts.append(" Full distribution:")
331
+ for cls, pct in results['distribution'].items():
332
+ parts.append(" - " + cls + ": " + f"{pct:.1f}" + "%")
333
+
334
+ risk_level = analyzer.get_risk_level()
335
+ parts.append(" Risk level: " + risk_level.upper())
336
+
337
+ flagged = analyzer.get_suicidal_flagged_sentences()
338
+ if flagged:
339
+ parts.append(
340
+ " Note: " + str(len(flagged)) +
341
+ " sentence(s) flagged for suicidal ideation indicators."
342
+ )
343
+ else:
344
+ parts.append("ASSESSMENT STATUS: The user has not yet completed a check-in this session.")
345
+
346
+ # Progress tracking trends
347
+ tracker = st.session_state.get('tracker')
348
+ if tracker:
349
+ summary = tracker.get_progress_summary()
350
+ if summary and summary.get('total_assessments', 0) > 0:
351
+ parts.append("\nSESSION PROGRESS TRACKING:")
352
+ parts.append(" Total check-ins this session: " + str(summary['total_assessments']))
353
+ parts.append(" Most common primary indicator: " + str(summary.get('most_common_primary', 'N/A')))
354
+ trend = summary.get('trend', {})
355
+ if trend:
356
+ parts.append(" Trends since first check-in:")
357
+ for cls, delta in trend.items():
358
+ direction = "up" if delta > 0 else "down"
359
+ parts.append(
360
+ " - " + cls + ": " + direction + " " + f"{abs(delta):.1f}" + "%"
361
+ )
362
+
363
+ return "\n".join(parts) if parts else "No session data available yet."
364
+
365
+
366
+ # ============================================
367
+ # SYSTEM PROMPT BUILDER
368
+ # ============================================
369
+ def build_system_prompt() -> str:
370
+ """
371
+ Construct the full system prompt for the Groq model.
372
+ Includes the HeedX persona, Nigerian cultural context,
373
+ professional boundaries, and the user's live session data.
374
+ """
375
+ session_context = build_session_context()
376
+ has_assessment = st.session_state.get('results') is not None
377
+
378
+ prompt = """You are HeedX, a professional AI mental wellness assistant embedded in the HeedX platform — a Nigerian mental health support application. You were developed to provide empathetic, culturally aware, and clinically informed mental wellness conversations for Nigerian users.
379
+
380
+ YOUR ROLE:
381
+ - Provide supportive, evidence-informed mental wellness conversations
382
+ - Give specific, actionable recommendations and coping strategies
383
+ - Interpret and explain the user's SVC model assessment results in plain language
384
+ - Reference the user's progress trends when relevant
385
+ - Maintain professional, warm, and non-judgmental tone throughout
386
+ - Be culturally sensitive to Nigerian values, family structures, and community dynamics
387
+
388
+ CLINICAL BOUNDARIES:
389
+ - You are not a licensed therapist and do not diagnose
390
+ - For high-risk or suicidal indicators, always direct to Nigerian crisis lines: 112 (emergency), 08062106493 (MANI), 08099769974 (She Writes Woman)
391
+ - Encourage professional consultation when warranted
392
+ - Never dismiss or minimise distress
393
+
394
+ TONE AND STYLE:
395
+ - Professional but warm — like a knowledgeable friend with clinical training
396
+ - Do not use emojis
397
+ - Write in clear, plain English that is accessible to Nigerian users
398
+ - Responses should be conversational but substantive — typically 3 to 6 sentences
399
+ - Vary your responses; do not repeat the same phrases
400
+
401
+ NIGERIAN CULTURAL CONTEXT:
402
+ - Acknowledge the role of faith, family, and community in Nigerian mental health
403
+ - Be aware of stigma around mental health in Nigerian society
404
+ - Reference local support systems where appropriate (Federal Neuro Hospitals: Yaba, Kaduna, Aro-Abeokuta)
405
+
406
+ """
407
+
408
+ if has_assessment:
409
+ prompt += "USER SESSION DATA (from the HeedX SVC psychotherapy model — use this to personalise your responses):\n"
410
+ prompt += session_context
411
+ prompt += "\n\nWhen the user asks about their results, feelings, or progress, refer to the above data specifically. Do not ask them to describe what the model already shows — interpret it for them and build on it."
412
+ else:
413
+ prompt += "USER SESSION DATA:\n"
414
+ prompt += session_context
415
+ prompt += "\n\nThe user has not completed a check-in yet. Warmly encourage them to complete one using the Check-In page so you can provide personalised insights. You may still engage in general mental wellness conversation in the meantime."
416
+
417
+ return prompt
418
+
419
+
420
+ # ============================================
421
+ # GROQ CHATBOT RESPONSE
422
+ # ============================================
423
+ def get_ai_response(user_message: str, api_key: str) -> str:
424
+ """
425
+ Build the full message history and call Groq.
426
+ Injects a fresh system prompt on every call so the
427
+ context always reflects the latest session state.
428
+ """
429
+ system_prompt = build_system_prompt()
430
+
431
+ # Crisis shortcut — handled locally before hitting API
432
+ crisis_keywords = [
433
+ 'kill myself', 'end my life', 'suicide', 'want to die',
434
+ 'no reason to live', 'hang myself', 'overdose',
435
+ 'hurt myself', 'self harm', 'take my life'
436
+ ]
437
+ if any(kw in user_message.lower() for kw in crisis_keywords):
438
+ return (
439
+ "What you have just shared is serious and I am glad you are talking. "
440
+ "Please reach out for immediate support right now:\n\n"
441
+ "- Emergency: Call 112\n"
442
+ "- Mentally Aware Nigeria Initiative (MANI): 08062106493\n"
443
+ "- She Writes Woman: 08099769974\n"
444
+ "- Visit the nearest Federal Neuropsychiatric Hospital\n\n"
445
+ "You do not have to face this alone. Would you like to talk about what is happening?"
446
+ )
447
+
448
+ # Build message list: system + conversation history + new user message
449
+ messages = [{"role": "system", "content": system_prompt}]
450
+
451
+ # Include up to last 10 exchanges for context window efficiency
452
+ for msg in st.session_state.chat_messages[-10:]:
453
+ messages.append({
454
+ "role": "user" if msg['role'] == 'user' else "assistant",
455
+ "content": msg['content']
456
+ })
457
+
458
+ messages.append({"role": "user", "content": user_message})
459
+
460
+ return call_groq(messages, api_key)
461
+
462
+
463
+ # ============================================
464
+ # CHAT PAGE (full page, mobile-friendly)
465
+ # ============================================
466
+ def render_chat_page():
467
+ """
468
+ Full-page Groq Llama 3 mental wellness chatbot.
469
+ Context-aware of SVC assessment results, risk level and session progress.
470
+ API key is loaded from .streamlit/secrets.toml — users never need to enter one.
471
+ """
472
+ st.markdown("<h2 class='sub-header'>Wellness Chat</h2>", unsafe_allow_html=True)
473
+ st.markdown(
474
+ "<p style='color:#4a5568;margin-top:-0.5rem;margin-bottom:1rem;'>"
475
+ "Speak with the HeedX AI wellness assistant. Responses are informed by "
476
+ "your assessment results and session progress.</p>",
477
+ unsafe_allow_html=True
478
+ )
479
+
480
+ # Resolve API key — secrets.toml takes priority, no user input needed
481
+ if not st.session_state.groq_api_key:
482
+ try:
483
+ st.session_state.groq_api_key = st.secrets["GROQ_API_KEY"]
484
+ except (KeyError, FileNotFoundError):
485
+ st.session_state.groq_api_key = ""
486
+
487
+ if not st.session_state.groq_api_key:
488
+ st.error(
489
+ "The chat assistant is not configured. "
490
+ "Please add GROQ_API_KEY to .streamlit/secrets.toml and restart the app."
491
+ )
492
+ if st.button("Back to Home", use_container_width=True):
493
+ st.session_state.page = 'home'
494
+ st.rerun()
495
+ return
496
+
497
+ # Context status banner
498
+ has_assessment = st.session_state.get('results') is not None
499
+ tracker = st.session_state.get('tracker')
500
+ has_progress = tracker is not None and tracker.has_history()
501
+
502
+ if has_assessment:
503
+ results = st.session_state['results']
504
+ primary = results['primary_indicator'].upper()
505
+ pct = f"{results['primary_percentage']:.1f}"
506
+ risk = st.session_state['analyzer'].get_risk_level().upper()
507
+ checkins = len(tracker.assessments) if has_progress else 0
508
+ st.markdown(
509
+ "<div style='background:#f0faf4;border-left:4px solid #008751;"
510
+ "border-radius:0 0.5rem 0.5rem 0;padding:0.75rem 1rem;"
511
+ "margin-bottom:1rem;font-size:0.88rem;color:#1a1a1a;'>"
512
+ "<strong>Active context from your assessment</strong><br>"
513
+ "Primary indicator: <strong>" + primary + "</strong> (" + pct + "%)&nbsp;&nbsp;|&nbsp;&nbsp;"
514
+ "Risk level: <strong>" + risk + "</strong>&nbsp;&nbsp;|&nbsp;&nbsp;"
515
+ "Check-ins: <strong>" + str(checkins) + "</strong>"
516
+ "</div>",
517
+ unsafe_allow_html=True
518
+ )
519
+ else:
520
+ st.markdown(
521
+ "<div style='background:#fef9e7;border-left:4px solid #e67e22;"
522
+ "border-radius:0 0.5rem 0.5rem 0;padding:0.75rem 1rem;"
523
+ "margin-bottom:1rem;font-size:0.88rem;color:#7d4e00;'>"
524
+ "No assessment completed yet. The assistant will encourage you to complete "
525
+ "a check-in so it can provide personalised responses based on your results."
526
+ "</div>",
527
+ unsafe_allow_html=True
528
+ )
529
+
530
+ st.markdown("---")
531
+
532
+ # Chat history
533
+ if not st.session_state.chat_messages:
534
+ st.markdown(
535
+ "<div class='chat-bot' style='max-width:640px;'>"
536
+ "Good day. I am the HeedX wellness assistant, powered by Llama 3. "
537
+ "I have access to your session data and assessment results to provide "
538
+ "personalised mental wellness support. How are you feeling today?"
539
+ "</div>",
540
+ unsafe_allow_html=True
541
+ )
542
+ else:
543
+ for msg in st.session_state.chat_messages:
544
+ if msg['role'] == 'user':
545
+ st.markdown(
546
+ "<div style='display:flex;justify-content:flex-end;margin:0.4rem 0;'>"
547
+ "<div class='chat-user' style='max-width:80%;'>"
548
+ + html_lib.escape(msg['content']) +
549
+ "</div></div>",
550
+ unsafe_allow_html=True
551
+ )
552
+ else:
553
+ content = msg['content'].replace('\n', '<br>')
554
+ st.markdown(
555
+ "<div style='display:flex;justify-content:flex-start;margin:0.4rem 0;'>"
556
+ "<div class='chat-bot' style='max-width:85%;'>"
557
+ + content +
558
+ "</div></div>",
559
+ unsafe_allow_html=True
560
+ )
561
+
562
+ st.markdown("---")
563
+
564
+ # Input form
565
+ with st.form("chat_page_form", clear_on_submit=True):
566
+ user_input = st.text_area(
567
+ "Your message",
568
+ placeholder="Share how you are feeling, ask a question, or discuss your results...",
569
+ height=110,
570
+ label_visibility="collapsed",
571
+ key="chat_page_input"
572
+ )
573
+ col_send, col_clear, col_back = st.columns([3, 1, 1])
574
+ with col_send:
575
+ send = st.form_submit_button("Send", use_container_width=True)
576
+ with col_clear:
577
+ clear = st.form_submit_button("Clear chat", use_container_width=True)
578
+ with col_back:
579
+ back = st.form_submit_button("Back", use_container_width=True)
580
+
581
+ if send and user_input and user_input.strip():
582
+ user_text = user_input.strip()
583
+ st.session_state.chat_messages.append({'role': 'user', 'content': user_text})
584
+ with st.spinner("HeedX is responding..."):
585
+ reply = get_ai_response(user_text, st.session_state.groq_api_key)
586
+ st.session_state.chat_messages.append({'role': 'bot', 'content': reply})
587
+ st.rerun()
588
+
589
+ if clear:
590
+ st.session_state.chat_messages = []
591
+ st.rerun()
592
+
593
+ if back:
594
+ st.session_state.page = 'home'
595
+ st.rerun()
596
+
597
+ st.caption(
598
+ "Powered by Llama 3.3-70b via Groq. Responses are supportive in nature "
599
+ "and do not constitute professional medical advice."
600
+ )
601
+
602
+
603
+ # ============================================
604
+ # SIDEBAR CONTACT CHANNELS
605
+ # ============================================
606
+ def render_sidebar_contacts():
607
+ """Quick-access contact buttons in the sidebar"""
608
+
609
+ st.sidebar.markdown("---")
610
+ st.sidebar.markdown("### Contact & Support")
611
+
612
+ # Counselling & Guidance
613
+ st.sidebar.markdown(
614
+ "<div class='sidebar-channel' style='background:#f0faf4;border-left:3px solid #008751;'>"
615
+ "<span style='color:#008751;'>Counselling and Guidance</span>"
616
+ "</div>",
617
+ unsafe_allow_html=True
618
+ )
619
+
620
+ whatsapp_number = CONTACT_INFO['whatsapp'].lstrip('0')
621
+ whatsapp_link = "https://wa.me/234" + whatsapp_number
622
+ call_number = CONTACT_INFO.get('phone', CONTACT_INFO['whatsapp'])
623
+
624
+ st.sidebar.markdown(
625
+ "<a href='" + whatsapp_link + "' target='_blank' class='contact-button'>"
626
+ "WhatsApp Counsellor</a>",
627
+ unsafe_allow_html=True
628
+ )
629
+ st.sidebar.markdown(
630
+ "<a href='tel:" + call_number + "' class='contact-button' "
631
+ "style='background-color:#008751;margin-bottom:0.6rem;'>"
632
+ "Call " + call_number + "</a>",
633
+ unsafe_allow_html=True
634
+ )
635
+
636
+ # Platform Support
637
+ st.sidebar.markdown(
638
+ "<div class='sidebar-channel' style='background:#f0f4ff;border-left:3px solid #2980b9;'>"
639
+ "<span style='color:#1565C0;'>Platform Support</span>"
640
+ "</div>",
641
+ unsafe_allow_html=True
642
+ )
643
+
644
+ support_email = CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
645
+ st.sidebar.markdown(
646
+ "<a href='mailto:" + support_email + "' target='_blank' class='email-button'>"
647
+ "Email Platform Support</a>",
648
+ unsafe_allow_html=True
649
+ )
650
+
651
+ platform_wa = CONTACT_INFO.get('platform_whatsapp', '')
652
+ if platform_wa:
653
+ pw_link = "https://wa.me/234" + platform_wa.lstrip('0')
654
+ st.sidebar.markdown(
655
+ "<a href='" + pw_link + "' target='_blank' class='contact-button'>"
656
+ "Platform WhatsApp</a>",
657
+ unsafe_allow_html=True
658
+ )
659
+
660
+
661
+ # ============================================
662
+ # NIGERIAN SUPPORT RESOURCES
663
+ # ============================================
664
+ def render_nigerian_support():
665
+ """Display comprehensive Nigerian support resources"""
666
+
667
+ with st.expander("Nigerian Support Resources", expanded=False):
668
+ st.markdown("### " + NIGERIA_EMERGENCY_NUMBERS['national']['title'])
669
+ for resource in NIGERIA_EMERGENCY_NUMBERS['national']['resources']:
670
+ st.markdown("- " + resource)
671
+
672
+ st.markdown("### " + NIGERIA_EMERGENCY_NUMBERS['state_emergency']['title'])
673
+ for resource in NIGERIA_EMERGENCY_NUMBERS['state_emergency']['resources']:
674
+ st.markdown("- " + resource)
675
+
676
+ st.markdown("---")
677
+ st.markdown("### " + MENTAL_HEALTH_SUPPORT['title'])
678
+ for resource in MENTAL_HEALTH_SUPPORT['resources']:
679
+ st.markdown("- " + resource)
680
+
681
+ st.markdown("---")
682
+ st.markdown("### " + PROFESSIONAL_HELP['title'])
683
+ for resource in PROFESSIONAL_HELP['resources']:
684
+ st.markdown("- " + resource)
685
+
686
+ st.markdown("---")
687
+ st.markdown("### " + FAITH_COMMUNITY_SUPPORT['title'])
688
+ for resource in FAITH_COMMUNITY_SUPPORT['resources']:
689
+ st.markdown("- " + resource)
690
+
691
+ st.markdown("---")
692
+ st.markdown("### Nigerian Wisdom for Mental Wellness")
693
+ for proverb in NIGERIAN_PROVERBS[:4]:
694
+ st.markdown("*\"" + proverb + "\"*")
695
+
696
+ st.markdown("---")
697
+ st.markdown("**Remember:** Help is available. You are not alone.")
698
+
699
+
700
+ # ============================================
701
+ # FEEDBACK / CONTACT SECTION (main page)
702
+ # ============================================
703
+ def render_feedback_section():
704
+ """Two clearly separated contact channels on the main page"""
705
+
706
+ st.markdown("### Contact and Support")
707
+
708
+ # Counselling & Guidance
709
+ st.markdown("""
710
+ <div style="background:#f0faf4;border-left:4px solid #008751;
711
+ border-radius:0 0.5rem 0.5rem 0;padding:1rem 1.2rem;margin-bottom:1rem;">
712
+ <p style="margin:0 0 0.3rem 0;font-weight:700;color:#008751;font-size:0.95rem;">
713
+ Mental Wellness Counselling and Guidance
714
+ </p>
715
+ <p style="margin:0;font-size:0.88rem;color:#2d3748;">
716
+ Reach out if you need to talk, seek emotional guidance, or want
717
+ personalised wellness advice from our counsellor.
718
+ </p>
719
+ </div>
720
+ """, unsafe_allow_html=True)
721
+
722
+ col1, col2 = st.columns(2)
723
+ with col1:
724
+ st.markdown("**WhatsApp — Counselling**")
725
+ whatsapp_number = CONTACT_INFO['whatsapp'].lstrip('0')
726
+ whatsapp_link = "https://wa.me/234" + whatsapp_number
727
+ st.markdown(
728
+ "<a href='" + whatsapp_link + "' target='_blank' class='contact-button'>"
729
+ "Chat with Counsellor</a>",
730
+ unsafe_allow_html=True
731
+ )
732
+ st.caption("Monday to Friday, 9 am to 5 pm")
733
+
734
+ with col2:
735
+ st.markdown("**Call or SMS**")
736
+ call_number = CONTACT_INFO.get('phone', CONTACT_INFO['whatsapp'])
737
+ st.markdown(
738
+ "<a href='tel:" + call_number + "' class='contact-button' "
739
+ "style='background-color:#008751;'>"
740
+ "Call " + call_number + "</a>",
741
+ unsafe_allow_html=True
742
+ )
743
+ st.caption("Voice calls welcome during hours above")
744
+
745
+ st.markdown("<br>", unsafe_allow_html=True)
746
+
747
+ # Platform Support
748
+ st.markdown("""
749
+ <div style="background:#f0f4ff;border-left:4px solid #2980b9;
750
+ border-radius:0 0.5rem 0.5rem 0;padding:1rem 1.2rem;margin-bottom:1rem;">
751
+ <p style="margin:0 0 0.3rem 0;font-weight:700;color:#1565C0;font-size:0.95rem;">
752
+ Platform Support
753
+ </p>
754
+ <p style="margin:0;font-size:0.88rem;color:#2d3748;">
755
+ Bug reports, feature requests, account questions, or any technical
756
+ issue with the HeedX AI platform.
757
+ </p>
758
+ </div>
759
+ """, unsafe_allow_html=True)
760
+
761
+ col3, col4 = st.columns(2)
762
+ with col3:
763
+ st.markdown("**Support Email**")
764
+ support_email = CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
765
+ st.markdown(
766
+ "<a href='mailto:" + support_email + "' target='_blank' class='email-button'>"
767
+ "Email Platform Support</a>",
768
+ unsafe_allow_html=True
769
+ )
770
+ st.caption("Response within 24 to 48 hours")
771
+
772
+ with col4:
773
+ st.markdown("**Platform WhatsApp**")
774
+ platform_wa = CONTACT_INFO.get('platform_whatsapp', CONTACT_INFO.get('whatsapp_support', ''))
775
+ if platform_wa:
776
+ pw_link = "https://wa.me/234" + platform_wa.lstrip('0')
777
+ st.markdown(
778
+ "<a href='" + pw_link + "' target='_blank' class='contact-button'>"
779
+ "Platform WhatsApp</a>",
780
+ unsafe_allow_html=True
781
+ )
782
+ else:
783
+ st.info("Platform WhatsApp — coming soon")
784
+
785
+ with st.expander("Send a Message", expanded=False):
786
+ contact_type = st.radio(
787
+ "What is this about?",
788
+ ["Counselling and Guidance", "Platform Support, Bug or Feature Request"],
789
+ horizontal=True
790
+ )
791
+ feedback_type = st.selectbox(
792
+ "Category",
793
+ ["General Enquiry", "Suggestion", "Bug Report",
794
+ "Feature Request", "Support Question", "Other"]
795
+ )
796
+ feedback_text = st.text_area(
797
+ "Your Message",
798
+ placeholder="Please describe your question or feedback...",
799
+ height=100
800
+ )
801
+ if st.button("Send Message"):
802
+ if feedback_text.strip():
803
+ subject = "HeedX AI - " + contact_type.split()[0] + ": " + feedback_type
804
+ body = "Category: " + feedback_type + "\nChannel: " + contact_type + "\n\nMessage:\n" + feedback_text
805
+ recipient = CONTACT_INFO['email'] if "Counselling" in contact_type else CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
806
+ mailto_link = "mailto:" + recipient + "?subject=" + urllib.parse.quote(subject) + "&body=" + urllib.parse.quote(body)
807
+ st.markdown(
808
+ "<a href='" + mailto_link + "' target='_blank'>Click to open email client</a>",
809
+ unsafe_allow_html=True
810
+ )
811
+ st.success("Email client opened. Please send the pre-filled email.")
812
+ else:
813
+ st.warning("Please enter a message before sending.")
814
+
815
+
816
+ # ============================================
817
+ # PROGRESS TRACKING
818
+ # ============================================
819
+ def render_progress_tracking():
820
+ """Render user progress tracking visualizations"""
821
+
822
+ st.markdown("""
823
+ <div style="margin:2rem 0 1rem 0;text-align:center;">
824
+ <h3 style="color:#008751;font-weight:600;">Your Progress This Session</h3>
825
+ <p style="color:#4a5568;margin-top:0.4rem;">
826
+ Track your mental wellness journey and notice patterns over time.
827
+ </p>
828
+ </div>
829
+ """, unsafe_allow_html=True)
830
+
831
+ if not st.session_state.get('tracker'):
832
+ st.info("Complete a check-in to start tracking your progress this session.")
833
+ return
834
+
835
+ tracker = st.session_state.tracker
836
+ df_history = tracker.get_history_dataframe()
837
+
838
+ if df_history.empty:
839
+ st.info("No assessments yet. Complete a check-in to see your progress.")
840
+ return
841
+
842
+ summary = tracker.get_progress_summary()
843
+
844
+ # Summary banner
845
+ st.markdown(
846
+ "<div style='background:linear-gradient(135deg,#e6fffa 0%,#c6f6d5 100%);"
847
+ "border-radius:1rem;padding:1.2rem;text-align:center;"
848
+ "margin-bottom:1.5rem;border:1px solid #9ae6b4;'>"
849
+ "<span style='font-size:1rem;color:#1a202c;'>You have completed </span>"
850
+ "<span style='font-size:2rem;font-weight:700;color:#065f46;margin:0 0.5rem;'>"
851
+ + str(len(df_history)) +
852
+ "</span>"
853
+ "<span style='font-size:1rem;color:#1a202c;'>"
854
+ + ("check-ins" if len(df_history) > 1 else "check-in") +
855
+ " in this session.</span>"
856
+ "</div>",
857
+ unsafe_allow_html=True
858
+ )
859
+
860
+ # Summary cards
861
+ col1, col2, col3, col4 = st.columns(4)
862
+
863
+ def metric_card(value, label):
864
+ return (
865
+ "<div style='background:white;border-radius:0.75rem;padding:1rem;"
866
+ "text-align:center;box-shadow:0 1px 6px rgba(0,0,0,0.06);"
867
+ "border:1px solid #e2e8f0;'>"
868
+ "<div style='font-size:1.4rem;font-weight:700;color:#008751;'>" + str(value) + "</div>"
869
+ "<div style='color:#4a5568;font-size:0.78rem;margin-top:0.2rem;'>" + label + "</div>"
870
+ "</div>"
871
+ )
872
+
873
+ with col1:
874
+ st.markdown(metric_card(summary['total_assessments'], "Total Check-ins"), unsafe_allow_html=True)
875
+ with col2:
876
+ st.markdown(metric_card(summary['first_date'], "First Check-in"), unsafe_allow_html=True)
877
+ with col3:
878
+ st.markdown(metric_card(summary['last_date'], "Most Recent"), unsafe_allow_html=True)
879
+ with col4:
880
+ most_common = summary.get('most_common_primary', 'N/A')
881
+ st.markdown(metric_card(most_common.title() if most_common else "N/A", "Most Common"), unsafe_allow_html=True)
882
+
883
+ # Trend chart
884
+ st.markdown("#### Indicator Trends")
885
+
886
+ fig = go.Figure()
887
+ traces = [
888
+ ("Anxiety", "#e67e22", "anxiety"),
889
+ ("Depression", "#2980b9", "depression"),
890
+ ("Suicidal", "#c0392b", "suicidal"),
891
+ ("Normal", "#27ae60", "normal"),
892
+ ]
893
+ for name, color, col in traces:
894
+ if col in df_history.columns:
895
+ fig.add_trace(go.Scatter(
896
+ x=df_history['assessment'],
897
+ y=df_history[col],
898
+ mode='lines+markers',
899
+ name=name,
900
+ line=dict(color=color, width=2.5),
901
+ marker=dict(size=8),
902
+ ))
903
+
904
+ fig.update_layout(
905
+ xaxis=dict(title="Check-in Number"),
906
+ yaxis=dict(title="Percentage (%)", range=[0, 100]),
907
+ hovermode='x unified',
908
+ height=420,
909
+ plot_bgcolor='white',
910
+ paper_bgcolor='white',
911
+ margin=dict(t=20, b=40),
912
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
913
+ )
914
+ fig.update_xaxes(showgrid=True, gridcolor='#f0f0f0')
915
+ fig.update_yaxes(showgrid=True, gridcolor='#f0f0f0')
916
+ st.plotly_chart(fig, use_container_width=True)
917
+
918
+ # Trend insights
919
+ if summary.get('trend'):
920
+ trend = summary['trend']
921
+ insights = []
922
+
923
+ if trend.get('normal', 0) > 5:
924
+ insights.append("Positive wellbeing improvement of +" + str(round(trend['normal'])) + "% since your first check-in.")
925
+ if trend.get('anxiety', 0) < 0:
926
+ insights.append("Anxiety indicators have reduced by " + str(abs(round(trend['anxiety']))) + "%.")
927
+ if trend.get('depression', 0) < 0:
928
+ insights.append("Depression indicators are improving by " + str(abs(round(trend['depression']))) + "%.")
929
+ if trend.get('suicidal', 0) > 2:
930
+ insights.append("An increase in difficult thoughts has been noted. Please consider reaching out for support.")
931
+ elif trend.get('suicidal', 0) > 0:
932
+ insights.append("A slight increase in difficult thought indicators. Continued support is recommended.")
933
+ if not insights:
934
+ insights.append("Your indicators are stable across this session.")
935
+
936
+ st.markdown("**Session Insights**")
937
+ for insight in insights[:4]:
938
+ st.markdown("- " + insight)
939
+
940
+ with st.expander("View All Check-Ins"):
941
+ st.dataframe(df_history, use_container_width=True)
942
+
943
+ st.caption("Your data exists only within this browser session and is cleared when you close the tab.")
944
+
945
+
946
+ # ============================================
947
+ # HOME PAGE
948
+ # ============================================
949
+ def render_home_page():
950
+ """Render the home page"""
951
+
952
+ st.markdown("<h1 class='main-header'>HeedX AI</h1>", unsafe_allow_html=True)
953
+ st.markdown(
954
+ "<p style='text-align:center;color:#008751;font-size:1.05rem;'>"
955
+ "Your Nigerian Mental Wellness Companion</p>",
956
+ unsafe_allow_html=True
957
+ )
958
+ st.markdown(
959
+ "<p style='text-align:center;color:#4a5568;font-size:0.9rem;'>"
960
+ "Understand. Respond. Support.</p>",
961
+ unsafe_allow_html=True
962
+ )
963
+ st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
964
+
965
+ col1, col2, col3 = st.columns([1, 2, 1])
966
+
967
+ with col2:
968
+ st.markdown("""
969
+ <div style="background:white;border-radius:0.75rem;padding:1.5rem;margin:1rem 0;
970
+ text-align:center;box-shadow:0 2px 10px rgba(0,0,0,0.05);
971
+ border:1px solid #e2e8f0;">
972
+ <p style="font-size:1.1rem;color:#2d3748;margin:0;">
973
+ A professional space to reflect, understand, and nurture your mental wellbeing.
974
+ </p>
975
+ <p style="font-size:0.88rem;color:#008751;margin-top:0.6rem;margin-bottom:0;">
976
+ Nigerian resources &nbsp;|&nbsp; Culturally adapted &nbsp;|&nbsp; Free and confidential
977
+ </p>
978
+ </div>
979
+ """, unsafe_allow_html=True)
980
+
981
+ st.markdown("""
982
+ ### How It Works
983
+
984
+ 1. **Complete a check-in** by answering questions about how you have been feeling
985
+ 2. **The AI model analyzes** your responses at sentence level
986
+ 3. **Receive insights**, risk assessment, and tailored recommendations
987
+ 4. **Chat with HeedX**, our AI wellness assistant, for personalised guidance
988
+ 5. **Track your journey** and monitor changes across check-ins
989
+
990
+ All data remains private within your current browser session.
991
+ """)
992
+
993
+ render_nigerian_support()
994
+
995
+ if st.session_state.tracker:
996
+ st.info(
997
+ "Check-ins completed this session: " + str(len(st.session_state.tracker.assessments))
998
+ )
999
+
1000
+ if st.button("Start Your Check-In", use_container_width=True):
1001
+ if not st.session_state.tracker:
1002
+ st.session_state.tracker = SessionTracker()
1003
+ st.session_state.page = 'questionnaire'
1004
+ st.rerun()
1005
+
1006
+ if st.session_state.tracker and st.session_state.tracker.has_history():
1007
+ st.markdown("---")
1008
+ st.markdown("### Recent Session Activity")
1009
+ history_df = st.session_state.tracker.get_history_dataframe()
1010
+ if not history_df.empty:
1011
+ for _, row in history_df.tail(3).iterrows():
1012
+ st.markdown(
1013
+ "<div class='history-card'>"
1014
+ + str(row['date']) +
1015
+ " &nbsp;&mdash;&nbsp; Primary: " + str(row['primary']).upper() +
1016
+ " &nbsp;&mdash;&nbsp; " + str(round(row['primary_pct'])) + "%"
1017
+ "</div>",
1018
+ unsafe_allow_html=True
1019
+ )
1020
+ if st.button("View Full Progress", use_container_width=True):
1021
+ st.session_state.page = 'progress'
1022
+ st.rerun()
1023
+
1024
+ st.markdown("""
1025
+ <div class='disclaimer'>
1026
+ <p>This is a supportive tool, not a medical diagnosis.</p>
1027
+ <p>If you are in crisis, call <strong>112</strong> (National Emergency)
1028
+ or <strong>08062106493</strong> (Mentally Aware Nigeria Initiative) immediately.</p>
1029
+ <p>Your life is valuable. Help is available.</p>
1030
+ </div>
1031
+ """, unsafe_allow_html=True)
1032
+
1033
+
1034
+ # ============================================
1035
+ # QUESTIONNAIRE PAGE
1036
+ # ============================================
1037
+ def render_questionnaire_page():
1038
+ """Render the questionnaire page"""
1039
+
1040
+ if not st.session_state.tracker:
1041
+ st.session_state.tracker = SessionTracker()
1042
+
1043
+ st.markdown("<h2 class='sub-header'>Mental Health Questionnaire</h2>",
1044
+ unsafe_allow_html=True)
1045
+
1046
+ if len(st.session_state.tracker.assessments) > 0:
1047
+ st.info("Check-ins completed this session: " + str(len(st.session_state.tracker.assessments)))
1048
+
1049
+ st.markdown(
1050
+ "Answer each question as fully as you can. "
1051
+ "The more detail you provide, the more accurate the analysis will be."
1052
+ )
1053
+
1054
+ if 'responses' not in st.session_state:
1055
+ st.session_state.responses = {}
1056
+
1057
+ with st.form("questionnaire_form"):
1058
+ for q in QUESTIONNAIRE:
1059
+ st.markdown("**" + q['question'] + "**")
1060
+ default_value = st.session_state.get("input_" + q['id'], "")
1061
+ response = st.text_area(
1062
+ label="Response for " + q['id'],
1063
+ label_visibility="collapsed",
1064
+ placeholder=q['placeholder'],
1065
+ value=default_value,
1066
+ height=100,
1067
+ key="input_" + q['id']
1068
+ )
1069
+ st.session_state.responses[q['id']] = response
1070
+ st.markdown("---")
1071
+
1072
+ submitted = st.form_submit_button("Analyze My Check-In", use_container_width=True)
1073
+
1074
+ if submitted:
1075
+ has_content = any(v and v.strip() for v in st.session_state.responses.values())
1076
+ if has_content:
1077
+ st.session_state.page = 'analysis'
1078
+ st.rerun()
1079
+ else:
1080
+ st.warning("Please share a little about how you are feeling before submitting.")
1081
+
1082
+ col1, _, _ = st.columns([1, 2, 1])
1083
+ with col1:
1084
+ if st.button("Back to Home", use_container_width=True):
1085
+ st.session_state.page = 'home'
1086
+ st.rerun()
1087
+
1088
+
1089
+ # ============================================
1090
+ # ANALYSIS PAGE
1091
+ # ============================================
1092
+ def render_analysis_page(model):
1093
+ """Render the analysis page with sentence-level results"""
1094
+
1095
+ st.markdown("<h2 class='sub-header'>Analyzing Your Responses</h2>",
1096
+ unsafe_allow_html=True)
1097
+
1098
+ analyzer = MentalHealthAnalyzer(model, model.classes_)
1099
+ progress_bar = st.progress(0)
1100
+ status_text = st.empty()
1101
+ all_sentences = []
1102
+ errors = 0
1103
+
1104
+ for i, (q_id, response) in enumerate(st.session_state.responses.items()):
1105
+ if response and response.strip():
1106
+ status_text.text("Analyzing question " + str(i + 1) + " of " + str(len(QUESTIONNAIRE)) + "...")
1107
+ try:
1108
+ cleaned = clean_response(response)
1109
+ sentence_results = analyzer.analyze_response(cleaned, q_id)
1110
+ all_sentences.extend(sentence_results)
1111
+ except Exception:
1112
+ errors += 1
1113
+ st.warning("Could not fully analyze question " + str(i + 1) + " — skipping.")
1114
+
1115
+ progress_bar.progress((i + 1) / len(QUESTIONNAIRE))
1116
+
1117
+ if errors:
1118
+ st.info(str(errors) + " question(s) were skipped due to processing issues.")
1119
+
1120
+ st.session_state.analyzer = analyzer
1121
+ analyzer.sentence_predictions = all_sentences
1122
+ analyzer.aggregated_results = analyzer._aggregate_predictions()
1123
+ st.session_state.results = analyzer.aggregated_results
1124
+ st.session_state.analysis_complete = True
1125
+
1126
+ if st.session_state.tracker:
1127
+ st.session_state.tracker.add_assessment(
1128
+ analyzer.aggregated_results,
1129
+ st.session_state.responses
1130
+ )
1131
+
1132
+ status_text.text("Analysis complete.")
1133
+ progress_bar.empty()
1134
+
1135
+ st.markdown("### Sentence-Level Analysis")
1136
+ st.caption(
1137
+ "Each sentence from your responses has been classified by the classifying model. "
1138
+ "Results below show the predicted indicator per sentence."
1139
+ )
1140
+
1141
+ COLOR_MAP = {
1142
+ 'suicidal': ("#fff0f0", "Suicidal"),
1143
+ 'anxiety': ("#fffbf0", "Anxiety"),
1144
+ 'depression': ("#f0f4ff", "Depression"),
1145
+ 'normal': ("#f8f9fa", "Normal"),
1146
+ }
1147
+
1148
+ visible = all_sentences[:10]
1149
+ hidden = all_sentences[10:]
1150
+
1151
+ if visible:
1152
+ for sent_result in visible:
1153
+ prediction = sent_result.get('prediction', 'normal')
1154
+ color, label = COLOR_MAP.get(prediction, ("#f8f9fa", "Normal"))
1155
+ safe_sentence = html_lib.escape(sent_result.get('sentence', ''))
1156
+ conf_text = ""
1157
+ if sent_result.get('confidence'):
1158
+ conf_text = " &mdash; Confidence: " + f"{sent_result['confidence']:.1%}"
1159
+
1160
+ html_block = (
1161
+ "<div class='sentence-box' style='background-color:" + color + ";'>"
1162
+ "<span style='color:#555;font-size:0.82rem;'>" + label + conf_text + "</span><br>"
1163
+ "<span>" + safe_sentence + "</span>"
1164
+ "</div>"
1165
+ )
1166
+ st.markdown(html_block, unsafe_allow_html=True)
1167
+
1168
+ if hidden:
1169
+ with st.expander("Show remaining " + str(len(hidden)) + " sentences"):
1170
+ for sent_result in hidden:
1171
+ prediction = sent_result.get('prediction', 'normal')
1172
+ color, label = COLOR_MAP.get(prediction, ("#f8f9fa", "Normal"))
1173
+ safe_sentence = html_lib.escape(sent_result.get('sentence', ''))
1174
+ conf_text = ""
1175
+ if sent_result.get('confidence'):
1176
+ conf_text = " &mdash; Confidence: " + f"{sent_result['confidence']:.1%}"
1177
+ html_block = (
1178
+ "<div class='sentence-box' style='background-color:" + color + ";'>"
1179
+ "<span style='color:#555;font-size:0.82rem;'>" + label + conf_text + "</span><br>"
1180
+ "<span>" + safe_sentence + "</span>"
1181
+ "</div>"
1182
+ )
1183
+ st.markdown(html_block, unsafe_allow_html=True)
1184
+ else:
1185
+ st.warning("No analyzable sentences were found. Please provide more detail in your responses.")
1186
+
1187
+ if st.button("View Assessment Summary", use_container_width=True):
1188
+ st.session_state.page = 'summary'
1189
+ st.rerun()
1190
+
1191
+
1192
+ # ============================================
1193
+ # SUMMARY PAGE
1194
+ # ============================================
1195
+ def render_summary_page():
1196
+ """Render the summary page with results and progress"""
1197
+
1198
+ st.markdown("<h2 class='sub-header'>Assessment Summary</h2>",
1199
+ unsafe_allow_html=True)
1200
+
1201
+ if not st.session_state.results:
1202
+ st.error("No analysis results found.")
1203
+ if st.button("Back to Questionnaire"):
1204
+ st.session_state.page = 'questionnaire'
1205
+ st.rerun()
1206
+ return
1207
+
1208
+ results = st.session_state.results
1209
+ analyzer = st.session_state.analyzer
1210
+ risk_level = analyzer.get_risk_level()
1211
+ recommender = RecommendationEngine()
1212
+ suicidal_flagged = analyzer.get_suicidal_flagged_sentences()
1213
+ recommendations = recommender.get_recommendations(
1214
+ results['primary_indicator'], risk_level, suicidal_flagged
1215
+ )
1216
+
1217
+ # Indicators
1218
+ col1, col2 = st.columns(2)
1219
+ with col1:
1220
+ st.markdown("### Primary Indicator")
1221
+ primary = results['primary_indicator']
1222
+ pct = results['primary_percentage']
1223
+ if primary == 'suicidal':
1224
+ st.error("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1225
+ elif primary in ['anxiety', 'depression']:
1226
+ st.warning("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1227
+ else:
1228
+ st.success("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1229
+
1230
+ with col2:
1231
+ if results['secondary_indicator']:
1232
+ st.markdown("### Secondary Indicator")
1233
+ secondary = results['secondary_indicator']
1234
+ st.info("**" + secondary.upper() + "** (" + f"{results['secondary_percentage']:.1f}" + "%)")
1235
+
1236
+ # Risk level
1237
+ st.markdown("### Risk Assessment")
1238
+ risk_map = {
1239
+ "high": ("risk-high", "HIGH RISK — Immediate support is strongly recommended."),
1240
+ "moderate_high": ("risk-high", "MODERATE-HIGH RISK — Please speak with a mental health professional."),
1241
+ "moderate": ("risk-moderate", "MODERATE RISK — Consider professional support."),
1242
+ "mild": ("risk-moderate", "MILD RISK — Self-care strategies are recommended."),
1243
+ "low": ("risk-low", "LOW RISK — Continue maintaining your mental wellness."),
1244
+ }
1245
+ css_class, message = risk_map.get(risk_level, ("risk-low", "Status could not be determined."))
1246
+ st.markdown("<div class='" + css_class + "'>" + message + "</div>", unsafe_allow_html=True)
1247
+
1248
+ # Distribution chart
1249
+ st.markdown("### Distribution of Indicators")
1250
+ df_dist = create_distribution_dataframe(results['distribution'])
1251
+ fig = px.bar(
1252
+ df_dist,
1253
+ x='Mental Health Indicator',
1254
+ y='Percentage',
1255
+ color='Mental Health Indicator',
1256
+ color_discrete_map={
1257
+ 'anxiety': '#e67e22',
1258
+ 'depression': '#2980b9',
1259
+ 'suicidal': '#c0392b',
1260
+ 'normal': '#27ae60',
1261
+ },
1262
+ text=df_dist['Percentage'].apply(lambda x: f"{x:.1f}%")
1263
+ )
1264
+ fig.update_layout(
1265
+ xaxis_title="",
1266
+ yaxis_title="Percentage of Sentences (%)",
1267
+ showlegend=False,
1268
+ height=380,
1269
+ plot_bgcolor='white',
1270
+ paper_bgcolor='white',
1271
+ margin=dict(t=10, b=40)
1272
+ )
1273
+ fig.update_traces(textposition='outside')
1274
+ fig.update_xaxes(showgrid=False)
1275
+ fig.update_yaxes(showgrid=True, gridcolor='#f0f0f0')
1276
+ st.plotly_chart(fig, use_container_width=True)
1277
+
1278
+ # Recommendations
1279
+ st.markdown("### Recommendations")
1280
+ if recommendations:
1281
+ st.markdown("#### " + recommendations['title'])
1282
+ st.markdown(recommendations['message'])
1283
+ for i, tip in enumerate(recommendations['tips'], 1):
1284
+ st.markdown(str(i) + ". " + tip)
1285
+
1286
+ # Crisis resources
1287
+ if risk_level in ['high', 'moderate_high']:
1288
+ with st.expander("Immediate Help — Nigeria", expanded=True):
1289
+ st.markdown("### " + CRISIS_RESOURCES['title'])
1290
+ st.markdown(CRISIS_RESOURCES['message'])
1291
+ for resource in CRISIS_RESOURCES['resources']:
1292
+ st.markdown("- " + resource)
1293
+ st.markdown("*" + CRISIS_RESOURCES['hospital_note'] + "*")
1294
+ st.markdown("---")
1295
+ st.markdown("**You are not alone. Reaching out is a sign of strength.**")
1296
+
1297
+ # Flagged sentences
1298
+ if suicidal_flagged:
1299
+ with st.expander("Sentences Flagged for Review",
1300
+ expanded=risk_level in ['high', 'moderate_high']):
1301
+ st.caption(
1302
+ "The following sentences were identified by the model as containing "
1303
+ "indicators associated with suicidal ideation."
1304
+ )
1305
+ for sent in suicidal_flagged:
1306
+ st.markdown("- *" + html_lib.escape(sent['sentence']) + "*")
1307
+
1308
+ # Nigerian wisdom
1309
+ with st.expander("Nigerian Wisdom", expanded=False):
1310
+ st.markdown("**Words of encouragement from our culture:**")
1311
+ for proverb in NIGERIAN_PROVERBS:
1312
+ st.markdown("*\"" + proverb + "\"*")
1313
+
1314
+ st.markdown("---")
1315
+ render_progress_tracking()
1316
+
1317
+ st.markdown("---")
1318
+ render_feedback_section()
1319
+
1320
+ # Action buttons
1321
+ col1, col2, col3 = st.columns(3)
1322
+
1323
+ with col1:
1324
+ if st.button("New Check-In", use_container_width=True):
1325
+ for q in QUESTIONNAIRE:
1326
+ st.session_state["input_" + q['id']] = ""
1327
+ for key in ['responses', 'analyzer', 'results', 'analysis_complete']:
1328
+ st.session_state.pop(key, None)
1329
+ st.session_state.page = 'questionnaire'
1330
+ st.rerun()
1331
+
1332
+ with col2:
1333
+ if st.button("Home", use_container_width=True):
1334
+ st.session_state.page = 'home'
1335
+ st.rerun()
1336
+
1337
+ with col3:
1338
+ nat_resources = NIGERIA_EMERGENCY_NUMBERS['national']['resources']
1339
+ state_resources = NIGERIA_EMERGENCY_NUMBERS['state_emergency']['resources']
1340
+
1341
+ report_lines = [
1342
+ "HEEDX AI - MENTAL HEALTH CHECK-IN REPORT",
1343
+ "Generated : " + datetime.now().strftime('%Y-%m-%d %H:%M'),
1344
+ "",
1345
+ "PRIMARY INDICATOR : " + results['primary_indicator'].upper() +
1346
+ " (" + f"{results['primary_percentage']:.1f}" + "%)",
1347
+ ]
1348
+ if results['secondary_indicator']:
1349
+ report_lines.append(
1350
+ "SECONDARY INDICATOR: " + results['secondary_indicator'].upper() +
1351
+ " (" + f"{results['secondary_percentage']:.1f}" + "%)"
1352
+ )
1353
+ report_lines += [
1354
+ "",
1355
+ "RISK LEVEL: " + risk_level.upper(),
1356
+ "",
1357
+ "DISTRIBUTION:",
1358
+ *[" - " + k + ": " + f"{v:.1f}" + "%" for k, v in results['distribution'].items()],
1359
+ "",
1360
+ "RECOMMENDATIONS:",
1361
+ *[" " + str(i) + ". " + tip for i, tip in enumerate(recommendations['tips'], 1)],
1362
+ "",
1363
+ "NIGERIAN EMERGENCY RESOURCES:",
1364
+ *[" - " + r for r in nat_resources],
1365
+ *[" - " + r for r in state_resources],
1366
+ "",
1367
+ "DISCLAIMER: This is an AI-generated assessment, not a medical diagnosis.",
1368
+ "If you are in crisis, call 112 or visit the nearest Federal Neuropsychiatric Hospital.",
1369
+ ]
1370
+
1371
+ st.download_button(
1372
+ label="Download Report",
1373
+ data="\n".join(report_lines),
1374
+ file_name="heedx_report_" + datetime.now().strftime('%Y%m%d_%H%M') + ".txt",
1375
+ mime="text/plain",
1376
+ use_container_width=True
1377
+ )
1378
+
1379
+
1380
+ # ============================================
1381
+ # PROGRESS PAGE
1382
+ # ============================================
1383
+ def render_progress_page():
1384
+ """Render the standalone progress page"""
1385
+
1386
+ st.markdown("<h2 class='sub-header'>Your Wellness Journey</h2>", unsafe_allow_html=True)
1387
+
1388
+ if not st.session_state.tracker:
1389
+ st.info("Complete your first check-in to see your progress.")
1390
+ if st.button("Start Check-In", use_container_width=True):
1391
+ st.session_state.page = 'questionnaire'
1392
+ st.rerun()
1393
+ return
1394
+
1395
+ render_progress_tracking()
1396
+
1397
+ if st.button("Back to Home", use_container_width=True):
1398
+ st.session_state.page = 'home'
1399
+ st.rerun()
1400
+
1401
+
1402
+ # ============================================
1403
+ # MAIN
1404
+ # ============================================
1405
+ def main():
1406
+ """Main application controller"""
1407
+
1408
+ init_session_state()
1409
+
1410
+ # Load model before sidebar renders — chatbot context depends on it
1411
+ if 'model' not in st.session_state:
1412
+ with st.spinner("Loading HeedX AI..."):
1413
+ st.session_state.model = load_model()
1414
+
1415
+ model = st.session_state.model
1416
+
1417
+ # ── Sidebar ───────────────────────────────────────────────────────────────
1418
+ with st.sidebar:
1419
+ st.markdown(
1420
+ "<div style='text-align:center;padding:0.5rem 0;'>"
1421
+ "<span style='font-size:1.5rem;font-weight:700;color:#008751;'>HeedX AI</span><br>"
1422
+ "<span style='font-size:0.78rem;color:#718096;'>Nigerian Mental Wellness Platform</span>"
1423
+ "</div>",
1424
+ unsafe_allow_html=True
1425
+ )
1426
+ st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
1427
+
1428
+ # Navigation
1429
+ st.markdown("**Navigation**")
1430
+ if st.button("Home", use_container_width=True):
1431
+ st.session_state.page = 'home'
1432
+ st.rerun()
1433
+ if st.button("Check-In", use_container_width=True):
1434
+ st.session_state.page = 'questionnaire'
1435
+ st.rerun()
1436
+ if st.button("Wellness Chat", use_container_width=True):
1437
+ st.session_state.page = 'chat'
1438
+ st.rerun()
1439
+ if st.session_state.get('analysis_complete', False):
1440
+ if st.button("Summary", use_container_width=True):
1441
+ st.session_state.page = 'summary'
1442
+ st.rerun()
1443
+ if st.session_state.tracker and st.session_state.tracker.has_history():
1444
+ if st.button("Progress", use_container_width=True):
1445
+ st.session_state.page = 'progress'
1446
+ st.rerun()
1447
+
1448
+ st.markdown("---")
1449
+
1450
+ with st.expander("Emergency Numbers", expanded=False):
1451
+ st.markdown("**Emergency:** 112")
1452
+ for r in NIGERIA_EMERGENCY_NUMBERS['national']['resources'][:3]:
1453
+ st.markdown("- " + r)
1454
+
1455
+ with st.expander("Disclaimer"):
1456
+ st.markdown(
1457
+ "This tool is for informational and supportive purposes only. "
1458
+ "It is not a substitute for professional medical advice. "
1459
+ "If you are in crisis, call **112** immediately."
1460
+ )
1461
+
1462
+ # Contact channels — always visible
1463
+ render_sidebar_contacts()
1464
+
1465
+ # ── Guard against missing model ───────────────────────────────────────────
1466
+ if model is None:
1467
+ st.error(
1468
+ "The model could not be loaded."
1469
+ )
1470
+ st.stop()
1471
+
1472
+ # ── Page dispatch ─────────────────────────────────────────────────────────
1473
+ PAGE_MAP = {
1474
+ 'home': lambda: render_home_page(),
1475
+ 'questionnaire': lambda: render_questionnaire_page(),
1476
+ 'analysis': lambda: render_analysis_page(model),
1477
+ 'summary': lambda: render_summary_page(),
1478
+ 'progress': lambda: render_progress_page(),
1479
+ 'chat': lambda: render_chat_page(),
1480
+ }
1481
+
1482
+ page_fn = PAGE_MAP.get(st.session_state.page, lambda: render_home_page())
1483
+ page_fn()
1484
+
1485
+ # ── Footer ────────────────────────────────────────────────────────────────
1486
+ st.markdown("---")
1487
+ st.markdown("""
1488
+ <div class='disclaimer'>
1489
+ <p><strong>HeedX AI &mdash; Nigerian Edition</strong></p>
1490
+ <p>This is a supportive tool only and does not constitute a medical diagnosis.</p>
1491
+ <p>Crisis lines: <strong>112</strong> (National Emergency) &nbsp;|&nbsp;
1492
+ <strong>08062106493</strong> (Mentally Aware Nigeria Initiative)</p>
1493
+ <p>You are not alone. Help is always available.</p>
1494
+ </div>
1495
+ """, unsafe_allow_html=True)
1496
+
1497
+
1498
+ if __name__ == "__main__":
1499
+ main()
mental_health_app_real/psychotherapy_svm_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5cfe9577a319ca09b9fb21e83eb3d4514b640ec96ce138e6e7d1d8b04fcbf4f
3
+ size 359512
mental_health_app_real/utils/__init__.py.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # utils/__init__.py
2
+ # This file makes the utils directory a Python package
mental_health_app_real/utils/__pycache__/analysis.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
mental_health_app_real/utils/__pycache__/preprocessing.cpython-310.pyc ADDED
Binary file (1.72 kB). View file
 
mental_health_app_real/utils/__pycache__/recommendations.cpython-310.pyc ADDED
Binary file (2.05 kB). View file
 
mental_health_app_real/utils/__pycache__/session_storage.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
mental_health_app_real/utils/__pycache__/storage.cpython-310.pyc ADDED
Binary file (5 kB). View file
 
mental_health_app_real/utils/analysis.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core analysis engine: sentence-level prediction and aggregation
3
+ """
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+ from collections import Counter
8
+ from .preprocessing import preprocess_text, split_sentences
9
+
10
+
11
+ class MentalHealthAnalyzer:
12
+ """
13
+ Handles all analysis logic for mental health predictions
14
+ """
15
+
16
+ def __init__(self, model, classes):
17
+ """
18
+ Initialize with loaded pipeline model
19
+ """
20
+ self.model = model
21
+ self.classes = classes
22
+ self.sentence_predictions = []
23
+ self.aggregated_results = {}
24
+
25
+ def analyze_response(self, text, question_id=None):
26
+ """
27
+ Analyze a single response by breaking into sentences
28
+ Returns list of sentence-level predictions
29
+ """
30
+ if not text:
31
+ return []
32
+
33
+ # Split into sentences
34
+ sentences = split_sentences(text)
35
+ results = []
36
+
37
+ for sentence in sentences:
38
+ if len(sentence.split()) < 2: # Skip very short sentences
39
+ continue
40
+
41
+ # Preprocess (CRITICAL: must match training)
42
+ cleaned = preprocess_text(sentence)
43
+
44
+ # Predict using pipeline (handles TF-IDF automatically)
45
+ prediction = self.model.predict([cleaned])[0]
46
+
47
+ # Get prediction confidence (probabilities)
48
+ try:
49
+ decision_scores = self.model.decision_function([cleaned])[0]
50
+ exp_scores = np.exp(decision_scores - np.max(decision_scores))
51
+ probs = exp_scores / exp_scores.sum()
52
+ confidence = probs[list(self.model.classes_).index(prediction)]
53
+ except:
54
+ confidence = None
55
+
56
+ results.append({
57
+ 'sentence': sentence,
58
+ 'prediction': prediction,
59
+ 'confidence': confidence,
60
+ 'question_id': question_id,
61
+ 'cleaned': cleaned
62
+ })
63
+
64
+ return results
65
+
66
+ def analyze_all_responses(self, responses_dict):
67
+ """
68
+ Analyze all questionnaire responses
69
+ responses_dict: {question_id: response_text}
70
+ """
71
+ all_predictions = []
72
+
73
+ for q_id, response in responses_dict.items():
74
+ if response and response.strip():
75
+ sentence_results = self.analyze_response(response, q_id)
76
+ all_predictions.extend(sentence_results)
77
+
78
+ self.sentence_predictions = all_predictions
79
+ self.aggregated_results = self._aggregate_predictions()
80
+
81
+ return self.sentence_predictions
82
+
83
+ def _aggregate_predictions(self):
84
+ """
85
+ Aggregate all sentence predictions into summary statistics
86
+ """
87
+ if not self.sentence_predictions:
88
+ return {}
89
+
90
+ # Count predictions
91
+ pred_counts = Counter([p['prediction'] for p in self.sentence_predictions])
92
+ total = len(self.sentence_predictions)
93
+
94
+ # Calculate percentages
95
+ distribution = {}
96
+ for class_name in self.classes:
97
+ count = pred_counts.get(class_name, 0)
98
+ distribution[class_name] = (count / total * 100) if total > 0 else 0
99
+
100
+ # Find primary and secondary indicators
101
+ sorted_classes = sorted(distribution.items(), key=lambda x: x[1], reverse=True)
102
+
103
+ result = {
104
+ 'total_sentences': total,
105
+ 'distribution': distribution,
106
+ 'primary_indicator': sorted_classes[0][0] if sorted_classes else None,
107
+ 'primary_percentage': sorted_classes[0][1] if sorted_classes else 0,
108
+ 'secondary_indicator': sorted_classes[1][0] if len(sorted_classes) > 1 else None,
109
+ 'secondary_percentage': sorted_classes[1][1] if len(sorted_classes) > 1 else 0,
110
+ 'raw_predictions': self.sentence_predictions
111
+ }
112
+
113
+ return result
114
+
115
+ def get_risk_level(self):
116
+ """
117
+ Determine risk level based on aggregated predictions
118
+ """
119
+ if not self.aggregated_results:
120
+ return "unknown"
121
+
122
+ dist = self.aggregated_results['distribution']
123
+ suicidal_pct = dist.get('suicidal', 0)
124
+
125
+ # Import thresholds from config
126
+ from config.settings import RISK_THRESHOLDS as TH
127
+
128
+ if suicidal_pct >= TH['suicidal_high_risk']:
129
+ return "high"
130
+ elif suicidal_pct >= TH['suicidal_moderate']:
131
+ return "moderate_high"
132
+ elif (dist.get('depression', 0) + dist.get('anxiety', 0)) >= TH['depression_anxiety_threshold']:
133
+ return "moderate"
134
+ elif dist.get('normal', 0) >= 60:
135
+ return "low"
136
+ else:
137
+ return "mild"
138
+
139
+ def get_suicidal_flagged_sentences(self):
140
+ """
141
+ Return all sentences flagged as suicidal for review
142
+ """
143
+ if not self.sentence_predictions:
144
+ return []
145
+
146
+ return [p for p in self.sentence_predictions if p['prediction'] == 'suicidal']
147
+
148
+
149
+ def create_distribution_dataframe(distribution):
150
+ """
151
+ Create a formatted DataFrame for visualization
152
+ """
153
+ df = pd.DataFrame({
154
+ 'Mental Health Indicator': list(distribution.keys()),
155
+ 'Percentage': list(distribution.values())
156
+ })
157
+ return df.sort_values('Percentage', ascending=False)
mental_health_app_real/utils/preprocessing.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils/preprocessing.py - NO NLTK DEPENDENCY
2
+ """
3
+ Text preprocessing utilities - Pure Python, no external dependencies
4
+ """
5
+
6
+ import re
7
+
8
+ def preprocess_text(text):
9
+ """
10
+ EXACT preprocessing function used during training
11
+ MUST match your training preprocessing exactly!
12
+ """
13
+ if not isinstance(text, str):
14
+ text = str(text)
15
+
16
+ # Convert to lowercase
17
+ text = text.lower()
18
+
19
+ # Remove special characters and digits (keep only letters and spaces)
20
+ text = ''.join([char for char in text if char.isalpha() or char.isspace()])
21
+
22
+ # Remove extra whitespace
23
+ text = ' '.join(text.split())
24
+
25
+ return text
26
+
27
+
28
+ def split_sentences(text):
29
+ """
30
+ Split text into sentences using regex
31
+ No NLTK required!
32
+ """
33
+ if not text or not isinstance(text, str):
34
+ return []
35
+
36
+ # Clean the text first
37
+ text = text.strip()
38
+ if not text:
39
+ return []
40
+
41
+ # Method 1: Split on sentence endings (.!?) followed by space or end of string
42
+ # This handles most cases
43
+ sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z])|(?<=[.!?])$', text)
44
+
45
+ # If that didn't work well, try simpler split
46
+ if len(sentences) <= 1 and '.' in text:
47
+ # Fallback: split on periods followed by space
48
+ sentences = re.split(r'\.\s+', text)
49
+
50
+ # Clean up sentences
51
+ cleaned_sentences = []
52
+ for s in sentences:
53
+ s = s.strip()
54
+ # Remove any trailing punctuation
55
+ s = re.sub(r'[.!?]+$', '', s)
56
+ if s and len(s.split()) >= 2: # At least 2 words
57
+ cleaned_sentences.append(s)
58
+
59
+ # If no sentences found, return the whole text as one sentence
60
+ if not cleaned_sentences and text:
61
+ # But only if it's substantial
62
+ if len(text.split()) >= 3:
63
+ cleaned_sentences = [text]
64
+
65
+ return cleaned_sentences
66
+
67
+
68
+ def clean_response(text):
69
+ """
70
+ Clean user input before processing
71
+ """
72
+ if not text:
73
+ return ""
74
+
75
+ # Remove excessive whitespace
76
+ text = ' '.join(text.split())
77
+
78
+ return text
79
+
80
+
81
+ def simple_word_tokenize(text):
82
+ """
83
+ Simple word tokenization (if needed)
84
+ """
85
+ if not text:
86
+ return []
87
+
88
+ # Remove punctuation and split
89
+ text = re.sub(r'[^\w\s]', '', text)
90
+ return text.split()
91
+
92
+
93
+ # Test function (you can remove this in production)
94
+ '''def test_tokenizer():
95
+ """Test the sentence splitter"""
96
+ test_texts = [
97
+ "I feel anxious. My heart is racing. I can't breathe.",
98
+ "I'm feeling hopeless and empty. Nothing matters anymore.",
99
+ "I want to kill myself. I have a plan. I bought pills.",
100
+ "I had a good day today. Spent time with family. Feeling hopeful.",
101
+ "This is one long sentence without punctuation so it should stay together"
102
+ ]
103
+
104
+ print("Testing sentence tokenizer:")
105
+ for text in test_texts:
106
+ sentences = split_sentences(text)
107
+ print(f"\nOriginal: {text}")
108
+ print(f"Split into {len(sentences)} sentences:")
109
+ for i, s in enumerate(sentences, 1):
110
+ print(f" {i}. {s}")
111
+
112
+ return True
113
+
114
+ # Run test if executed directly
115
+ if __name__ == "__main__":
116
+ test_tokenizer()'''
mental_health_app_real/utils/recommendations.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Recommendation engine based on risk assessment
3
+ """
4
+
5
+ from config.settings import RECOMMENDATIONS
6
+
7
+
8
+ class RecommendationEngine:
9
+ """
10
+ Provides appropriate recommendations based on analysis results
11
+ """
12
+
13
+ def __init__(self):
14
+ self.recommendations = RECOMMENDATIONS
15
+
16
+ def get_recommendations(self, primary_indicator, risk_level, suicidal_flagged=None):
17
+ """
18
+ Get tailored recommendations based on primary indicator and risk level
19
+ """
20
+ # Handle high-risk suicidal cases first
21
+ if risk_level in ['high', 'moderate_high'] and suicidal_flagged:
22
+ return self.recommendations['suicidal']
23
+
24
+ # Get recommendations based on primary indicator
25
+ if primary_indicator in self.recommendations:
26
+ return self.recommendations[primary_indicator]
27
+
28
+ # Default to normal if unknown
29
+ return self.recommendations['normal']
30
+
31
+ def get_crisis_resources(self):
32
+ """
33
+ Return crisis resources for high-risk situations
34
+ """
35
+ return {
36
+ 'title': "🚨 Crisis Resources",
37
+ 'resources': [
38
+ "**National Suicide Prevention Lifeline:** 988",
39
+ "**Crisis Text Line:** Text HOME to 741741",
40
+ "**Veterans Crisis Line:** 988 then press 1",
41
+ "**Trevor Project (LGBTQ+):** 1-866-488-7386",
42
+ "**SAMHSA National Helpline:** 1-800-662-4357"
43
+ ],
44
+ 'message': "These resources provide immediate, confidential support 24/7."
45
+ }
46
+
47
+ def format_recommendations(self, recommendations_dict):
48
+ """
49
+ Format recommendations for display
50
+ """
51
+ if not recommendations_dict:
52
+ return ""
53
+
54
+ formatted = f"### {recommendations_dict['title']}\n\n"
55
+ formatted += f"{recommendations_dict['message']}\n\n"
56
+
57
+ for i, tip in enumerate(recommendations_dict['tips'], 1):
58
+ formatted += f"{i}. {tip}\n"
59
+
60
+ return formatted
mental_health_app_real/utils/session_storage.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MindMirror AI - Session-Only Storage
3
+ No files created - data lives only in browser session
4
+ """
5
+
6
+ import streamlit as st
7
+ from datetime import datetime
8
+ import pandas as pd
9
+ from typing import Dict, List, Optional
10
+ import hashlib
11
+
12
+
13
+ class SessionTracker:
14
+ """
15
+ Session-only storage - Data cleared when browser tab closes
16
+ Perfect for privacy and mobile users
17
+ """
18
+
19
+ def __init__(self, user_id: Optional[str] = None):
20
+ """Initialize session storage - no files created!"""
21
+
22
+ # Initialize session state if not exists
23
+ if 'session_assessments' not in st.session_state:
24
+ st.session_state.session_assessments = []
25
+
26
+ if 'session_user_id' not in st.session_state:
27
+ # Create temporary session ID (only for this browsing session)
28
+ st.session_state.session_user_id = hashlib.md5(
29
+ str(datetime.now().timestamp()).encode()
30
+ ).hexdigest()[:8]
31
+
32
+ # Store user_id if provided (for returning users - but in session-only,
33
+ # returning users will get a new ID anyway)
34
+ if user_id and user_id.strip():
35
+ st.session_state.session_user_id = user_id.strip()
36
+
37
+ self.user_id = st.session_state.session_user_id
38
+ self.assessments = st.session_state.session_assessments
39
+
40
+ def add_assessment(self, results: Dict, responses: Dict) -> None:
41
+ """
42
+ Add assessment to current session
43
+ NO files created - stored in browser memory only
44
+ """
45
+ assessment = {
46
+ 'timestamp': datetime.now().isoformat(),
47
+ 'date': datetime.now().strftime('%b %d, %Y'),
48
+ 'time': datetime.now().strftime('%I:%M %p'),
49
+ 'primary': results['primary_indicator'],
50
+ 'primary_pct': round(results['primary_percentage'], 1),
51
+ 'secondary': results.get('secondary_indicator'),
52
+ 'secondary_pct': round(results.get('secondary_percentage', 0), 1),
53
+ 'anxiety': round(results['distribution'].get('anxiety', 0), 1),
54
+ 'depression': round(results['distribution'].get('depression', 0), 1),
55
+ 'suicidal': round(results['distribution'].get('suicidal', 0), 1),
56
+ 'normal': round(results['distribution'].get('normal', 0), 1)
57
+ }
58
+
59
+ # Store in session state (browser memory)
60
+ st.session_state.session_assessments.append(assessment)
61
+
62
+ def get_history_dataframe(self) -> pd.DataFrame:
63
+ """
64
+ Return assessment history as DataFrame
65
+ Data comes from browser memory, NOT from files
66
+ """
67
+ if not st.session_state.session_assessments:
68
+ return pd.DataFrame()
69
+
70
+ df = pd.DataFrame(st.session_state.session_assessments)
71
+ df['assessment'] = range(1, len(df) + 1)
72
+
73
+ # Select and rename columns for display
74
+ display_df = df[[
75
+ 'assessment', 'date', 'primary', 'primary_pct',
76
+ 'anxiety', 'depression', 'suicidal', 'normal'
77
+ ]]
78
+
79
+ return display_df
80
+
81
+ def get_progress_summary(self) -> Dict:
82
+ """
83
+ Generate progress summary from session data
84
+ """
85
+ df = self.get_history_dataframe()
86
+ if df.empty:
87
+ return {}
88
+
89
+ first = df.iloc[0]
90
+ last = df.iloc[-1]
91
+
92
+ # Calculate trends
93
+ trend = {
94
+ 'normal': round(last['normal'] - first['normal'], 1),
95
+ 'anxiety': round(last['anxiety'] - first['anxiety'], 1),
96
+ 'depression': round(last['depression'] - first['depression'], 1),
97
+ 'suicidal': round(last['suicidal'] - first['suicidal'], 1)
98
+ }
99
+
100
+ # Find most common primary indicator
101
+ most_common = df['primary'].mode()
102
+ most_common_primary = most_common[0] if not most_common.empty else None
103
+
104
+ return {
105
+ 'total_assessments': len(df),
106
+ 'first_date': first['date'],
107
+ 'last_date': last['date'],
108
+ 'trend': trend,
109
+ 'most_common_primary': most_common_primary
110
+ }
111
+
112
+ def has_history(self) -> bool:
113
+ """Check if user has any assessments in this session"""
114
+ return len(st.session_state.session_assessments) > 0
115
+
116
+ def clear_history(self):
117
+ """Clear all session data"""
118
+ st.session_state.session_assessments = []
119
+ st.session_state.session_user_id = hashlib.md5(
120
+ str(datetime.now().timestamp()).encode()
121
+ ).hexdigest()[:8]
122
+ self.user_id = st.session_state.session_user_id
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.54.0
2
+ pandas==2.3.3
3
+ numpy==2.2.6
4
+ joblib==1.5.3
5
+ plotly==6.5.2
6
+ seaborn==0.13.2
7
+ matplotlib==3.10.8
8
+ requests==2.32.5