MuhammadTechxone commited on
Commit
0efcfb5
·
verified ·
1 Parent(s): e89d705

Delete mental_app.py

Browse files
Files changed (1) hide show
  1. mental_app.py +0 -1602
mental_app.py DELETED
@@ -1,1602 +0,0 @@
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
- import pypdf
22
-
23
- from config.settings import (
24
- QUESTIONNAIRE, MENTAL_HEALTH_CLASSES,
25
- RISK_THRESHOLDS, CONTACT_INFO,
26
- NIGERIA_EMERGENCY_NUMBERS, MENTAL_HEALTH_SUPPORT,
27
- PROFESSIONAL_HELP, FAITH_COMMUNITY_SUPPORT,
28
- NIGERIAN_PROVERBS, CULTURAL_WELLNESS_TIPS, CRISIS_RESOURCES
29
- )
30
- from utils.preprocessing import clean_response, split_sentences, preprocess_text
31
- from utils.analysis import MentalHealthAnalyzer, create_distribution_dataframe
32
- from utils.recommendations import RecommendationEngine
33
- from utils.session_storage import SessionTracker
34
-
35
- # ============================================
36
- # PAGE CONFIGURATION
37
- # ============================================
38
- st.set_page_config(
39
- page_title="HeedX AI - Nigerian Mental Wellness",
40
- page_icon="NG",
41
- layout="wide",
42
- initial_sidebar_state="expanded"
43
- )
44
-
45
- # ============================================
46
- # CUSTOM CSS — professional, no emoji reliance
47
- # ============================================
48
- st.markdown("""
49
- <style>
50
- /* ── Typography & base ── */
51
- html, body, [class*="css"] {
52
- font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
53
- }
54
- .main-header {
55
- font-size: 2.2rem;
56
- font-weight: 700;
57
- color: #1a1a2e;
58
- text-align: center;
59
- letter-spacing: -0.5px;
60
- margin-bottom: 0.5rem;
61
- }
62
- .sub-header {
63
- font-size: 1.4rem;
64
- font-weight: 600;
65
- color: #2d3748;
66
- margin-bottom: 1rem;
67
- }
68
-
69
- /* ── Risk banners ── */
70
- .risk-high {
71
- background-color: #fff0f0;
72
- color: #1a1a1a;
73
- padding: 1rem;
74
- border-radius: 0.5rem;
75
- border-left: 5px solid #c0392b;
76
- }
77
- .risk-moderate {
78
- background-color: #fffbf0;
79
- color: #1a1a1a;
80
- padding: 1rem;
81
- border-radius: 0.5rem;
82
- border-left: 5px solid #e67e22;
83
- }
84
- .risk-low {
85
- background-color: #f0fff4;
86
- color: #1a1a1a;
87
- padding: 1rem;
88
- border-radius: 0.5rem;
89
- border-left: 5px solid #27ae60;
90
- }
91
-
92
- /* ── Sentence analysis box ── */
93
- .sentence-box {
94
- background-color: #f8f9fa;
95
- color: #1a1a1a;
96
- padding: 0.6rem 0.8rem;
97
- margin: 0.3rem 0;
98
- border-radius: 0.3rem;
99
- border-left: 3px solid #718096;
100
- font-size: 0.9rem;
101
- line-height: 1.5;
102
- }
103
-
104
- /* ── Disclaimer ── */
105
- .disclaimer {
106
- font-size: 0.8rem;
107
- color: #718096;
108
- font-style: italic;
109
- margin-top: 2rem;
110
- padding: 1rem;
111
- border-top: 1px solid #e2e8f0;
112
- }
113
-
114
- /* ── Buttons ── */
115
- .stButton > button {
116
- width: 100%;
117
- background-color: #008751;
118
- color: white;
119
- font-weight: 600;
120
- border-radius: 0.4rem;
121
- border: none;
122
- padding: 0.5rem 1rem;
123
- transition: all 0.3s ease;
124
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
125
- }
126
- /* Pulse effect for attention seeking */
127
- .stButton > button:first-child {
128
- animation: pulse-green 2s infinite;
129
- }
130
- @keyframes pulse-green {
131
- 0% { box-shadow: 0 0 0 0 rgba(0, 135, 81, 0.4); }
132
- 70% { box-shadow: 0 0 0 15px rgba(0, 135, 81, 0); }
133
- 100% { box-shadow: 0 0 0 0 rgba(0, 135, 81, 0); }
134
- }
135
- .stButton > button:hover {
136
- background-color: #006640;
137
- transform: translateY(-2px);
138
- box-shadow: 0 6px 12px rgba(0,0,0,0.15);
139
- }
140
-
141
- /* ── Contact link buttons ── */
142
- .contact-button {
143
- display: block;
144
- text-align: center;
145
- padding: 0.45rem 1rem;
146
- margin: 0.2rem 0;
147
- background-color: #25D366;
148
- color: white;
149
- text-decoration: none;
150
- border-radius: 0.35rem;
151
- font-weight: 600;
152
- font-size: 0.88rem;
153
- }
154
- .email-button {
155
- display: block;
156
- text-align: center;
157
- padding: 0.45rem 1rem;
158
- margin: 0.2rem 0;
159
- background-color: #c0392b;
160
- color: white;
161
- text-decoration: none;
162
- border-radius: 0.35rem;
163
- font-weight: 600;
164
- font-size: 0.88rem;
165
- }
166
-
167
- /* ── Nigerian flag accent bar ── */
168
- .nigeria-accent {
169
- background: linear-gradient(
170
- 90deg,
171
- #008751 0%, #008751 33%,
172
- #ffffff 33%, #ffffff 66%,
173
- #008751 66%, #008751 100%
174
- );
175
- height: 4px;
176
- margin: 0.8rem 0 1.4rem 0;
177
- border-radius: 2px;
178
- }
179
-
180
- /* ── Chat bubbles ── */
181
- .chat-user {
182
- background-color: #008751;
183
- color: #ffffff;
184
- padding: 0.55rem 0.9rem;
185
- border-radius: 1rem 1rem 0.2rem 1rem;
186
- margin: 0.4rem 0;
187
- font-size: 0.84rem;
188
- line-height: 1.5;
189
- text-align: right;
190
- }
191
- .chat-bot {
192
- background-color: #f1f5f9;
193
- color: #1a202c;
194
- padding: 0.55rem 0.9rem;
195
- border-radius: 1rem 1rem 1rem 0.2rem;
196
- margin: 0.4rem 0;
197
- font-size: 0.84rem;
198
- line-height: 1.6;
199
- border-left: 3px solid #008751;
200
- }
201
- .chat-system {
202
- background-color: #fef9e7;
203
- color: #7d6608;
204
- padding: 0.4rem 0.8rem;
205
- border-radius: 0.4rem;
206
- margin: 0.3rem 0;
207
- font-size: 0.8rem;
208
- border-left: 3px solid #f39c12;
209
- }
210
-
211
- /* ── Sidebar contact channel labels ── */
212
- .sidebar-channel {
213
- border-radius: 0.4rem;
214
- padding: 0.5rem 0.75rem;
215
- margin-bottom: 0.4rem;
216
- font-size: 0.83rem;
217
- font-weight: 600;
218
- }
219
-
220
- /* ── History card ── */
221
- .history-card {
222
- background: var(--secondary-background-color);
223
- padding: 0.5rem 0.8rem;
224
- border-radius: 0.4rem;
225
- margin: 0.3rem 0;
226
- border-left: 3px solid #008751;
227
- font-size: 0.88rem;
228
- }
229
- </style>
230
- """, unsafe_allow_html=True)
231
-
232
-
233
- # ============================================
234
- # MODEL LOADING
235
- # ============================================
236
- @st.cache_resource
237
- def load_model():
238
- """Load the pre-trained SVC pipeline model"""
239
- model_path = 'psychotherapy_svm_model.pkl'
240
-
241
- if not os.path.exists(model_path):
242
- st.error("Model file not found: " + model_path)
243
- st.info("Please ensure 'psychotherapy_svm_model.pkl' is in the app directory.")
244
- return None
245
-
246
- try:
247
- model = joblib.load(model_path)
248
- with st.sidebar.expander("Model Info", expanded=False):
249
- st.write("**Model type:** " + type(model).__name__)
250
- st.write("**Classes:** " + ", ".join(model.classes_))
251
- return model
252
- except Exception as e:
253
- st.error("Error loading model: " + str(e))
254
- return None
255
-
256
-
257
- # ============================================
258
- # SESSION STATE INITIALIZATION
259
- # ============================================
260
- def init_session_state():
261
- """Initialize all session state variables"""
262
- defaults = {
263
- 'page': 'home',
264
- 'responses': {},
265
- 'analysis_complete': False,
266
- 'analyzer': None,
267
- 'results': None,
268
- 'tracker': None,
269
- 'chat_messages': [],
270
- 'groq_api_key': '',
271
- 'uploader_id': 0,
272
- }
273
- for key, value in defaults.items():
274
- if key not in st.session_state:
275
- st.session_state[key] = value
276
-
277
-
278
- # ============================================
279
- # GROQ API CALL
280
- # ============================================
281
- def call_groq(messages: list, api_key: str, temperature: float = 0.7) -> str:
282
- """
283
- Call Groq's Llama-3.3-70b-versatile model.
284
- Returns the assistant reply text, or an error string.
285
- """
286
- url = "https://api.groq.com/openai/v1/chat/completions"
287
- headers = {
288
- "Authorization": "Bearer " + api_key,
289
- "Content-Type": "application/json",
290
- }
291
- payload = {
292
- "model": "llama-3.3-70b-versatile",
293
- "messages": messages,
294
- "temperature": temperature,
295
- "max_tokens": 600,
296
- }
297
- try:
298
- resp = requests.post(url, headers=headers, json=payload, timeout=30)
299
- resp.raise_for_status()
300
- return resp.json()["choices"][0]["message"]["content"].strip()
301
- except requests.exceptions.Timeout:
302
- return "The response took too long. Please try again."
303
- except requests.exceptions.HTTPError as e:
304
- code = e.response.status_code if e.response else "?"
305
- if code == 401:
306
- return "Invalid Groq API key. Please check your key in the sidebar."
307
- if code == 429:
308
- return "Rate limit reached. Please wait a moment and try again."
309
- return "API error (" + str(code) + "). Please try again."
310
- except Exception as e:
311
- return "Could not reach the AI service. Please check your connection."
312
-
313
-
314
- # ============================================
315
- # SESSION CONTEXT BUILDER
316
- # ============================================
317
- def build_session_context() -> str:
318
- """
319
- Build a structured context string from the user's current session:
320
- - SVC model assessment results
321
- - Risk level
322
- - Distribution percentages
323
- - Progress tracking trends
324
- Injected into the chatbot system prompt so it speaks from knowledge,
325
- not guesswork.
326
- """
327
- parts = []
328
-
329
- # Assessment results from the SVC model
330
- results = st.session_state.get('results')
331
- analyzer = st.session_state.get('analyzer')
332
-
333
- if results and analyzer:
334
- parts.append("CURRENT SESSION ASSESSMENT (from SVC psychotherapy model):")
335
- parts.append(
336
- " Primary indicator : " + results['primary_indicator'].upper() +
337
- " (" + f"{results['primary_percentage']:.1f}" + "%)"
338
- )
339
- if results.get('secondary_indicator'):
340
- parts.append(
341
- " Secondary indicator: " + results['secondary_indicator'].upper() +
342
- " (" + f"{results['secondary_percentage']:.1f}" + "%)"
343
- )
344
- parts.append(" Full distribution:")
345
- for cls, pct in results['distribution'].items():
346
- parts.append(" - " + cls + ": " + f"{pct:.1f}" + "%")
347
-
348
- risk_level = analyzer.get_risk_level()
349
- parts.append(" Risk level: " + risk_level.upper())
350
-
351
- flagged = analyzer.get_suicidal_flagged_sentences()
352
- if flagged:
353
- parts.append(
354
- " Note: " + str(len(flagged)) +
355
- " sentence(s) flagged for suicidal ideation indicators."
356
- )
357
- else:
358
- parts.append("ASSESSMENT STATUS: The user has not yet completed a check-in this session.")
359
-
360
- # Progress tracking trends
361
- tracker = st.session_state.get('tracker')
362
- if tracker:
363
- summary = tracker.get_progress_summary()
364
- if summary and summary.get('total_assessments', 0) > 0:
365
- parts.append("\nSESSION PROGRESS TRACKING:")
366
- parts.append(" Total check-ins this session: " + str(summary['total_assessments']))
367
- parts.append(" Most common primary indicator: " + str(summary.get('most_common_primary', 'N/A')))
368
- trend = summary.get('trend', {})
369
- if trend:
370
- parts.append(" Trends since first check-in:")
371
- for cls, delta in trend.items():
372
- direction = "up" if delta > 0 else "down"
373
- parts.append(
374
- " - " + cls + ": " + direction + " " + f"{abs(delta):.1f}" + "%"
375
- )
376
-
377
- return "\n".join(parts) if parts else "No session data available yet."
378
-
379
-
380
- # ============================================
381
- # SYSTEM PROMPT BUILDER
382
- # ============================================
383
- def build_system_prompt() -> str:
384
- """
385
- Construct the full system prompt for the Groq model.
386
- Includes the HeedX persona, Nigerian cultural context,
387
- professional boundaries, and the user's live session data.
388
- """
389
- session_context = build_session_context()
390
- has_assessment = st.session_state.get('results') is not None
391
-
392
- 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.
393
-
394
- YOUR ROLE:
395
- - Provide supportive, evidence-informed mental wellness conversations
396
- - Give specific, actionable recommendations and coping strategies
397
- - Interpret and explain the user's SVC model assessment results in plain language
398
- - Reference the user's progress trends when relevant
399
- - Maintain professional, warm, and non-judgmental tone throughout
400
- - Be culturally sensitive to Nigerian values, family structures, and community dynamics
401
-
402
- CLINICAL BOUNDARIES:
403
- - You are not a licensed therapist and do not diagnose
404
- - For high-risk or suicidal indicators, always direct to Nigerian crisis lines: 112 (emergency), 08062106493 (MANI), 08099769974 (She Writes Woman)
405
- - Encourage professional consultation when warranted
406
- - Never dismiss or minimise distress but dont be too confident
407
-
408
-
409
- TONE AND STYLE:
410
- - Professional but warm — like a knowledgeable friend with clinical training
411
- - Do not use emojis
412
- - Write in clear, plain English that is accessible to Nigerian users
413
- - Responses should be conversational but substantive — typically 3 to 6 sentences
414
- - Vary your responses; do not repeat the same phrases
415
-
416
- NIGERIAN CULTURAL CONTEXT:
417
- - Acknowledge the role of faith, family, and community in Nigerian mental health
418
- - Be aware of stigma around mental health in Nigerian society
419
- - Reference local support systems where appropriate (Federal Neuro Hospitals: Yaba, Kaduna, Aro-Abeokuta)
420
-
421
- """
422
-
423
- if has_assessment:
424
- prompt += "USER SESSION DATA (from the HeedX SVC psychotherapy model — use this to personalise your responses):\n"
425
- prompt += session_context
426
- 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."
427
- else:
428
- prompt += "USER SESSION DATA:\n"
429
- prompt += session_context
430
- 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."
431
-
432
- return prompt
433
-
434
-
435
- # ============================================
436
- # GROQ CHATBOT RESPONSE
437
- # ============================================
438
- def get_ai_response(user_message: str, api_key: str) -> str:
439
- """
440
- Build the full message history and call Groq.
441
- Injects a fresh system prompt on every call so the
442
- context always reflects the latest session state.
443
- """
444
- system_prompt = build_system_prompt()
445
-
446
- # Crisis shortcut — handled locally before hitting API
447
- crisis_keywords = [
448
- 'kill myself', 'end my life', 'suicide', 'want to die',
449
- 'no reason to live', 'hang myself', 'overdose',
450
- 'hurt myself', 'self harm', 'take my life',
451
- 'want to kpai', 'end it all', 'better off dead'
452
- ]
453
- if any(kw in user_message.lower() for kw in crisis_keywords):
454
- return (
455
- "What you have just shared is serious and I am glad you are talking. "
456
- "Please reach out for immediate support right now:\n\n"
457
- "- Emergency: Call 112\n"
458
- "- Mentally Aware Nigeria Initiative (MANI): 08062106493\n"
459
- "- She Writes Woman: 08099769974\n"
460
- "- Visit the nearest Federal Neuropsychiatric Hospital\n\n"
461
- "You do not have to face this alone. Would you like to talk about what is happening?"
462
- )
463
-
464
- # Build message list: system + conversation history + new user message
465
- messages = [{"role": "system", "content": system_prompt}]
466
-
467
- # Include up to last 10 exchanges for context window efficiency
468
- for msg in st.session_state.chat_messages[-10:]:
469
- messages.append({
470
- "role": "user" if msg['role'] == 'user' else "assistant",
471
- "content": msg['content']
472
- })
473
-
474
- messages.append({"role": "user", "content": user_message})
475
-
476
- return call_groq(messages, api_key)
477
-
478
-
479
- # ============================================
480
- # CHAT PAGE (full page, mobile-friendly)
481
- # ============================================
482
- def render_chat_page():
483
- """
484
- Full-page Groq Llama 3 mental wellness chatbot.
485
- Context-aware of SVC assessment results, risk level and session progress.
486
- API key is loaded from .streamlit/secrets.toml — users never need to enter one.
487
- """
488
- st.markdown("<h2 class='sub-header'>Wellness Chat</h2>", unsafe_allow_html=True)
489
- st.markdown(
490
- "<p style='color:#4a5568;margin-top:-0.5rem;margin-bottom:1rem;'>"
491
- "Speak with the HeedX AI wellness assistant. Responses are informed by "
492
- "your assessment results and session progress.</p>",
493
- unsafe_allow_html=True
494
- )
495
-
496
- # Resolve API key — secrets.toml takes priority, no user input needed
497
- if not st.session_state.groq_api_key:
498
- try:
499
- st.session_state.groq_api_key = st.secrets["GROQ_API_KEY"]
500
- except (KeyError, FileNotFoundError):
501
- st.session_state.groq_api_key = ""
502
-
503
- if not st.session_state.groq_api_key:
504
- st.error(
505
- "The chat assistant is not configured. "
506
- "Please add GROQ_API_KEY to .streamlit/secrets.toml and restart the app."
507
- )
508
- if st.button("Back to Home", use_container_width=True):
509
- st.session_state.page = 'home'
510
- st.rerun()
511
- return
512
-
513
- # Context status banner
514
- has_assessment = st.session_state.get('results') is not None
515
- tracker = st.session_state.get('tracker')
516
- has_progress = tracker is not None and tracker.has_history()
517
-
518
- if has_assessment:
519
- results = st.session_state['results']
520
- primary = results['primary_indicator'].upper()
521
- pct = f"{results['primary_percentage']:.1f}"
522
- risk = st.session_state['analyzer'].get_risk_level().upper()
523
- checkins = len(tracker.assessments) if has_progress else 0
524
- st.markdown(
525
- "<div style='background:#f0faf4;border-left:4px solid #008751;"
526
- "border-radius:0 0.5rem 0.5rem 0;padding:0.75rem 1rem;"
527
- "margin-bottom:1rem;font-size:0.88rem;color:#1a1a1a;'>"
528
- "<strong>Active context from your assessment</strong><br>"
529
- "Primary indicator: <strong>" + primary + "</strong> (" + pct + "%)&nbsp;&nbsp;|&nbsp;&nbsp;"
530
- "Risk level: <strong>" + risk + "</strong>&nbsp;&nbsp;|&nbsp;&nbsp;"
531
- "Check-ins: <strong>" + str(checkins) + "</strong>"
532
- "</div>",
533
- unsafe_allow_html=True
534
- )
535
- else:
536
- st.markdown(
537
- "<div style='background:#fef9e7;border-left:4px solid #e67e22;"
538
- "border-radius:0 0.5rem 0.5rem 0;padding:0.75rem 1rem;"
539
- "margin-bottom:1rem;font-size:0.88rem;color:#7d4e00;'>"
540
- "No assessment completed yet. The assistant will encourage you to complete "
541
- "a check-in so it can provide personalised responses based on your results."
542
- "</div>",
543
- unsafe_allow_html=True
544
- )
545
-
546
- st.markdown("---")
547
-
548
- # Chat history
549
- if not st.session_state.chat_messages:
550
- st.markdown(
551
- "<div class='chat-bot' style='max-width:640px;'>"
552
- "Good day. I am the HeedX wellness assistant, powered by Llama 3. "
553
- "I have access to your session data and assessment results to provide "
554
- "personalised mental wellness support. How are you feeling today?"
555
- "</div>",
556
- unsafe_allow_html=True
557
- )
558
- else:
559
- for msg in st.session_state.chat_messages:
560
- if msg['role'] == 'user':
561
- st.markdown(
562
- "<div style='display:flex;justify-content:flex-end;margin:0.4rem 0;'>"
563
- "<div class='chat-user' style='max-width:80%;'>"
564
- + html_lib.escape(msg['content']) +
565
- "</div></div>",
566
- unsafe_allow_html=True
567
- )
568
- else:
569
- content = msg['content'].replace('\n', '<br>')
570
- st.markdown(
571
- "<div style='display:flex;justify-content:flex-start;margin:0.4rem 0;'>"
572
- "<div class='chat-bot' style='max-width:85%;'>"
573
- + content +
574
- "</div></div>",
575
- unsafe_allow_html=True
576
- )
577
-
578
- st.markdown("---")
579
-
580
- # Input form
581
- with st.form("chat_page_form", clear_on_submit=True):
582
- user_input = st.text_area(
583
- "Your message",
584
- placeholder="Share how you are feeling, ask a question, or discuss your results...",
585
- height=110,
586
- label_visibility="collapsed",
587
- key="chat_page_input"
588
- )
589
- col_send, col_clear, col_back = st.columns([3, 1, 1])
590
- with col_send:
591
- send = st.form_submit_button("Send", use_container_width=True)
592
- with col_clear:
593
- clear = st.form_submit_button("Clear chat", use_container_width=True)
594
- with col_back:
595
- back = st.form_submit_button("Back", use_container_width=True)
596
-
597
- if send and user_input and user_input.strip():
598
- user_text = user_input.strip()
599
- st.session_state.chat_messages.append({'role': 'user', 'content': user_text})
600
- with st.spinner("HeedX is responding..."):
601
- reply = get_ai_response(user_text, st.session_state.groq_api_key)
602
- st.session_state.chat_messages.append({'role': 'bot', 'content': reply})
603
- st.rerun()
604
-
605
- if clear:
606
- st.session_state.chat_messages = []
607
- st.rerun()
608
-
609
- if back:
610
- st.session_state.page = 'home'
611
- st.rerun()
612
-
613
- st.caption(
614
- "Powered by Llama 3.3-70b via Groq. Responses are supportive in nature "
615
- "and do not constitute professional medical advice."
616
- )
617
-
618
-
619
- # ============================================
620
- # SIDEBAR CONTACT CHANNELS
621
- # ============================================
622
- def render_sidebar_contacts():
623
- """Quick-access contact buttons in the sidebar"""
624
-
625
- st.sidebar.markdown("---")
626
- st.sidebar.markdown("### Contact & Support")
627
-
628
- # Counselling & Guidance
629
- st.sidebar.markdown(
630
- "<div class='sidebar-channel' style='background:#f0faf4;border-left:3px solid #008751;'>"
631
- "<span style='color:#008751;'>Counselling and Guidance</span>"
632
- "</div>",
633
- unsafe_allow_html=True
634
- )
635
-
636
- whatsapp_number = CONTACT_INFO['whatsapp'].lstrip('0')
637
- whatsapp_link = "https://wa.me/234" + whatsapp_number
638
- call_number = CONTACT_INFO.get('phone', CONTACT_INFO['whatsapp'])
639
-
640
- st.sidebar.markdown(
641
- "<a href='" + whatsapp_link + "' target='_blank' class='contact-button'>"
642
- "WhatsApp Counsellor</a>",
643
- unsafe_allow_html=True
644
- )
645
- st.sidebar.markdown(
646
- "<a href='tel:" + call_number + "' class='contact-button' "
647
- "style='background-color:#008751;margin-bottom:0.6rem;'>"
648
- "Call " + call_number + "</a>",
649
- unsafe_allow_html=True
650
- )
651
-
652
- # Platform Support
653
- st.sidebar.markdown(
654
- "<div class='sidebar-channel' style='background:#f0f4ff;border-left:3px solid #2980b9;'>"
655
- "<span style='color:#1565C0;'>Platform Support</span>"
656
- "</div>",
657
- unsafe_allow_html=True
658
- )
659
-
660
- support_email = CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
661
- st.sidebar.markdown(
662
- "<a href='mailto:" + support_email + "' target='_blank' class='email-button'>"
663
- "Email Platform Support</a>",
664
- unsafe_allow_html=True
665
- )
666
-
667
- platform_wa = CONTACT_INFO.get('platform_whatsapp', '')
668
- if platform_wa:
669
- pw_link = "https://wa.me/234" + platform_wa.lstrip('0')
670
- st.sidebar.markdown(
671
- "<a href='" + pw_link + "' target='_blank' class='contact-button'>"
672
- "Platform WhatsApp</a>",
673
- unsafe_allow_html=True
674
- )
675
-
676
-
677
- # ============================================
678
- # NIGERIAN SUPPORT RESOURCES
679
- # ============================================
680
- def render_nigerian_support():
681
- """Display comprehensive Nigerian support resources"""
682
-
683
- with st.expander("Nigerian Support Resources", expanded=False):
684
- st.markdown("### " + NIGERIA_EMERGENCY_NUMBERS['national']['title'])
685
- for resource in NIGERIA_EMERGENCY_NUMBERS['national']['resources']:
686
- st.markdown("- " + resource)
687
-
688
- st.markdown("### " + NIGERIA_EMERGENCY_NUMBERS['state_emergency']['title'])
689
- for resource in NIGERIA_EMERGENCY_NUMBERS['state_emergency']['resources']:
690
- st.markdown("- " + resource)
691
-
692
- st.markdown("---")
693
- st.markdown("### " + MENTAL_HEALTH_SUPPORT['title'])
694
- for resource in MENTAL_HEALTH_SUPPORT['resources']:
695
- st.markdown("- " + resource)
696
-
697
- st.markdown("---")
698
- st.markdown("### " + PROFESSIONAL_HELP['title'])
699
- for resource in PROFESSIONAL_HELP['resources']:
700
- st.markdown("- " + resource)
701
-
702
- st.markdown("---")
703
- st.markdown("### " + FAITH_COMMUNITY_SUPPORT['title'])
704
- for resource in FAITH_COMMUNITY_SUPPORT['resources']:
705
- st.markdown("- " + resource)
706
-
707
- st.markdown("---")
708
- st.markdown("### Nigerian Wisdom for Mental Wellness")
709
- for proverb in NIGERIAN_PROVERBS[:4]:
710
- st.markdown("*\"" + proverb + "\"*")
711
-
712
- st.markdown("---")
713
- st.markdown("**Remember:** Help is available. You are not alone.")
714
-
715
-
716
- # ============================================
717
- # FEEDBACK / CONTACT SECTION (main page)
718
- # ============================================
719
- def render_feedback_section():
720
- """Two clearly separated contact channels on the main page"""
721
-
722
- st.markdown("### Contact and Support")
723
-
724
- # Counselling & Guidance
725
- st.markdown("""
726
- <div style="background:#f0faf4;border-left:4px solid #008751;
727
- border-radius:0 0.5rem 0.5rem 0;padding:1rem 1.2rem;margin-bottom:1rem;">
728
- <p style="margin:0 0 0.3rem 0;font-weight:700;color:#008751;font-size:0.95rem;">
729
- Mental Wellness Counselling and Guidance
730
- </p>
731
- <p style="margin:0;font-size:0.88rem;color:#2d3748;">
732
- Reach out if you need to talk, seek emotional guidance, or want
733
- personalised wellness advice from our counsellor.
734
- </p>
735
- </div>
736
- """, unsafe_allow_html=True)
737
-
738
- col1, col2 = st.columns(2)
739
- with col1:
740
- st.markdown("**WhatsApp — Counselling**")
741
- whatsapp_number = CONTACT_INFO['whatsapp'].lstrip('0')
742
- whatsapp_link = "https://wa.me/234" + whatsapp_number
743
- st.markdown(
744
- "<a href='" + whatsapp_link + "' target='_blank' class='contact-button'>"
745
- "Chat with Counsellor</a>",
746
- unsafe_allow_html=True
747
- )
748
- st.caption("Monday to Friday, 9 am to 5 pm")
749
-
750
- with col2:
751
- st.markdown("**Call or SMS**")
752
- call_number = CONTACT_INFO.get('phone', CONTACT_INFO['whatsapp'])
753
- st.markdown(
754
- "<a href='tel:" + call_number + "' class='contact-button' "
755
- "style='background-color:#008751;'>"
756
- "Call " + call_number + "</a>",
757
- unsafe_allow_html=True
758
- )
759
- st.caption("Voice calls welcome during hours above")
760
-
761
- st.markdown("<br>", unsafe_allow_html=True)
762
-
763
- # Platform Support
764
- st.markdown("""
765
- <div style="background:#f0f4ff;border-left:4px solid #2980b9;
766
- border-radius:0 0.5rem 0.5rem 0;padding:1rem 1.2rem;margin-bottom:1rem;">
767
- <p style="margin:0 0 0.3rem 0;font-weight:700;color:#1565C0;font-size:0.95rem;">
768
- Platform Support
769
- </p>
770
- <p style="margin:0;font-size:0.88rem;color:#2d3748;">
771
- Bug reports, feature requests, account questions, or any technical
772
- issue with the HeedX AI platform.
773
- </p>
774
- </div>
775
- """, unsafe_allow_html=True)
776
-
777
- col3, col4 = st.columns(2)
778
- with col3:
779
- st.markdown("**Support Email**")
780
- support_email = CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
781
- st.markdown(
782
- "<a href='mailto:" + support_email + "' target='_blank' class='email-button'>"
783
- "Email Platform Support</a>",
784
- unsafe_allow_html=True
785
- )
786
- st.caption("Response within 24 to 48 hours")
787
-
788
- with col4:
789
- st.markdown("**Platform WhatsApp**")
790
- platform_wa = CONTACT_INFO.get('platform_whatsapp', CONTACT_INFO.get('whatsapp_support', ''))
791
- if platform_wa:
792
- pw_link = "https://wa.me/234" + platform_wa.lstrip('0')
793
- st.markdown(
794
- "<a href='" + pw_link + "' target='_blank' class='contact-button'>"
795
- "Platform WhatsApp</a>",
796
- unsafe_allow_html=True
797
- )
798
- else:
799
- st.info("Platform WhatsApp — coming soon")
800
-
801
- with st.expander("Send a Message", expanded=False):
802
- contact_type = st.radio(
803
- "What is this about?",
804
- ["Counselling and Guidance", "Platform Support, Bug or Feature Request"],
805
- horizontal=True
806
- )
807
- feedback_type = st.selectbox(
808
- "Category",
809
- ["General Enquiry", "Suggestion", "Bug Report",
810
- "Feature Request", "Support Question", "Other"]
811
- )
812
- feedback_text = st.text_area(
813
- "Your Message",
814
- placeholder="Please describe your question or feedback...",
815
- height=100
816
- )
817
- if st.button("Send Message"):
818
- if feedback_text.strip():
819
- subject = "HeedX AI - " + contact_type.split()[0] + ": " + feedback_type
820
- body = "Category: " + feedback_type + "\nChannel: " + contact_type + "\n\nMessage:\n" + feedback_text
821
- recipient = CONTACT_INFO['email'] if "Counselling" in contact_type else CONTACT_INFO.get('support_email', CONTACT_INFO['email'])
822
- mailto_link = "mailto:" + recipient + "?subject=" + urllib.parse.quote(subject) + "&body=" + urllib.parse.quote(body)
823
- st.markdown(
824
- "<a href='" + mailto_link + "' target='_blank'>Click to open email client</a>",
825
- unsafe_allow_html=True
826
- )
827
- st.success("Email client opened. Please send the pre-filled email.")
828
- else:
829
- st.warning("Please enter a message before sending.")
830
-
831
-
832
- # ============================================
833
- # PROGRESS TRACKING
834
- # ============================================
835
- def render_progress_tracking():
836
- """Render user progress tracking visualizations"""
837
-
838
- st.markdown("""
839
- <div style="margin:2rem 0 1rem 0;text-align:center;">
840
- <h3 style="color:#008751;font-weight:600;">Your Progress This Session</h3>
841
- <p style="color:#4a5568;margin-top:0.4rem;">
842
- Track your mental wellness journey and notice patterns over time.
843
- </p>
844
- </div>
845
- """, unsafe_allow_html=True)
846
-
847
- if not st.session_state.get('tracker'):
848
- st.info("Complete a check-in to start tracking your progress this session.")
849
- return
850
-
851
- tracker = st.session_state.tracker
852
- df_history = tracker.get_history_dataframe()
853
-
854
- if df_history.empty:
855
- st.info("No assessments yet. Complete a check-in to see your progress.")
856
- return
857
-
858
- summary = tracker.get_progress_summary()
859
-
860
- # Summary banner
861
- st.markdown(
862
- "<div style='background:linear-gradient(135deg,#e6fffa 0%,#c6f6d5 100%);"
863
- "border-radius:1rem;padding:1.2rem;text-align:center;"
864
- "margin-bottom:1.5rem;border:1px solid #9ae6b4;'>"
865
- "<span style='font-size:1rem;color:#1a202c;'>You have completed </span>"
866
- "<span style='font-size:2rem;font-weight:700;color:#065f46;margin:0 0.5rem;'>"
867
- + str(len(df_history)) +
868
- "</span>"
869
- "<span style='font-size:1rem;color:#1a202c;'>"
870
- + ("check-ins" if len(df_history) > 1 else "check-in") +
871
- " in this session.</span>"
872
- "</div>",
873
- unsafe_allow_html=True
874
- )
875
-
876
- # Summary cards
877
- col1, col2, col3, col4 = st.columns(4)
878
-
879
- def metric_card(value, label):
880
- return (
881
- "<div style='background:white;border-radius:0.75rem;padding:1rem;"
882
- "text-align:center;box-shadow:0 1px 6px rgba(0,0,0,0.06);"
883
- "border:1px solid #e2e8f0;'>"
884
- "<div style='font-size:1.4rem;font-weight:700;color:#008751;'>" + str(value) + "</div>"
885
- "<div style='color:#4a5568;font-size:0.78rem;margin-top:0.2rem;'>" + label + "</div>"
886
- "</div>"
887
- )
888
-
889
- with col1:
890
- st.markdown(metric_card(summary['total_assessments'], "Total Check-ins"), unsafe_allow_html=True)
891
- with col2:
892
- st.markdown(metric_card(summary['first_date'], "First Check-in"), unsafe_allow_html=True)
893
- with col3:
894
- st.markdown(metric_card(summary['last_date'], "Most Recent"), unsafe_allow_html=True)
895
- with col4:
896
- most_common = summary.get('most_common_primary', 'N/A')
897
- st.markdown(metric_card(most_common.title() if most_common else "N/A", "Most Common"), unsafe_allow_html=True)
898
-
899
- # Trend chart
900
- st.markdown("#### Indicator Trends")
901
-
902
- fig = go.Figure()
903
- traces = [
904
- ("Anxiety", "#e67e22", "anxiety"),
905
- ("Depression", "#2980b9", "depression"),
906
- ("Suicidal", "#c0392b", "suicidal"),
907
- ("Normal", "#27ae60", "normal"),
908
- ]
909
- for name, color, col in traces:
910
- if col in df_history.columns:
911
- fig.add_trace(go.Scatter(
912
- x=df_history['assessment'],
913
- y=df_history[col],
914
- mode='lines+markers',
915
- name=name,
916
- line=dict(color=color, width=2.5),
917
- marker=dict(size=8),
918
- ))
919
-
920
- fig.update_layout(
921
- xaxis=dict(title="Check-in Number"),
922
- yaxis=dict(title="Percentage (%)", range=[0, 100]),
923
- hovermode='x unified',
924
- height=420,
925
- plot_bgcolor='white',
926
- paper_bgcolor='white',
927
- margin=dict(t=20, b=40),
928
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
929
- )
930
- fig.update_xaxes(showgrid=True, gridcolor='#f0f0f0')
931
- fig.update_yaxes(showgrid=True, gridcolor='#f0f0f0')
932
- st.plotly_chart(fig, use_container_width=True)
933
-
934
- # Trend insights
935
- if summary.get('trend'):
936
- trend = summary['trend']
937
- insights = []
938
-
939
- if trend.get('normal', 0) > 5:
940
- insights.append("Positive wellbeing improvement of +" + str(round(trend['normal'])) + "% since your first check-in.")
941
- if trend.get('anxiety', 0) < 0:
942
- insights.append("Anxiety indicators have reduced by " + str(abs(round(trend['anxiety']))) + "%.")
943
- if trend.get('depression', 0) < 0:
944
- insights.append("Depression indicators are improving by " + str(abs(round(trend['depression']))) + "%.")
945
- if trend.get('suicidal', 0) > 2:
946
- insights.append("An increase in difficult thoughts has been noted. Please consider reaching out for support.")
947
- elif trend.get('suicidal', 0) > 0:
948
- insights.append("A slight increase in difficult thought indicators. Continued support is recommended.")
949
- if not insights:
950
- insights.append("Your indicators are stable across this session.")
951
-
952
- st.markdown("**Session Insights**")
953
- for insight in insights[:4]:
954
- st.markdown("- " + insight)
955
-
956
- with st.expander("View All Check-Ins"):
957
- st.dataframe(df_history, use_container_width=True)
958
-
959
- st.caption("Your data exists only within this browser session and is cleared when you close the tab.")
960
-
961
-
962
- # ============================================
963
- # HOME PAGE
964
- # ============================================
965
- def render_home_page():
966
- """Render the home page"""
967
-
968
- st.markdown("<h1 class='main-header'>HeedX AI</h1>", unsafe_allow_html=True)
969
- st.markdown(
970
- "<p style='text-align:center;color:#008751;font-size:1.05rem;'>"
971
- "Your Nigerian Mental Wellness Companion</p>",
972
- unsafe_allow_html=True
973
- )
974
- st.markdown(
975
- "<p style='text-align:center;color:#4a5568;font-size:0.9rem;'>"
976
- "Understand. Respond. Support.</p>",
977
- unsafe_allow_html=True
978
- )
979
- st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
980
-
981
- col1, col2, col3 = st.columns([1, 2, 1])
982
-
983
- with col2:
984
- st.markdown("""
985
- <div style="background:white;border-radius:0.75rem;padding:1.5rem;margin:1rem 0;
986
- text-align:center;box-shadow:0 2px 10px rgba(0,0,0,0.05);
987
- border:1px solid #e2e8f0;">
988
- <p style="font-size:1.1rem;color:#2d3748;margin:0;">
989
- A professional space to reflect, understand, and nurture your mental wellbeing.
990
- </p>
991
- <p style="font-size:0.88rem;color:#008751;margin-top:0.6rem;margin-bottom:0;">
992
- Nigerian resources &nbsp;|&nbsp; Culturally adapted &nbsp;|&nbsp; Free and confidential
993
- </p>
994
- </div>
995
- """, unsafe_allow_html=True)
996
-
997
- st.markdown("""
998
- ### How It Works
999
-
1000
- 1. **Complete a check-in** by sharing a detailed narration of your situation
1001
- 2. **The AI model analyzes** your responses at sentence level
1002
- 3. **Receive insights**, risk assessment, and tailored recommendations
1003
- 4. **Chat with HeedX**, our AI wellness assistant, for personalised guidance
1004
- 5. **Track your journey** and monitor changes across check-ins
1005
-
1006
- All data remains private within your current browser session.
1007
- """)
1008
-
1009
- render_nigerian_support()
1010
-
1011
- # High-impact call to action section
1012
- st.markdown("<br>", unsafe_allow_html=True)
1013
- cta_col1, cta_col2 = st.columns(2)
1014
-
1015
- with cta_col1:
1016
- if st.button("Start Your Check-In", use_container_width=True):
1017
- if not st.session_state.tracker:
1018
- st.session_state.tracker = SessionTracker()
1019
- st.session_state.page = 'questionnaire'
1020
- st.rerun()
1021
- st.caption("Detailed sentence-level analysis")
1022
-
1023
- with cta_col2:
1024
- if st.button("Chat with HeedX", use_container_width=True):
1025
- st.session_state.page = 'chat'
1026
- st.rerun()
1027
- st.caption("Immediate conversational support")
1028
-
1029
- if st.session_state.tracker:
1030
- st.markdown("---")
1031
- st.info(
1032
- "Check-ins completed this session: " + str(len(st.session_state.tracker.assessments))
1033
- )
1034
-
1035
- if st.session_state.tracker and st.session_state.tracker.has_history():
1036
- st.markdown("### Recent Session Activity")
1037
- history_df = st.session_state.tracker.get_history_dataframe()
1038
- if not history_df.empty:
1039
- for _, row in history_df.tail(3).iterrows():
1040
- st.markdown(
1041
- "<div class='history-card'>"
1042
- + str(row['date']) +
1043
- " &nbsp;&mdash;&nbsp; Primary: " + str(row['primary']).upper() +
1044
- " &nbsp;&mdash;&nbsp; " + str(round(row['primary_pct'])) + "%"
1045
- "</div>",
1046
- unsafe_allow_html=True
1047
- )
1048
- if st.button("View Full Progress", use_container_width=True):
1049
- st.session_state.page = 'progress'
1050
- st.rerun()
1051
-
1052
- st.markdown("""
1053
- <div class='disclaimer'>
1054
- <p>This is a supportive tool, not a medical diagnosis.</p>
1055
- <p>If you are in crisis, call <strong>112</strong> (National Emergency)
1056
- or <strong>08062106493</strong> (Mentally Aware Nigeria Initiative) immediately.</p>
1057
- <p>Your life is valuable. Help is available.</p>
1058
- </div>
1059
- """, unsafe_allow_html=True)
1060
-
1061
-
1062
- # ============================================
1063
- # QUESTIONNAIRE PAGE
1064
- # ============================================
1065
- def render_questionnaire_page():
1066
- """Render the questionnaire page"""
1067
-
1068
- if not st.session_state.tracker:
1069
- st.session_state.tracker = SessionTracker()
1070
-
1071
- # Define callback to clear narration safely before widgets are redrawn
1072
- def handle_clear_narration():
1073
- for q in QUESTIONNAIRE:
1074
- st.session_state["input_" + q['id']] = ""
1075
- st.session_state.pop("last_uploaded_file_id", None)
1076
- st.session_state.responses = {}
1077
- st.session_state.uploader_id += 1
1078
-
1079
- st.markdown("<h2 class='sub-header'>Wellness Narration</h2>",
1080
- unsafe_allow_html=True)
1081
-
1082
- if len(st.session_state.tracker.assessments) > 0:
1083
- st.info("Check-ins completed this session: " + str(len(st.session_state.tracker.assessments)))
1084
-
1085
- st.markdown(
1086
- "Whether you are a user reflecting on your journey, or a professional/researcher analyzing a case, "
1087
- "The more detail you provide, the more accurate the analysis will be."
1088
- )
1089
-
1090
- if 'responses' not in st.session_state:
1091
- st.session_state.responses = {}
1092
-
1093
- # Optional File Upload for Researchers/Professionals
1094
- uploaded_file = st.file_uploader(
1095
- "Researchers/Psychologists: Upload a case note or narration (.pdf, .txt)",
1096
- type=['pdf', 'txt'],
1097
- key=f"file_uploader_{st.session_state.get('uploader_id', 0)}"
1098
- )
1099
-
1100
- if uploaded_file is not None:
1101
- # Track unique file to prevent infinite reruns and allow post-upload editing
1102
- file_id = f"{uploaded_file.name}_{uploaded_file.size}"
1103
- if st.session_state.get("last_uploaded_file_id") != file_id:
1104
- try:
1105
- if uploaded_file.type == "application/pdf":
1106
- reader = pypdf.PdfReader(uploaded_file)
1107
- pages_text = []
1108
- for page in reader.pages:
1109
- text = page.extract_text()
1110
- if text:
1111
- pages_text.append(text)
1112
- content = "\n".join(pages_text)
1113
- else:
1114
- content = uploaded_file.read().decode("utf-8")
1115
-
1116
- st.session_state["input_narration"] = content.strip()
1117
- st.session_state["last_uploaded_file_id"] = file_id
1118
- st.rerun()
1119
- except Exception as e:
1120
- st.error("Error reading file: " + str(e))
1121
-
1122
- with st.form("questionnaire_form"):
1123
- for q in QUESTIONNAIRE:
1124
- st.markdown("**" + q['question'] + "**")
1125
-
1126
- response = st.text_area(
1127
- label="Response for " + q['id'],
1128
- label_visibility="collapsed",
1129
- placeholder=q['placeholder'],
1130
- height=400,
1131
- key="input_" + q['id']
1132
- )
1133
- st.session_state.responses[q['id']] = response
1134
-
1135
- # Word counter to encourage more writing
1136
- words = len(response.split()) if response else 0
1137
- if words < 30:
1138
- st.caption(f"📝 {words} words. Try to share a bit more for a deeper analysis (recommended: 50+ words).")
1139
- else:
1140
- st.caption(f"✅ {words} words. Great detail provided.")
1141
-
1142
- st.markdown("---")
1143
-
1144
- submitted = st.form_submit_button("Analyze My Check-In", use_container_width=True)
1145
-
1146
- if submitted:
1147
- has_content = any(v and v.strip() for v in st.session_state.responses.values())
1148
- if has_content:
1149
- st.session_state.page = 'analysis'
1150
- st.rerun()
1151
- else:
1152
- st.warning("Please share a little about how you are feeling before submitting.")
1153
-
1154
- col1, col2, _ = st.columns([1, 1, 1])
1155
- with col1:
1156
- if st.button("Back to Home", use_container_width=True):
1157
- st.session_state.page = 'home'
1158
- st.rerun()
1159
-
1160
- with col2:
1161
- st.button("Clear Narration", on_click=handle_clear_narration, use_container_width=True)
1162
-
1163
-
1164
- # ============================================
1165
- # ANALYSIS PAGE
1166
- # ============================================
1167
- def render_analysis_page(model):
1168
- """Render the analysis page with sentence-level results"""
1169
-
1170
- st.markdown("<h2 class='sub-header'>Analyzing Your Responses</h2>",
1171
- unsafe_allow_html=True)
1172
-
1173
- analyzer = MentalHealthAnalyzer(model, model.classes_)
1174
- progress_bar = st.progress(0)
1175
- status_text = st.empty()
1176
- all_sentences = []
1177
- errors = 0
1178
-
1179
- for i, (q_id, response) in enumerate(st.session_state.responses.items()):
1180
- if response and response.strip():
1181
- status_text.text("Processing narration and segmenting thoughts...")
1182
- try:
1183
- cleaned = clean_response(response)
1184
- sentence_results = analyzer.analyze_response(cleaned, q_id)
1185
- all_sentences.extend(sentence_results)
1186
- except Exception:
1187
- errors += 1
1188
- st.warning("Could not fully analyze the text segment.")
1189
-
1190
- progress_bar.progress((i + 1) / len(QUESTIONNAIRE))
1191
-
1192
- if errors:
1193
- st.info(str(errors) + " question(s) were skipped due to processing issues.")
1194
-
1195
- if all_sentences:
1196
- st.session_state.analyzer = analyzer
1197
- analyzer.sentence_predictions = all_sentences
1198
- analyzer.aggregated_results = analyzer._aggregate_predictions()
1199
- st.session_state.results = analyzer.aggregated_results
1200
- st.session_state.analysis_complete = True
1201
-
1202
- if st.session_state.tracker:
1203
- st.session_state.tracker.add_assessment(
1204
- analyzer.aggregated_results,
1205
- st.session_state.responses
1206
- )
1207
- else:
1208
- st.error("The AI requires more than a single word to provide an accurate assessment. Please provide more detail in your responses.")
1209
- st.session_state.analysis_complete = False
1210
-
1211
- status_text.text("Analysis complete.")
1212
- progress_bar.empty()
1213
-
1214
- st.markdown("### Sentence-Level Analysis")
1215
- st.caption(
1216
- "Each sentence from your responses has been classified by the classifying model. "
1217
- "Results below show the predicted indicator per sentence."
1218
- )
1219
-
1220
- COLOR_MAP = {
1221
- 'suicidal': ("#fff0f0", "Suicidal"),
1222
- 'anxiety': ("#fffbf0", "Anxiety"),
1223
- 'depression': ("#f0f4ff", "Depression"),
1224
- 'normal': ("#f8f9fa", "Normal"),
1225
- }
1226
-
1227
- visible = all_sentences[:10]
1228
- hidden = all_sentences[10:]
1229
-
1230
- if visible:
1231
- for sent_result in visible:
1232
- prediction = sent_result.get('prediction', 'normal')
1233
- color, label = COLOR_MAP.get(prediction, ("#f8f9fa", "Normal"))
1234
- safe_sentence = html_lib.escape(sent_result.get('sentence', ''))
1235
-
1236
- # Explainable AI markers
1237
- intensity = sent_result.get('intensity', 1.0)
1238
- markers = ", ".join(sent_result.get('markers', []))
1239
- marker_text = f" | Signals: {markers}" if markers else ""
1240
- conf_text = f" &mdash; Confidence: {sent_result.get('confidence', 0):.1%} | Intensity: {intensity:.1f}x{marker_text}"
1241
-
1242
- html_block = (
1243
- "<div class='sentence-box' style='background-color:" + color + ";'>"
1244
- "<span style='color:#555;font-size:0.82rem;'>" + label + conf_text + "</span><br>"
1245
- "<span>" + safe_sentence + "</span>"
1246
- "</div>"
1247
- )
1248
- st.markdown(html_block, unsafe_allow_html=True)
1249
-
1250
- if hidden:
1251
- with st.expander("Show remaining " + str(len(hidden)) + " sentences"):
1252
- for sent_result in hidden:
1253
- prediction = sent_result.get('prediction', 'normal')
1254
- color, label = COLOR_MAP.get(prediction, ("#f8f9fa", "Normal"))
1255
- safe_sentence = html_lib.escape(sent_result.get('sentence', ''))
1256
-
1257
- # Explainable AI markers (Consistent with visible section)
1258
- intensity = sent_result.get('intensity', 1.0)
1259
- markers = ", ".join(sent_result.get('markers', []))
1260
- marker_text = f" | Signals: {markers}" if markers else ""
1261
- conf_text = f" &mdash; Confidence: {sent_result.get('confidence', 0):.1%} | Intensity: {intensity:.1f}x{marker_text}"
1262
-
1263
- html_block = (
1264
- "<div class='sentence-box' style='background-color:" + color + ";'>"
1265
- "<span style='color:#555;font-size:0.82rem;'>" + label + conf_text + "</span><br>"
1266
- "<span>" + safe_sentence + "</span>"
1267
- "</div>"
1268
- )
1269
- st.markdown(html_block, unsafe_allow_html=True)
1270
- else:
1271
- st.warning("No analyzable sentences were found. Please provide more detail in your responses.")
1272
- if st.button("Go Back to Questionnaire", use_container_width=True):
1273
- st.session_state.page = 'questionnaire'
1274
- st.rerun()
1275
-
1276
- if all_sentences:
1277
- if st.button("View Assessment Summary", use_container_width=True):
1278
- st.session_state.page = 'summary'
1279
- st.rerun()
1280
-
1281
-
1282
- # ============================================
1283
- # SUMMARY PAGE
1284
- # ============================================
1285
- def render_summary_page():
1286
- """Render the summary page with results and progress"""
1287
-
1288
- st.markdown("<h2 class='sub-header'>Assessment Summary</h2>",
1289
- unsafe_allow_html=True)
1290
-
1291
- if not st.session_state.results:
1292
- st.error("No analysis results found.")
1293
- if st.button("Back to Questionnaire"):
1294
- st.session_state.page = 'questionnaire'
1295
- st.rerun()
1296
- return
1297
-
1298
- results = st.session_state.results
1299
- analyzer = st.session_state.analyzer
1300
- risk_level = analyzer.get_risk_level()
1301
- recommender = RecommendationEngine()
1302
- suicidal_flagged = analyzer.get_suicidal_flagged_sentences()
1303
- recommendations = recommender.get_recommendations(
1304
- results['primary_indicator'], risk_level, suicidal_flagged
1305
- )
1306
-
1307
- # Indicators
1308
- col1, col2 = st.columns(2)
1309
- with col1:
1310
- st.markdown("### Primary Indicator")
1311
- primary = results['primary_indicator']
1312
- pct = results['primary_percentage']
1313
- if primary == 'suicidal':
1314
- st.error("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1315
- elif primary in ['anxiety', 'depression']:
1316
- st.warning("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1317
- else:
1318
- st.success("**" + primary.upper() + "** (" + f"{pct:.1f}" + "%)")
1319
-
1320
- # Display Continuity Insight
1321
- if results.get('continuity', {}).get('escalating_distress'):
1322
- st.info("💡 **Pattern Detected**: Our analysis noted a slight escalation in emotional distress throughout your responses. We recommend taking extra time for the self-care steps below.")
1323
- elif results.get('continuity', {}).get('resilience_count', 0) > 1:
1324
- st.success("🌱 **Resilience Noted**: We detected several markers of hope and recovery in your thoughts. This is a very positive sign.")
1325
-
1326
- with col2:
1327
- if results['secondary_indicator']:
1328
- st.markdown("### Secondary Indicator")
1329
- secondary = results['secondary_indicator']
1330
- st.info("**" + secondary.upper() + "** (" + f"{results['secondary_percentage']:.1f}" + "%)")
1331
-
1332
- # Risk level
1333
- st.markdown("### Risk Assessment")
1334
- risk_map = {
1335
- "high": ("risk-high", "HIGH RISK — Immediate support is strongly recommended."),
1336
- "moderate_high": ("risk-high", "MODERATE-HIGH RISK — Please speak with a mental health professional."),
1337
- "moderate": ("risk-moderate", "MODERATE RISK — Consider professional support."),
1338
- "mild": ("risk-moderate", "MILD RISK — Self-care strategies are recommended."),
1339
- "low": ("risk-low", "LOW RISK — Continue maintaining your mental wellness."),
1340
- }
1341
- css_class, message = risk_map.get(risk_level, ("risk-low", "Status could not be determined."))
1342
- st.markdown("<div class='" + css_class + "'>" + message + "</div>", unsafe_allow_html=True)
1343
-
1344
- # Distribution chart
1345
- st.markdown("### Distribution of Indicators")
1346
- df_dist = create_distribution_dataframe(results['distribution'])
1347
- fig = px.bar(
1348
- df_dist,
1349
- x='Mental Health Indicator',
1350
- y='Percentage',
1351
- color='Mental Health Indicator',
1352
- color_discrete_map={
1353
- 'anxiety': '#e67e22',
1354
- 'depression': '#2980b9',
1355
- 'suicidal': '#c0392b',
1356
- 'normal': '#27ae60',
1357
- },
1358
- text=df_dist['Percentage'].apply(lambda x: f"{x:.1f}%")
1359
- )
1360
- fig.update_layout(
1361
- xaxis_title="",
1362
- yaxis_title="Percentage of Sentences (%)",
1363
- showlegend=False,
1364
- height=380,
1365
- plot_bgcolor='white',
1366
- paper_bgcolor='white',
1367
- margin=dict(t=10, b=40)
1368
- )
1369
- fig.update_traces(textposition='outside')
1370
- fig.update_xaxes(showgrid=False)
1371
- fig.update_yaxes(showgrid=True, gridcolor='#f0f0f0')
1372
- st.plotly_chart(fig, use_container_width=True)
1373
-
1374
- # Recommendations
1375
- st.markdown("### Recommendations")
1376
- if recommendations:
1377
- st.markdown("#### " + recommendations['title'])
1378
- st.markdown(recommendations['message'])
1379
- for i, tip in enumerate(recommendations['tips'], 1):
1380
- st.markdown(str(i) + ". " + tip)
1381
-
1382
- # Crisis resources
1383
- if risk_level in ['high', 'moderate_high']:
1384
- with st.expander("Immediate Help — Nigeria", expanded=True):
1385
- st.markdown("### " + CRISIS_RESOURCES['title'])
1386
- st.markdown(CRISIS_RESOURCES['message'])
1387
- for resource in CRISIS_RESOURCES['resources']:
1388
- st.markdown("- " + resource)
1389
- st.markdown("*" + CRISIS_RESOURCES['hospital_note'] + "*")
1390
- st.markdown("---")
1391
- st.markdown("**You are not alone. Reaching out is a sign of strength.**")
1392
-
1393
- # Flagged sentences
1394
- if suicidal_flagged:
1395
- with st.expander("Sentences Flagged for Review",
1396
- expanded=risk_level in ['high', 'moderate_high']):
1397
- st.caption(
1398
- "The following sentences were identified by the model as containing "
1399
- "indicators associated with suicidal ideation."
1400
- )
1401
- for sent in suicidal_flagged:
1402
- st.markdown("- *" + html_lib.escape(sent['sentence']) + "*")
1403
-
1404
- # Nigerian wisdom
1405
- with st.expander("Nigerian Wisdom", expanded=False):
1406
- st.markdown("**Words of encouragement from our culture:**")
1407
- for proverb in NIGERIAN_PROVERBS:
1408
- st.markdown("*\"" + proverb + "\"*")
1409
-
1410
- st.markdown("---")
1411
- render_progress_tracking()
1412
-
1413
- st.markdown("---")
1414
- render_feedback_section()
1415
-
1416
- # Action buttons
1417
- col1, col2, col3 = st.columns(3)
1418
-
1419
- with col1:
1420
- if st.button("New Check-In", use_container_width=True):
1421
- for q in QUESTIONNAIRE:
1422
- st.session_state["input_" + q['id']] = ""
1423
- for key in ['responses', 'analyzer', 'results', 'analysis_complete']:
1424
- st.session_state.pop(key, None)
1425
- st.session_state.page = 'questionnaire'
1426
- st.rerun()
1427
-
1428
- with col2:
1429
- if st.button("Home", use_container_width=True):
1430
- st.session_state.page = 'home'
1431
- st.rerun()
1432
-
1433
- with col3:
1434
- nat_resources = NIGERIA_EMERGENCY_NUMBERS['national']['resources']
1435
- state_resources = NIGERIA_EMERGENCY_NUMBERS['state_emergency']['resources']
1436
-
1437
- report_lines = [
1438
- "HEEDX AI - MENTAL HEALTH CHECK-IN REPORT",
1439
- "Generated : " + datetime.now().strftime('%Y-%m-%d %H:%M'),
1440
- "",
1441
- "PRIMARY INDICATOR : " + results['primary_indicator'].upper() +
1442
- " (" + f"{results['primary_percentage']:.1f}" + "%)",
1443
- ]
1444
- if results['secondary_indicator']:
1445
- report_lines.append(
1446
- "SECONDARY INDICATOR: " + results['secondary_indicator'].upper() +
1447
- " (" + f"{results['secondary_percentage']:.1f}" + "%)"
1448
- )
1449
- report_lines += [
1450
- "",
1451
- "RISK LEVEL: " + risk_level.upper(),
1452
- "",
1453
- "DISTRIBUTION:",
1454
- *[" - " + k + ": " + f"{v:.1f}" + "%" for k, v in results['distribution'].items()],
1455
- "",
1456
- "RECOMMENDATIONS:",
1457
- *[" " + str(i) + ". " + tip for i, tip in enumerate(recommendations['tips'], 1)],
1458
- "",
1459
- "NIGERIAN EMERGENCY RESOURCES:",
1460
- *[" - " + r for r in nat_resources],
1461
- *[" - " + r for r in state_resources],
1462
- "",
1463
- "DISCLAIMER: This is an AI-generated assessment, not a medical diagnosis.",
1464
- "If you are in crisis, call 112 or visit the nearest Federal Neuropsychiatric Hospital.",
1465
- ]
1466
-
1467
- st.download_button(
1468
- label="Download Report",
1469
- data="\n".join(report_lines),
1470
- file_name="heedx_report_" + datetime.now().strftime('%Y%m%d_%H%M') + ".txt",
1471
- mime="text/plain",
1472
- use_container_width=True
1473
- )
1474
-
1475
-
1476
- # ============================================
1477
- # PROGRESS PAGE
1478
- # ============================================
1479
- def render_progress_page():
1480
- """Render the standalone progress page"""
1481
-
1482
- st.markdown("<h2 class='sub-header'>Your Wellness Journey</h2>", unsafe_allow_html=True)
1483
-
1484
- if not st.session_state.tracker:
1485
- st.info("Complete your first check-in to see your progress.")
1486
- if st.button("Start Check-In", use_container_width=True):
1487
- st.session_state.page = 'questionnaire'
1488
- st.rerun()
1489
- return
1490
-
1491
- render_progress_tracking()
1492
-
1493
- if st.button("Back to Home", use_container_width=True):
1494
- st.session_state.page = 'home'
1495
- st.rerun()
1496
-
1497
-
1498
- # ============================================
1499
- # MAIN
1500
- # ============================================
1501
- def main():
1502
- """Main application controller"""
1503
-
1504
- init_session_state()
1505
-
1506
- # ── Development Notice ──────────────────────────────────────────────────
1507
- st.info(
1508
- "🛠️ **Development Notice**: HeedX AI is currently in an active testing and development phase. "
1509
- "We are continuously working to improve the analysis accuracy and system intelligence. "
1510
- "Thank you for participating in our user testing."
1511
- )
1512
-
1513
- # Load model before sidebar renders — chatbot context depends on it
1514
- if 'model' not in st.session_state:
1515
- with st.spinner("Loading HeedX AI..."):
1516
- st.session_state.model = load_model()
1517
-
1518
- model = st.session_state.model
1519
-
1520
- # ── Sidebar ───────────────────────────────────────────────────────────────
1521
- with st.sidebar:
1522
- st.markdown(
1523
- "<div style='text-align:center;padding:0.5rem 0;'>"
1524
- "<span style='font-size:1.5rem;font-weight:700;color:#008751;'>HeedX AI</span><br>"
1525
- "<span style='font-size:0.78rem;color:#718096;'>Nigerian Mental Wellness Platform</span>"
1526
- "</div>",
1527
- unsafe_allow_html=True
1528
- )
1529
- st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
1530
-
1531
- # Navigation
1532
- st.markdown("**Navigation**")
1533
- if st.button("Home", use_container_width=True):
1534
- st.session_state.page = 'home'
1535
- st.rerun()
1536
- if st.button("Check-In", use_container_width=True):
1537
- st.session_state.page = 'questionnaire'
1538
- st.rerun()
1539
- if st.button("Wellness Chat", use_container_width=True):
1540
- st.session_state.page = 'chat'
1541
- st.rerun()
1542
- if st.session_state.get('analysis_complete', False):
1543
- if st.button("Summary", use_container_width=True):
1544
- st.session_state.page = 'summary'
1545
- st.rerun()
1546
- if st.session_state.tracker and st.session_state.tracker.has_history():
1547
- if st.button("Progress", use_container_width=True):
1548
- st.session_state.page = 'progress'
1549
- st.rerun()
1550
-
1551
- st.markdown("---")
1552
-
1553
- with st.expander("Emergency Numbers", expanded=False):
1554
- st.markdown("**Emergency:** 112")
1555
- for r in NIGERIA_EMERGENCY_NUMBERS['national']['resources'][:3]:
1556
- st.markdown("- " + r)
1557
-
1558
- with st.expander("Disclaimer"):
1559
- st.markdown(
1560
- "This tool is for informational and supportive purposes only. "
1561
- "It is not a substitute for professional medical advice. "
1562
- "If you are in crisis, call **112** immediately."
1563
- )
1564
-
1565
- # Contact channels — always visible
1566
- render_sidebar_contacts()
1567
-
1568
- # ── Guard against missing model ───────────────────────────────────────────
1569
- if model is None:
1570
- st.error(
1571
- "The model could not be loaded."
1572
- )
1573
- st.stop()
1574
-
1575
- # ── Page dispatch ─────────────────────────────────────────────────────────
1576
- PAGE_MAP = {
1577
- 'home': lambda: render_home_page(),
1578
- 'questionnaire': lambda: render_questionnaire_page(),
1579
- 'analysis': lambda: render_analysis_page(model),
1580
- 'summary': lambda: render_summary_page(),
1581
- 'progress': lambda: render_progress_page(),
1582
- 'chat': lambda: render_chat_page(),
1583
- }
1584
-
1585
- page_fn = PAGE_MAP.get(st.session_state.page, lambda: render_home_page())
1586
- page_fn()
1587
-
1588
- # ── Footer ────────────────────────────────────────────────────────────────
1589
- st.markdown("---")
1590
- st.markdown("""
1591
- <div class='disclaimer'>
1592
- <p><strong>HeedX AI &mdash; Nigerian Edition</strong></p>
1593
- <p>This is a supportive tool only and does not constitute a medical diagnosis.</p>
1594
- <p>Crisis lines: <strong>112</strong> (National Emergency) &nbsp;|&nbsp;
1595
- <strong>08062106493</strong> (Mentally Aware Nigeria Initiative)</p>
1596
- <p>You are not alone. Help is always available.</p>
1597
- </div>
1598
- """, unsafe_allow_html=True)
1599
-
1600
-
1601
- if __name__ == "__main__":
1602
- main()