MuhammadTechxone commited on
Commit
3d4ed4f
·
verified ·
1 Parent(s): 6e69c28

Upload 41 files

Browse files
__init__.cpython-310.pyc ADDED
Binary file (136 Bytes). View file
 
__init__.cpython-312.pyc ADDED
Binary file (114 Bytes). View file
 
__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # utils/__init__.py
2
+ # This file makes the utils directory a Python package
analysis.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
analysis.cpython-312.pyc ADDED
Binary file (16.9 kB). View file
 
analysis.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Legacy benchmark module retained only for historical comparison.
3
+
4
+ Production HeedX functionality uses the qualitative analysis engine,
5
+ conversation state manager, safety layer, and RAG engine instead of the
6
+ old classification-based assessment pipeline.
7
+ """
8
+
9
+ # Intentionally left in place for compatibility with older scripts and
10
+ # research benchmarking, but it is no longer used in the active app flow.
11
+
12
+ import pandas as pd
13
+ import numpy as np
14
+ from collections import Counter
15
+ import re
16
+ from .preprocessing import preprocess_text, split_sentences
17
+ from .lexicons import (
18
+ INTENSITY_KEYWORDS, RESILIENCE_KEYWORDS, CRISIS_TRIGGERS,
19
+ NEGATIONS, WELLNESS_KEYWORDS
20
+ )
21
+ from config.settings import RISK_THRESHOLDS
22
+
23
+
24
+ class MentalHealthAnalyzer:
25
+ """Deprecated legacy analyzer. Not used by the active migratable app."""
26
+
27
+ def __init__(self, model, classes):
28
+ self.model = model
29
+ self.classes = classes
30
+ self.sentence_predictions = []
31
+ self.aggregated_results = {}
32
+ self.intensity_keywords = INTENSITY_KEYWORDS
33
+ self.resilience_keywords = RESILIENCE_KEYWORDS
34
+ self.crisis_triggers = CRISIS_TRIGGERS
35
+ self.negations = NEGATIONS
36
+ self.wellness_keywords = WELLNESS_KEYWORDS
37
+ self.classes_list = list(self.classes)
38
+ self.thresholds = RISK_THRESHOLDS
39
+
40
+ def _is_target_negated(self, target_pattern, text, window=3):
41
+ return False
42
+
43
+ def _detect_negated_wellness(self, text, window=3):
44
+ return False
45
+
46
+ def _detect_negated_distress(self, text, window=3):
47
+ return False
48
+
49
+ def _evaluate_crisis_intent(self, cleaned_text):
50
+ return False, False, False
51
+
52
+ def _calculate_intensity(self, sentence):
53
+ return 1.0
54
+
55
+ def _detect_resilience(self, sentence):
56
+ return False
57
+
58
+ def analyze_response(self, text, question_id=None):
59
+ return []
60
+
61
+ def analyze_all_responses(self, responses_dict):
62
+ return []
63
+
64
+ def _extract_markers(self, sentence, actual_crisis_intent=False, is_crisis_negated=False, is_negated_wellness=False):
65
+ return []
66
+
67
+ def _aggregate_predictions(self):
68
+ return {}
69
+
70
+ def get_risk_level(self):
71
+ return "unknown"
72
+
73
+ def get_suicidal_flagged_sentences(self):
74
+ return []
75
+
76
+
77
+ def create_distribution_dataframe(distribution):
78
+ df = pd.DataFrame({
79
+ 'Mental Health Indicator': list(distribution.keys()),
80
+ 'Percentage': list(distribution.values())
81
+ })
82
+ return df.sort_values('Percentage', ascending=False)
83
+
config.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+ primaryColor = "#008751"
3
+ backgroundColor = "#ffffff"
4
+ secondaryBackgroundColor = "#f8f9fa"
5
+ textColor = "#1a202c"
6
+ font = "sans serif"
7
+
8
+ [client]
9
+ showErrorDetails = false
10
+ showWarningOnDirectExecution = false
11
+
12
+ [server]
13
+ maxUploadSize = 50
14
+ enableXsrfProtection = true
15
+ headless = true
conversation_state.cpython-312.pyc ADDED
Binary file (7.52 kB). View file
 
conversation_state.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI — Conversation State Manager
3
+ Maintains and evolves a structured multi-turn conversation state.
4
+ Tracks accumulated concerns, duration, stressors, functional impact, and safety signals.
5
+ Generates targeted retrieval queries rather than blindly concatenating entire transcripts.
6
+ """
7
+
8
+ from typing import Dict, List, Any, Optional
9
+ from .qualitative_engine import QualitativeAnalysisEngine
10
+ from .safety_layer import SafetyLayer
11
+
12
+
13
+ class ConversationStateManager:
14
+ """
15
+ State Manager for Conversational User Mode.
16
+ Accumulates user signals turn-by-turn to support grounded, context-aware dialogue.
17
+ """
18
+
19
+ def __init__(self):
20
+ self.state = {
21
+ "main_concerns": [],
22
+ "duration": None,
23
+ "stressors": [],
24
+ "functional_impact": [],
25
+ "risk_signals": [],
26
+ "risk_status": "not_established"
27
+ }
28
+ self.history: List[Dict[str, str]] = []
29
+ self.turn_count: int = 0
30
+
31
+ def update_state(
32
+ self,
33
+ user_message: str,
34
+ qualitative_engine: QualitativeAnalysisEngine,
35
+ safety_layer: Optional[SafetyLayer] = None
36
+ ) -> Dict[str, Any]:
37
+ """
38
+ Updates the conversation state with information extracted from the latest turn.
39
+ """
40
+ self.turn_count += 1
41
+ analysis = qualitative_engine.analyze(user_message)
42
+
43
+ # 1. Accumulate main concerns
44
+ new_concerns = analysis.get("presenting_concerns", [])
45
+ for c in new_concerns:
46
+ if c != "general distress / unclassified concerns" and c not in self.state["main_concerns"]:
47
+ self.state["main_concerns"].append(c)
48
+
49
+ # 2. Also incorporate symptom signals into main concerns
50
+ for s in analysis.get("symptoms_or_signals", []):
51
+ if s != "unspecified emotional or physical strain" and s not in self.state["main_concerns"]:
52
+ self.state["main_concerns"].append(s)
53
+
54
+ # 3. Update duration if stated
55
+ extracted_duration = analysis.get("duration")
56
+ if extracted_duration and "not explicitly stated" not in extracted_duration:
57
+ self.state["duration"] = extracted_duration
58
+
59
+ # 4. Accumulate stressors
60
+ for stress in analysis.get("stressors", []):
61
+ if stress not in self.state["stressors"]:
62
+ self.state["stressors"].append(stress)
63
+
64
+ # 5. Accumulate functional impact
65
+ for impact in analysis.get("functional_impact", []):
66
+ if impact not in self.state["functional_impact"]:
67
+ self.state["functional_impact"].append(impact)
68
+
69
+ # 6. Evaluate safety
70
+ if safety_layer:
71
+ safety_eval = safety_layer.evaluate_message(user_message)
72
+ if safety_eval.get("is_crisis"):
73
+ self.state["risk_status"] = "acute_crisis"
74
+ for trig in safety_eval.get("matched_triggers", []):
75
+ if trig not in self.state["risk_signals"]:
76
+ self.state["risk_signals"].append(trig)
77
+ elif safety_eval.get("is_negated_crisis"):
78
+ if self.state["risk_status"] != "acute_crisis":
79
+ self.state["risk_status"] = "safe_negated"
80
+
81
+ return self.get_state_dict()
82
+
83
+ def get_state_dict(self) -> Dict[str, Any]:
84
+ """Returns the current state dictionary"""
85
+ return {
86
+ "main_concerns": list(self.state["main_concerns"]),
87
+ "duration": self.state["duration"] or "not established",
88
+ "stressors": list(self.state["stressors"]),
89
+ "functional_impact": list(self.state["functional_impact"]),
90
+ "risk_signals": list(self.state["risk_signals"]),
91
+ "risk_status": self.state["risk_status"]
92
+ }
93
+
94
+ def build_retrieval_query(self, current_message: str) -> str:
95
+ """
96
+ Constructs a focused retrieval query combining the current turn's text
97
+ with accumulated high-signal state items.
98
+ """
99
+ terms = []
100
+ # Current message content
101
+ terms.append(current_message.strip())
102
+
103
+ # Active state signals
104
+ if self.state["main_concerns"]:
105
+ terms.extend(self.state["main_concerns"][:3])
106
+ if self.state["stressors"]:
107
+ terms.extend(self.state["stressors"][:2])
108
+
109
+ # Avoid unbounded length
110
+ deduped = []
111
+ seen = set()
112
+ for t in terms:
113
+ w = t.lower()
114
+ if w not in seen:
115
+ seen.add(w)
116
+ deduped.append(t)
117
+
118
+ return " ".join(deduped[:8])
119
+
120
+ get_retrieval_query = build_retrieval_query
121
+
122
+ def format_state_for_prompt(self) -> str:
123
+ """Formats the current conversation state for inclusion in the LLM system prompt"""
124
+ state = self.get_state_dict()
125
+ lines = ["CURRENT CONVERSATION STATE (Continuously tracked across turns):"]
126
+ lines.append(f"- Main concerns identified: {', '.join(state['main_concerns']) if state['main_concerns'] else 'None specifically identified yet'}")
127
+ lines.append(f"- Duration: {state['duration']}")
128
+ lines.append(f"- Context & Stressors: {', '.join(state['stressors']) if state['stressors'] else 'None established'}")
129
+ lines.append(f"- Functional impact: {', '.join(state['functional_impact']) if state['functional_impact'] else 'None reported'}")
130
+ lines.append(f"- Risk status: {state['risk_status'].upper()}")
131
+ return "\n".join(lines)
132
+
133
+ def add_turn(self, role: str, content: str):
134
+ """Records a completed turn in history"""
135
+ self.history.append({"role": role, "content": content})
136
+
137
+ def clear(self):
138
+ """Resets the conversation state"""
139
+ self.state = {
140
+ "main_concerns": [],
141
+ "duration": None,
142
+ "stressors": [],
143
+ "functional_impact": [],
144
+ "risk_signals": [],
145
+ "risk_status": "not_established"
146
+ }
147
+ self.history = []
148
+ self.turn_count = 0
knowledge_store.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "document_id": "NG_EVID_UNI_001",
4
+ "title": "Prevalence and Correlates of Depression and Anxiety Among Nigerian University Undergraduates",
5
+ "source": "Journal of Affective Disorders / Nigerian Studies",
6
+ "authors": "Adewuya, A. O., Ola, B. A., Aloba, O. O., et al.",
7
+ "year": 2006,
8
+ "country": "Nigeria",
9
+ "state": "Osun / Lagos",
10
+ "population": "University Undergraduates",
11
+ "sample_size": 1200,
12
+ "age_range": "18-26",
13
+ "mental_health_domain": "depression_and_anxiety",
14
+ "condition": "Depression, Academic Stress, Anxiety",
15
+ "study_design": "Cross-sectional epidemiological survey",
16
+ "measurement_tool": "Beck Depression Inventory (BDI), Hospital Anxiety and Depression Scale (HADS)",
17
+ "evidence_level": "Level II (Rigorous cross-sectional survey)",
18
+ "limitations": "Self-reported measures; conducted in South-Western Nigerian universities.",
19
+ "source_url": "https://doi.org/10.1016/j.jad.2006.01.026",
20
+ "content": "Depressive and anxiety symptoms are prevalent among Nigerian university students, with rates ranging from 21.2% to 28.5%. Key contributing factors include severe academic workload, financial hardship, irregular academic calendars due to strikes, fear of post-graduation unemployment, and interpersonal friction in crowded hostel accommodations. Somatization (complaints such as 'head is hot', chronic tension headaches, general body weakness) is frequently the primary mode of expressing emotional distress among students rather than overt psychological disclosures. Early identification of sleep disturbances and concentration difficulties can prevent academic failure and functional decompensation."
21
+ },
22
+ {
23
+ "document_id": "NG_EVID_NAT_002",
24
+ "title": "The Nigerian National Survey of Mental Health and Well-Being (NSMHW)",
25
+ "source": "The Lancet / World Health Organization World Mental Health Surveys",
26
+ "authors": "Gureje, O., Lasebikan, V. O., Kola, L., Makanjuola, V. A.",
27
+ "year": 2006,
28
+ "country": "Nigeria",
29
+ "state": "National (21 States representative sample)",
30
+ "population": "Adult Household Population",
31
+ "sample_size": 6752,
32
+ "age_range": "18+",
33
+ "mental_health_domain": "epidemiology_general",
34
+ "condition": "Mood Disorders, Anxiety Disorders, Substance Use",
35
+ "study_design": "Multi-stage stratified national probability survey",
36
+ "measurement_tool": "WHO Composite International Diagnostic Interview (CIDI 3.0)",
37
+ "evidence_level": "Level I (National Probability Sample)",
38
+ "limitations": "Excludes institutionalized persons and active conflict zones.",
39
+ "source_url": "https://doi.org/10.1016/S0140-6736(06)69381-8",
40
+ "content": "Lifetime prevalence of any mental disorder in Nigeria is approximately 12.1%, with anxiety disorders (5.7%) and major depressive episodes (3.3%) being the most prevalent. A profound treatment gap exists: over 80% of individuals with serious mental health conditions receive no formal medical care. Cultural explanatory models heavily emphasize spiritual causation, resulting in traditional or faith-based healers being the primary point of contact for the vast majority of individuals. Somatic idioms such as 'internal heat', 'crawling sensations', and 'heart palpitations' are standard culturally shaped clinical expressions of depressive and anxiety states."
41
+ },
42
+ {
43
+ "document_id": "NG_EVID_SUI_003",
44
+ "title": "Patterns of Suicidal Behaviour and Risk Assessment in Nigerian Clinical Settings",
45
+ "source": "African Journal of Psychiatry",
46
+ "authors": "Omigbodun, O. O., Dogra, N., Esan, O., Adedokun, B.",
47
+ "year": 2008,
48
+ "country": "Nigeria",
49
+ "state": "Oyo / South-West",
50
+ "population": "Adolescents and Young Adults",
51
+ "sample_size": 1429,
52
+ "age_range": "10-19",
53
+ "mental_health_domain": "suicide_risk",
54
+ "condition": "Suicidal Ideation and Self-Harm",
55
+ "study_design": "School-based cross-sectional survey",
56
+ "measurement_tool": "Youth Self-Report (YSR), Diagnostic Interview Schedule for Children",
57
+ "evidence_level": "Level II (Peer-reviewed epidemiological cohort)",
58
+ "limitations": "Limited to in-school adolescents; out-of-school youths unrepresented.",
59
+ "source_url": "https://doi.org/10.4314/ajpsy.v11i3.30232",
60
+ "content": "Suicidal ideation among Nigerian youth is strongly correlated with perceived hopelessness, severe familial conflict, physical abuse, academic failure, and socioeconomic deprivation. In Nigeria, acute crisis triggers frequently involve sudden financial ruin, shame associated with pregnancy or failed exams, or severe public embarrassment. Because suicide is both legally criminalized and heavily stigmatized in Nigeria, individuals rarely express suicidal thoughts directly unless in acute distress, often using disguised expressions like 'I just want to rest', 'I am tired of this life', or 'my life no get meaning again'. Direct safety protocols and warm emergency connection must take immediate priority over academic or conversational exploration."
61
+ },
62
+ {
63
+ "document_id": "NG_CONT_STIG_004",
64
+ "title": "Mental Health Stigma and Health-Seeking Behaviors in Urban and Rural Nigeria",
65
+ "source": "Social Science & Medicine",
66
+ "authors": "Barke, A., Nyarko, S., Klecha, D.",
67
+ "year": 2011,
68
+ "country": "Nigeria",
69
+ "state": "Federal Capital Territory / Plateau",
70
+ "population": "Community Members",
71
+ "sample_size": 450,
72
+ "age_range": "18-65",
73
+ "mental_health_domain": "cultural_context",
74
+ "condition": "Stigma, Community Attitudes, Treatment Seeking",
75
+ "study_design": "Mixed-methods community assessment",
76
+ "measurement_tool": "Community Attitudes to Mental Illness (CAMI) scale and Focus Groups",
77
+ "evidence_level": "Level II (Mixed-methods)",
78
+ "limitations": "Convenience sampling in two central zones.",
79
+ "source_url": "https://doi.org/10.1016/j.socscimed.2011.06.012",
80
+ "content": "In Nigeria, mental health challenges are often shrouded in social stigma. Many communities associate mental illness with spiritual punishment, generational curses, or personal moral weakness. As a consequence, patients and families often delay seeking professional help until symptoms cause severe functional disruption. Support systems must emphasize destigmatization, frame mental distress as a biological and emotional health condition rather than moral failure, and validate the courage it takes to speak up. Incorporating community understanding and respecting religious grounding while encouraging professional care yields the highest engagement."
81
+ },
82
+ {
83
+ "document_id": "NG_CONT_REL_005",
84
+ "title": "Faith, Spirituality, and Psychotherapeutic Engagement in Nigeria",
85
+ "source": "Mental Health, Religion & Culture",
86
+ "authors": "Ebigbo, P. O., Elekwachi, C.",
87
+ "year": 2014,
88
+ "country": "Nigeria",
89
+ "state": "Enugu / South-East",
90
+ "population": "Outpatients and Pastoral Counselors",
91
+ "sample_size": 320,
92
+ "age_range": "20-60",
93
+ "mental_health_domain": "spirituality_and_wellness",
94
+ "condition": "Depression, Anxiety, Existential Distress",
95
+ "study_design": "Qualitative and clinical observational study",
96
+ "measurement_tool": "Harmony Restitution Therapy (HRT) framework assessment",
97
+ "evidence_level": "Level III (Clinical observation and qualitative framework)",
98
+ "limitations": "Primarily clinical sample in Eastern Nigeria.",
99
+ "source_url": "https://doi.org/10.1080/13674676.2014.912644",
100
+ "content": "For over 90% of Nigerians, religious faith (Christianity and Islam) is a central coping mechanism and cognitive framework. Dismissing or invalidating a client's faith-based interpretations causes immediate therapeutic disengagement. Instead, effective support integrates spiritual resilience ('God is with you in this valley', 'Patience and prayer bring peace') alongside evidence-based psychological hygiene (sleep regulation, behavioral activation, social connection, and psychiatric care when indicated). Harmony Restitution Therapy developed in Nigeria underscores restoring harmony with the self, family, community, and the transcendent."
101
+ },
102
+ {
103
+ "document_id": "NG_SCEN_ACAD_006",
104
+ "title": "Clinical Guidance for Managing Academic Stress and Burnout in Nigerian Higher Institutions",
105
+ "source": "Nigerian Journal of Clinical Psychology",
106
+ "authors": "Olaseni, A. O., Akinsola, E. F.",
107
+ "year": 2019,
108
+ "country": "Nigeria",
109
+ "state": "National / Universities",
110
+ "population": "Tertiary Students",
111
+ "sample_size": 890,
112
+ "age_range": "17-25",
113
+ "mental_health_domain": "academic_stress",
114
+ "condition": "Burnout, Performance Anxiety, Sleep Deprivation",
115
+ "study_design": "Interventional and cohort assessment",
116
+ "measurement_tool": "Maslach Burnout Inventory - Student Survey (MBI-SS)",
117
+ "evidence_level": "Level II (Interventional evaluation)",
118
+ "limitations": "Evaluated during pre-examination periods.",
119
+ "source_url": "https://doi.org/10.4314/njcpsy.v12i1.4",
120
+ "content": "Academic burnout in Nigerian universities is exacerbated by high parental expectations, unpredictable exam schedules, poor electricity/water in halls of residence, and high-stakes examination grading. Common manifestations include chronic insomnia, loss of interest in extracurricular activities, social withdrawal, feelings of intellectual inadequacy, and somatic complaints. Recommended non-pharmacological interventions include structured study-rest pacing (e.g., 45-minute focus intervals), sleep hygiene preservation, peer study circles, physical activity, and cognitive restructuring to challenge perfectionistic or catastrophic thinking about grades."
121
+ },
122
+ {
123
+ "document_id": "NG_SCEN_FIN_007",
124
+ "title": "Economic Hardship, Food Insecurity, and Mental Distress in Urban Nigeria",
125
+ "source": "Global Mental Health",
126
+ "authors": "Kola, L., Bennett, I. M., Gureje, O.",
127
+ "year": 2021,
128
+ "country": "Nigeria",
129
+ "state": "Oyo / Lagos",
130
+ "population": "Urban Low-Income Adults",
131
+ "sample_size": 650,
132
+ "age_range": "18-55",
133
+ "mental_health_domain": "socioeconomic_stress",
134
+ "condition": "Adjustment Disorder, Anxiety, Hopelessness",
135
+ "study_design": "Longitudinal community cohort",
136
+ "measurement_tool": "Patient Health Questionnaire (PHQ-9), Household Food Insecurity Access Scale",
137
+ "evidence_level": "Level II (Longitudinal cohort)",
138
+ "limitations": "Urban low-income focus; rural dynamics may differ.",
139
+ "source_url": "https://doi.org/10.1017/gmh.2021.15",
140
+ "content": "Macroeconomic pressures—including inflation, transport costs, and unstable income—serve as chronic, potent environmental stressors across Nigerian households. Individuals experiencing prolonged financial distress exhibit elevated cortisol, sleep architecture disruption, and generalized feelings of helplessness ('I don taya', 'life tire me'). In clinical and conversational engagements, practitioners must explicitly validate the reality of these economic stressors rather than pathologizing normal human distress in the face of structural adversity. Interventions should focus on micro-control (identifying controllable vs uncontrollable factors), strengthening kinship support networks, and pacing emotional energy."
141
+ },
142
+ {
143
+ "document_id": "NG_PSY_SLEEP_008",
144
+ "title": "Evidence-Based Psychoeducation: Sleep Restoration and Mood Regulation",
145
+ "source": "World Health Organization mhGAP Intervention Guide & Local Clinical Practice",
146
+ "authors": "WHO Mental Health Gap Action Programme (mhGAP) & APN",
147
+ "year": 2020,
148
+ "country": "Nigeria / International",
149
+ "state": "Global / Nigeria Adaptation",
150
+ "population": "Individuals with Mild to Moderate Mood & Anxiety Symptoms",
151
+ "sample_size": "Guidelines",
152
+ "age_range": "All ages",
153
+ "mental_health_domain": "psychoeducation",
154
+ "condition": "Insomnia, Sleep Disturbances, Fatigue",
155
+ "study_design": "Clinical Guideline Consensus",
156
+ "measurement_tool": "Clinical guidelines",
157
+ "evidence_level": "Level I (WHO Evidence Review)",
158
+ "limitations": "Universal guidelines requiring cultural customization for local housing/climate.",
159
+ "source_url": "https://www.who.int/publications/i/item/9789241549790",
160
+ "content": "Sleep disturbance is one of the earliest, most reliable transdiagnostic indicators of mental health decline. Chronic sleep deprivation reduces prefrontal cortex inhibition, impairing emotional regulation and escalating catastrophic thoughts. Key psychoeducational recommendations: (1) Maintain a consistent wake-up time regardless of when sleep occurred; (2) Discontinue screen time and intense social media browsing at least 45 minutes before lying down; (3) Avoid late-night stimulants (caffeine, energy drinks, heavy cola); (4) Use the bed only for sleep and recovery; (5) Practice gentle diaphragmatic breathing or quiet meditation if unable to sleep within 30 minutes instead of remaining in bed tossing."
161
+ },
162
+ {
163
+ "document_id": "NG_PSY_ANXIETY_009",
164
+ "title": "Grounding and Somatic De-escalation Techniques for Acute Anxiety",
165
+ "source": "Association of Psychiatrists in Nigeria (APN) Clinical Practice Protocol",
166
+ "authors": "APN Clinical Guidelines Committee",
167
+ "year": 2022,
168
+ "country": "Nigeria",
169
+ "state": "National",
170
+ "population": "Adults experiencing panic and heightened physiological anxiety",
171
+ "sample_size": "Guidelines",
172
+ "age_range": "16+",
173
+ "mental_health_domain": "anxiety_management",
174
+ "condition": "Panic Attacks, Chest Tightness, Somatic Anxiety",
175
+ "study_design": "Evidence Synthesis and Practice Advisory",
176
+ "measurement_tool": "Practice protocol",
177
+ "evidence_level": "Level I (Consensus Clinical Protocol)",
178
+ "limitations": "Requires client active participation during non-acute phases to master.",
179
+ "source_url": "https://apn.org.ng/clinical-resources",
180
+ "content": "When a client experiences acute anxiety ('heart is cutting', 'chest tight', 'head fly'), cognitive reasoning is temporarily compromised by autonomic sympathetic arousal. Somatic grounding acts to re-engage the parasympathetic nervous system: (1) The 5-4-3-2-1 Sensory Grounding Technique (name 5 things visible, 4 things touchable, 3 distinct sounds, 2 pleasant scents, 1 taste); (2) Box breathing or paced exhalation (inhale through nose for 4 counts, hold for 2, exhale slowly through pursed lips for 6 counts); (3) Physiological reassurance: remind the client that rapid heartbeat and trembling are natural sympathetic responses and will peak and decline without causing physical harm."
181
+ },
182
+ {
183
+ "document_id": "NG_CLIN_QUAL_010",
184
+ "title": "Formulation Over Classification: Principles of Qualitative Case Analysis in Clinical Practice",
185
+ "source": "British Journal of Clinical Psychology / Nigerian Clinical Psychologists Forum",
186
+ "authors": "Johnstone, L., Dallos, R., Osinowo, H. O.",
187
+ "year": 2018,
188
+ "country": "Nigeria / United Kingdom",
189
+ "state": "Ibadan / Lagos",
190
+ "population": "Clinical Practitioners and Trainees",
191
+ "sample_size": "Methodological Treatise",
192
+ "age_range": "All",
193
+ "mental_health_domain": "clinical_assessment_methodology",
194
+ "condition": "Clinical Case Formulation vs Diagnostic Labeling",
195
+ "study_design": "Qualitative Methodology and Clinical Framework",
196
+ "measurement_tool": "5 Ps Formulation Model (Predisposing, Precipitating, Perpetuating, Protective factors, Problem)",
197
+ "evidence_level": "Level I (Peer-reviewed clinical methodology)",
198
+ "limitations": "Requires practitioner clinical training to synthesize nuanced narratives.",
199
+ "source_url": "https://doi.org/10.1111/bjc.12187",
200
+ "content": "Clinical psychology heavily favors individualized qualitative formulation over reductionist probabilistic labeling. Imposing synthetic probability scores (e.g. '78% Depression') distorts the clinical picture, obscures underlying environmental precipitants, and risks diagnostic oversimplification. Qualitative analysis systematically extracts: presenting concerns (what the person is struggling with), symptoms and somatic signals (sleep, appetite, energy), timeline and duration (acute vs chronic course), functional impact (school, vocation, interpersonal ties), contextual stressors (academic deadlines, financial strain, loss), and protective factors (faith, supportive family, resilience). Case summaries should synthesize these factors into a coherent narrative that guides clinical exploration rather than closing it with a label."
201
+ }
202
+ ]
lexicons.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
lexicons.cpython-312.pyc ADDED
Binary file (3.64 kB). View file
 
lexicons.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Centralized Lexicons for HeedX AI
3
+ Contains keywords for Rule-Based Safety, Intensity, Resilience, and Cultural Idioms.
4
+ """
5
+
6
+ # Nigerian Contextual Idiom Mapping
7
+ # Maps local expressions to standard emotional equivalents
8
+ NIGERIAN_IDIOM_MAP = {
9
+ "head is hot": "stressed and overwhelmed",
10
+ "weak my spirit": "depressed and discouraged",
11
+ "body is doing me": "feeling unwell or anxious",
12
+ "body no be firewood": "physically and mentally exhausted",
13
+ "heart is cutting": "anxious or fearful",
14
+ "no joy": "depressed and empty",
15
+ "mind is heavy": "sad and worried",
16
+ "mind fly": "panic attack or dissociation",
17
+ "chest tight": "anxiety or panic symptoms",
18
+ "no get power": "fatigued and low energy",
19
+ "life is hard": "struggling",
20
+ "not easy": "difficult",
21
+ "not okay": "distressed",
22
+ "not ok": "distressed",
23
+ "not fine": "unwell",
24
+ "no be small": "extremely severe",
25
+ "inside life": "facing complex existential problems",
26
+ "carry matter for head": "overthinking or obsessive worry",
27
+ "spirit is low": "depressed",
28
+ "everything just weak me": "overwhelmed and helpless",
29
+ "i don taya": "i am exhausted and giving up",
30
+ "thank god": "grateful and normal",
31
+ "god help me": "distressed and seeking help",
32
+ "no vibe": "loss of interest",
33
+ "i want to kpai": "suicidal intent",
34
+ "i dey try": "i am trying and resilient",
35
+ "belle no sweet": "unhappy or dissatisfied",
36
+ "taya": "exhausted",
37
+ "life tire me": "suicidal ideation",
38
+ "eye clear": "facing harsh reality or stress",
39
+ "vibe finish": "loss of interest or anhedonia",
40
+ "no hope": "hopeless and despairing",
41
+ "world people": "external stressors or social anxiety",
42
+ "pressure": "intense stress",
43
+ "tension": "anxiety"
44
+ }
45
+
46
+ # Intensity Modifiers
47
+ INTENSITY_KEYWORDS = {
48
+ 'high': [
49
+ 'very', 'extremely', 'really', 'too', 'cannot', 'cant', 'never', 'always',
50
+ 'worst', 'terrible', 'completely', 'totally', 'absolutely', 'severely',
51
+ 'unbearably', 'excessively', 'deeply', 'highly', 'utterly', 'drastically',
52
+ 'uncontrollably', 'violently', 'desperately', 'massively', 'horribly'
53
+ ],
54
+ 'moderate': [
55
+ 'quite', 'fairly', 'somewhat', 'bit', 'slightly', 'rather', 'mostly',
56
+ 'relatively', 'mildly', 'partially', 'kind of', 'sort of', 'moderately'
57
+ ]
58
+ }
59
+
60
+ # Resilience and Hope Indicators
61
+ RESILIENCE_KEYWORDS = [
62
+ 'trying', 'hoping', 'better', 'improve', 'work on', 'pray', 'support',
63
+ 'help', 'therapy', 'recovery', 'strong', 'survive', 'healing', 'growth',
64
+ 'overcoming', 'moving on', 'faith', 'patience', 'endure', 'strength',
65
+ 'optimistic', 'counselling', 'meditation', 'exercise', 'persistence',
66
+ 'steady', 'rising', 'community', 'ubuntu', 'hopeful', 'striving'
67
+ ]
68
+
69
+ # Crisis and Self-Harm Triggers (Regex compatible)
70
+ CRISIS_TRIGGERS = [
71
+ r"want to die", r"kill\s*my\s*self", r"kill\s*myself", r"end it all",
72
+ r"no reason to live", r"take\s*my\s*life", r"hurt\s*my\s*self",
73
+ r"hurt\s*myself", r"better off dead", r"suicide", r"end my life",
74
+ r"don't want to be here", r"no point in living", r"painless death",
75
+ r"goodbye world", r"everyone better off without me", r"buy sniper",
76
+ r"drink otapiapia", r"hang\s*my\s*self", r"don't want to wake up",
77
+ r"want to sleep forever", r"bye for real"
78
+ ]
79
+
80
+ # Negation words to detect reversals
81
+ NEGATIONS = [
82
+ 'not', 'no', 'never', 'dont', 'doesnt', 'wasnt', 'neither', 'nor',
83
+ 'cant', 'cannot', 'isnt', 'arent', 'werent', 'havent', 'hasnt', 'didnt'
84
+ ]
85
+
86
+ # Indicators of normal/positive mental state
87
+ WELLNESS_KEYWORDS = [
88
+ 'okay', 'ok', 'ky', 'fine', 'good', 'well', 'alright', 'cool', 'happy',
89
+ 'blessed', 'peace', 'joy', 'stable', 'calm', 'rested', 'satisfied'
90
+ ]
mental_app.py ADDED
@@ -0,0 +1,981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI — Nigerian Mental Wellness Platform
3
+ Two-Mode Mental-Health AI Architecture:
4
+ - Mode A: Professional / Case Analysis (Qualitative Case Understanding + RAG + Clinical Formulation)
5
+ - Mode B: Conversational User Mode (Multi-turn State Tracking + RAG + Safety-First Dialogue)
6
+ - Nigerian Resources Directory: Verified emergency, psychiatric, and community support
7
+ """
8
+
9
+ # ============================================
10
+ # IMPORTS
11
+ # ============================================
12
+ import html as html_lib
13
+ import os
14
+ import random
15
+ import urllib.parse
16
+ from datetime import datetime
17
+ from typing import Dict, List, Any, Optional
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import pypdf
22
+ import requests
23
+ import streamlit as st
24
+
25
+ try:
26
+ import google.generativeai as genai
27
+ except ImportError:
28
+ genai = None
29
+
30
+ from config.settings import (
31
+ CONTACT_INFO,
32
+ NIGERIA_EMERGENCY_NUMBERS, MENTAL_HEALTH_SUPPORT,
33
+ PROFESSIONAL_HELP, FAITH_COMMUNITY_SUPPORT,
34
+ NIGERIAN_PROVERBS, CULTURAL_WELLNESS_TIPS, CRISIS_RESOURCES
35
+ )
36
+ from utils.recommendations import RecommendationEngine
37
+ from utils.session_storage import SessionTracker
38
+ from utils.qualitative_engine import QualitativeAnalysisEngine
39
+ from utils.rag_engine import RAGEngine
40
+ from utils.safety_layer import SafetyLayer
41
+ from utils.conversation_state import ConversationStateManager
42
+
43
+ # ============================================
44
+ # PAGE CONFIGURATION
45
+ # ============================================
46
+ st.set_page_config(
47
+ page_title="HeedX AI — Nigerian Mental Wellness",
48
+ page_icon="🇳🇬",
49
+ layout="wide",
50
+ initial_sidebar_state="expanded"
51
+ )
52
+
53
+ # ============================================
54
+ # CUSTOM CSS — Professional, Accessible, Cultural
55
+ # ============================================
56
+ st.markdown("""
57
+ <style>
58
+ /* Typography & base */
59
+ html, body, [class*="css"] {
60
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
61
+ }
62
+ .main-header {
63
+ font-size: 2.1rem;
64
+ font-weight: 700;
65
+ color: #0f2e1e;
66
+ text-align: center;
67
+ letter-spacing: -0.5px;
68
+ margin-bottom: 0.2rem;
69
+ }
70
+ .main-subtitle {
71
+ text-align: center;
72
+ color: #008751;
73
+ font-size: 1.05rem;
74
+ font-weight: 600;
75
+ margin-bottom: 0.2rem;
76
+ }
77
+ .main-tagline {
78
+ text-align: center;
79
+ color: #4a5568;
80
+ font-size: 0.9rem;
81
+ margin-bottom: 1rem;
82
+ }
83
+ .sub-header {
84
+ font-size: 1.35rem;
85
+ font-weight: 600;
86
+ color: #1a202c;
87
+ margin-bottom: 0.75rem;
88
+ }
89
+ .nigeria-accent {
90
+ height: 4px;
91
+ background: linear-gradient(90deg, #008751 33%, #ffffff 33%, #ffffff 66%, #008751 66%);
92
+ border-radius: 2px;
93
+ margin: 0.5rem auto 1.2rem auto;
94
+ max-width: 320px;
95
+ }
96
+
97
+ /* Cards */
98
+ .feature-card {
99
+ background-color: #ffffff;
100
+ border-radius: 0.6rem;
101
+ padding: 1.2rem;
102
+ margin-bottom: 0.8rem;
103
+ border: 1px solid #e2e8f0;
104
+ box-shadow: 0 2px 6px rgba(0,0,0,0.04);
105
+ transition: transform 0.2s ease;
106
+ }
107
+ .feature-card:hover {
108
+ transform: translateY(-2px);
109
+ box-shadow: 0 4px 12px rgba(0,0,0,0.08);
110
+ }
111
+ .clinical-card {
112
+ background-color: #f7fafc;
113
+ border-left: 4px solid #008751;
114
+ padding: 0.9rem 1.1rem;
115
+ border-radius: 0.35rem;
116
+ margin: 0.5rem 0;
117
+ color: #2d3748;
118
+ }
119
+ .evidence-card {
120
+ background-color: #f0fdf4;
121
+ border-left: 4px solid #16a34a;
122
+ padding: 0.9rem 1.1rem;
123
+ border-radius: 0.35rem;
124
+ margin: 0.5rem 0;
125
+ font-size: 0.92rem;
126
+ }
127
+ .safety-alert-card {
128
+ background-color: #fef2f2;
129
+ border-left: 5px solid #dc2626;
130
+ padding: 1.2rem;
131
+ border-radius: 0.5rem;
132
+ margin: 0.8rem 0;
133
+ color: #991b1b;
134
+ }
135
+
136
+ /* Buttons */
137
+ .stButton > button {
138
+ width: 100%;
139
+ background-color: #008751;
140
+ color: white;
141
+ font-weight: 600;
142
+ border-radius: 0.4rem;
143
+ border: none;
144
+ padding: 0.5rem 1rem;
145
+ transition: all 0.25s ease;
146
+ }
147
+ .stButton > button:hover {
148
+ background-color: #006640;
149
+ color: white;
150
+ transform: translateY(-1px);
151
+ box-shadow: 0 4px 8px rgba(0,0,0,0.12);
152
+ }
153
+
154
+ /* Contact Links */
155
+ .contact-button {
156
+ display: block;
157
+ text-align: center;
158
+ padding: 0.45rem 1rem;
159
+ margin: 0.25rem 0;
160
+ border-radius: 0.35rem;
161
+ text-decoration: none;
162
+ font-weight: 600;
163
+ font-size: 0.85rem;
164
+ }
165
+ .contact-whatsapp {
166
+ background-color: #25D366;
167
+ color: white !important;
168
+ }
169
+ .contact-email {
170
+ background-color: #4a5568;
171
+ color: white !important;
172
+ }
173
+
174
+ /* Chat bubble styling */
175
+ .chat-user {
176
+ background-color: #e6f4ea;
177
+ color: #1a202c;
178
+ padding: 0.8rem 1rem;
179
+ border-radius: 0.75rem 0.75rem 0.1rem 0.75rem;
180
+ margin: 0.4rem 0;
181
+ max-width: 85%;
182
+ margin-left: auto;
183
+ }
184
+ .chat-assistant {
185
+ background-color: #ffffff;
186
+ color: #1a202c;
187
+ border: 1px solid #e2e8f0;
188
+ padding: 0.9rem 1.1rem;
189
+ border-radius: 0.75rem 0.75rem 0.75rem 0.1rem;
190
+ margin: 0.4rem 0;
191
+ max-width: 88%;
192
+ box-shadow: 0 1px 4px rgba(0,0,0,0.03);
193
+ }
194
+
195
+ /* Disclaimer */
196
+ .disclaimer {
197
+ font-size: 0.82rem;
198
+ color: #718096;
199
+ font-style: italic;
200
+ margin-top: 2rem;
201
+ padding: 1rem;
202
+ border-top: 1px solid #e2e8f0;
203
+ text-align: center;
204
+ }
205
+ </style>
206
+ """, unsafe_allow_html=True)
207
+
208
+ # ============================================
209
+ # SHARED CORE SINGLETONS & SESSION STATE
210
+ # ============================================
211
+ @st.cache_resource
212
+ def get_shared_core():
213
+ """Initializes and caches the shared HeedX core engines"""
214
+ qualitative_engine = QualitativeAnalysisEngine()
215
+ rag_engine = RAGEngine()
216
+ safety_layer = SafetyLayer()
217
+ recommendation_engine = RecommendationEngine()
218
+ return qualitative_engine, rag_engine, safety_layer, recommendation_engine
219
+
220
+
221
+ def init_session_state():
222
+ """Initializes session variables with clean state defaults"""
223
+ defaults = {
224
+ 'page': 'home', # 'home', 'mode_a', 'mode_b', 'resources'
225
+ 'gemini_api_key': '',
226
+ 'case_text': '',
227
+ 'case_analysis': None,
228
+ 'case_evidence': [],
229
+ 'case_formulation': '',
230
+ 'conversation_manager': ConversationStateManager(),
231
+ 'chat_messages': [],
232
+ 'active_crisis_banner': None,
233
+ 'tracker': SessionTracker(),
234
+ 'uploader_id': 0,
235
+ }
236
+ for k, v in defaults.items():
237
+ if k not in st.session_state:
238
+ st.session_state[k] = v
239
+
240
+ # Resolve API Key
241
+ if not st.session_state.gemini_api_key:
242
+ try:
243
+ st.session_state.gemini_api_key = st.secrets.get("GEMINI_API_KEY", "")
244
+ except Exception:
245
+ pass
246
+ if not st.session_state.gemini_api_key:
247
+ st.session_state.gemini_api_key = os.environ.get("GEMINI_API_KEY", "")
248
+
249
+
250
+ # ============================================
251
+ # LLM SERVICE (GEMINI WITH ROBUST FALLBACK)
252
+ # ============================================
253
+ GEMINI_MODEL = "gemini-3.8-flash"
254
+
255
+ def call_gemini_service(
256
+ messages: List[Dict[str, str]],
257
+ api_key: str,
258
+ system_instruction: Optional[str] = None,
259
+ temperature: float = 0.5,
260
+ max_tokens: int = 1000
261
+ ) -> str:
262
+ """
263
+ Calls Google Gemini via SDK or direct REST with error handling.
264
+ """
265
+ if not api_key or not str(api_key).strip():
266
+ return (
267
+ "Gemini API key is not configured. "
268
+ "Please provide a Gemini API key in the sidebar or in `.streamlit/secrets.toml`."
269
+ )
270
+
271
+ api_key = str(api_key).strip()
272
+
273
+ # Strategy 1: google.generativeai SDK
274
+ if genai is not None:
275
+ try:
276
+ genai.configure(api_key=api_key)
277
+ model_kwargs = {"model_name": GEMINI_MODEL}
278
+ if system_instruction:
279
+ model_kwargs["system_instruction"] = system_instruction
280
+ if hasattr(genai, "types") and hasattr(genai.types, "GenerationConfig"):
281
+ model_kwargs["generation_config"] = genai.types.GenerationConfig(
282
+ temperature=temperature,
283
+ max_output_tokens=max_tokens,
284
+ thinking_config=genai.types.ThinkingConfig(thinking_budget=0)
285
+ )
286
+ model = genai.GenerativeModel(**model_kwargs)
287
+
288
+ chat_history = []
289
+ current_prompt = "Hello"
290
+ for m in messages:
291
+ role = m.get("role", "")
292
+ content = m.get("content", "")
293
+ if role in ["user", "human"]:
294
+ chat_history.append({"role": "user", "parts": [content]})
295
+ elif role in ["assistant", "model", "bot"]:
296
+ chat_history.append({"role": "model", "parts": [content]})
297
+
298
+ if chat_history and chat_history[-1]["role"] == "user":
299
+ current_prompt = chat_history.pop()["parts"][0]
300
+
301
+ chat = model.start_chat(history=chat_history)
302
+ response = chat.send_message(current_prompt)
303
+ if response and response.text:
304
+ return response.text.strip()
305
+ except Exception:
306
+ pass # Fallback to direct REST
307
+
308
+ # Strategy 2: Direct REST endpoint (zero dependency, highly reliable)
309
+ try:
310
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent?key={api_key}"
311
+ headers = {"Content-Type": "application/json"}
312
+
313
+ contents_payload = []
314
+ for m in messages:
315
+ role = "user" if m.get("role") in ["user", "human"] else "model"
316
+ contents_payload.append({
317
+ "role": role,
318
+ "parts": [{"text": m.get("content", "")}]
319
+ })
320
+
321
+ body = {
322
+ "contents": contents_payload,
323
+ "generationConfig": {
324
+ "temperature": temperature,
325
+ "maxOutputTokens": max_tokens,
326
+ "thinkingConfig": {"thinkingBudget": 0}
327
+ }
328
+ }
329
+ if system_instruction:
330
+ body["system_instruction"] = {
331
+ "parts": [{"text": system_instruction}]
332
+ }
333
+
334
+ resp = requests.post(url, headers=headers, json=body, timeout=30)
335
+ if resp.status_code == 200:
336
+ data = resp.json()
337
+ candidates = data.get("candidates", [])
338
+ if candidates:
339
+ cand = candidates[0]
340
+ parts = cand.get("content", {}).get("parts", [])
341
+ if parts and "text" in parts[0]:
342
+ return parts[0]["text"].strip()
343
+ return "No response text generated from the service."
344
+ else:
345
+ return f"Gemini API returned status {resp.status_code}: {resp.text[:180]}"
346
+ except Exception as err:
347
+ return f"Service connection error: {err}"
348
+
349
+
350
+ # ============================================
351
+ # SIDEBAR NAVIGATION & CONTACTS
352
+ # ============================================
353
+ def render_sidebar():
354
+ """Renders the persistent application sidebar"""
355
+ with st.sidebar:
356
+ st.markdown(
357
+ "<div style='text-align:center;padding:0.4rem 0;'>"
358
+ "<span style='font-size:1.6rem;font-weight:700;color:#008751;'>HeedX AI</span><br>"
359
+ "<span style='font-size:0.8rem;color:#718096;letter-spacing:0.5px;'>Nigerian Mental Health Intelligence</span>"
360
+ "</div>",
361
+ unsafe_allow_html=True
362
+ )
363
+ st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
364
+
365
+ st.markdown("### Navigation")
366
+ if st.button("🏠 Overview & Home", use_container_width=True):
367
+ st.session_state.page = 'home'
368
+ st.rerun()
369
+
370
+ if st.button("📋 Mode A: Professional Case Analysis", use_container_width=True):
371
+ st.session_state.page = 'mode_a'
372
+ st.rerun()
373
+
374
+ if st.button("💬 Mode B: Conversational Support", use_container_width=True):
375
+ st.session_state.page = 'mode_b'
376
+ st.rerun()
377
+
378
+ if st.button("📍 Nigerian Support Resources", use_container_width=True):
379
+ st.session_state.page = 'resources'
380
+ st.rerun()
381
+
382
+ st.markdown("---")
383
+
384
+ # API Key Configuration
385
+ #with st.expander("🔑 Gemini API Settings", expanded=not bool(st.session_state.gemini_api_key)):
386
+ #st.caption("Required for LLM Case Formulations and Dynamic Chat.")
387
+ #new_key = st.text_input(
388
+ #"Gemini API Key",
389
+ #value=st.session_state.gemini_api_key,
390
+ #type="password",
391
+ #placeholder="AIzaSy..."
392
+ #)
393
+ #if st.button("Save API Key", use_container_width=True):
394
+ #st.session_state.gemini_api_key = new_key.strip()
395
+ #st.success("API Key saved.")
396
+
397
+ # Crisis Emergency Quick Card
398
+ with st.expander("🚨 Nigerian Crisis Lines", expanded=False):
399
+ st.markdown("""
400
+ - **National Emergency**: `112`
401
+ - **MANI Hotline**: `08062106493`
402
+ - **She Writes Woman**: `08099769974`
403
+ - **Lagos State Helpline**: `767`
404
+ """)
405
+
406
+ # Confidentiality & Support Contacts
407
+ st.markdown("### Confidential Connect")
408
+ st.markdown(
409
+ f"<a href='{CONTACT_INFO['whatsapp_link']}' target='_blank' class='contact-button contact-whatsapp'>"
410
+ "Direct WhatsApp Support</a>",
411
+ unsafe_allow_html=True
412
+ )
413
+ st.markdown(
414
+ f"<a href='mailto:{CONTACT_INFO['email']}' class='contact-button contact-email'>"
415
+ "Email Clinical Team</a>",
416
+ unsafe_allow_html=True
417
+ )
418
+
419
+ st.caption("Privacy Guarantee: Observations and conversation data reside only within your current browser session.")
420
+
421
+
422
+ # ============================================
423
+ # PAGE 1: OVERVIEW & HOME
424
+ # ============================================
425
+ def render_home_page():
426
+ """Landing view introducing the two-mode architecture and principles"""
427
+ st.markdown("<h1 class='main-header'>HeedX AI</h1>", unsafe_allow_html=True)
428
+ st.markdown("<p class='main-subtitle'>Nigerian Mental Wellness & Clinical Decision Support</p>", unsafe_allow_html=True)
429
+ st.markdown("<p class='main-tagline'>Evidence-Grounded • Culturally Attuned • Qualitative Understanding</p>", unsafe_allow_html=True)
430
+ st.markdown("<div class='nigeria-accent'></div>", unsafe_allow_html=True)
431
+
432
+ col_info, col_modes = st.columns([1, 1], gap="large")
433
+
434
+ with col_info:
435
+ st.markdown("""
436
+ ### Why Qualitative Understanding Matters
437
+ Most conventional AI mental health tools attempt to compress complex human suffering into artificial percentage scores (e.g., *Depression = 78%*). Clinical mental healthcare does not operate on synthetic probabilities.
438
+
439
+ **HeedX AI replaces artificial percentages with qualitative clinical understanding:**
440
+ - **Presenting concerns and symptoms** extracted directly from natural language.
441
+ - **Sociocultural context recognition** (academic strikes, economic pressures, family dynamics, stigma).
442
+ - **Evidence grounding (RAG)** referencing peer-reviewed Nigerian epidemiological research and national surveys.
443
+ - **Deterministic safety safeguards** guaranteeing immediate emergency contacts for acute distress.
444
+ """)
445
+
446
+ # Nigerian proverb banner
447
+ proverb = random.choice(NIGERIAN_PROVERBS)
448
+ st.info(f"💡 *Nigerian Wisdom:* \"{proverb}\"")
449
+
450
+ with col_modes:
451
+ st.markdown("### Choose an Operation Mode")
452
+
453
+ # Mode A Card
454
+ st.markdown("""
455
+ <div class='feature-card'>
456
+ <h4 style='color:#008751;margin-top:0;'>📋 Mode A: Professional Case Analysis</h4>
457
+ <p style='color:#4a5568;font-size:0.92rem;'>
458
+ Designed for psychologists, clinical researchers, counsellors, and case officers.
459
+ Upload or paste patient notes to perform structured qualitative extraction, retrieve Nigerian clinical literature, and generate comprehensive case formulations.
460
+ </p>
461
+ </div>
462
+ """, unsafe_allow_html=True)
463
+ if st.button("Enter Mode A (Professional)", use_container_width=True):
464
+ st.session_state.page = 'mode_a'
465
+ st.rerun()
466
+
467
+ st.markdown("<br>", unsafe_allow_html=True)
468
+
469
+ # Mode B Card
470
+ st.markdown("""
471
+ <div class='feature-card'>
472
+ <h4 style='color:#008751;margin-top:0;'>💬 Mode B: Conversational Support (User Chat)</h4>
473
+ <p style='color:#4a5568;font-size:0.92rem;'>
474
+ Designed for individuals seeking supportive, private conversation.
475
+ Speak freely about what you are going through. HeedX maintains conversational context over turns and offers culturally sensitive, empathetic guidance without making clinical diagnostic claims.
476
+ </p>
477
+ </div>
478
+ """, unsafe_allow_html=True)
479
+ if st.button("Enter Mode B (Conversational Chat)", use_container_width=True):
480
+ st.session_state.page = 'mode_b'
481
+ st.rerun()
482
+
483
+
484
+ # ============================================
485
+ # PAGE 2: MODE A — PROFESSIONAL CASE ANALYSIS
486
+ # ============================================
487
+ def render_mode_a_page(qa_engine: QualitativeAnalysisEngine, rag_engine: RAGEngine, safety_layer: SafetyLayer):
488
+ """
489
+ Mode A — Professional / Case Analysis:
490
+ - Text upload (PDF/TXT) or paste
491
+ - Qualitative extraction (concerns, duration, functioning, stressors, risks)
492
+ - Grounded RAG retrieval of Nigerian evidence
493
+ - LLM-generated structured case formulation with citations
494
+ """
495
+ st.markdown("<h2 class='sub-header'>📋 Mode A: Professional Case Analysis</h2>", unsafe_allow_html=True)
496
+ st.markdown(
497
+ "<p style='color:#4a5568;margin-top:-0.4rem;'>"
498
+ "Qualitative clinical case formulation and evidence retrieval for mental health professionals and researchers."
499
+ "</p>",
500
+ unsafe_allow_html=True
501
+ )
502
+
503
+ col_input, col_meta = st.columns([2, 1], gap="medium")
504
+
505
+ with col_input:
506
+ # Document Upload
507
+ uploaded_doc = st.file_uploader(
508
+ "Upload clinical note or observation (.pdf, .txt)",
509
+ type=['pdf', 'txt'],
510
+ key=f"mode_a_uploader_{st.session_state.uploader_id}"
511
+ )
512
+ if uploaded_doc is not None:
513
+ try:
514
+ if uploaded_doc.name.endswith('.pdf'):
515
+ reader = pypdf.PdfReader(uploaded_doc)
516
+ extracted_text = "\n".join([page.extract_text() or "" for page in reader.pages])
517
+ else:
518
+ extracted_text = uploaded_doc.read().decode('utf-8', errors='ignore')
519
+ st.session_state.case_text = extracted_text.strip()
520
+ st.success(f"Loaded '{uploaded_doc.name}' ({len(st.session_state.case_text)} characters).")
521
+ except Exception as e:
522
+ st.error(f"Error parsing uploaded document: {e}")
523
+
524
+ # Direct Text Input Area
525
+ case_input = st.text_area(
526
+ "Patient / Client Case Observation",
527
+ value=st.session_state.case_text,
528
+ height=200,
529
+ placeholder="Example: The patient reports feeling persistently sad for approximately one month. She has difficulty sleeping, has withdrawn from friends, and is struggling to concentrate at university..."
530
+ )
531
+
532
+ col_btn1, col_btn2 = st.columns([2, 1])
533
+ with col_btn1:
534
+ run_analysis = st.button("Run Qualitative Case Formulation", use_container_width=True)
535
+ with col_btn2:
536
+ if st.button("Clear Case", use_container_width=True):
537
+ st.session_state.case_text = ""
538
+ st.session_state.case_analysis = None
539
+ st.session_state.case_evidence = []
540
+ st.session_state.case_formulation = ""
541
+ st.session_state.uploader_id += 1
542
+ st.rerun()
543
+
544
+ with col_meta:
545
+ st.markdown("""
546
+ <div class='clinical-card'>
547
+ <strong>Clinical Guidelines (Mode A):</strong><br>
548
+ • Analyzes supplied observations qualitatively.<br>
549
+ • No synthetic percentages or probabilistic diagnoses.<br>
550
+ • Cross-references Nigerian epidemiological studies.<br>
551
+ • Formulates structured clinical insights for clinician decision support.
552
+ </div>
553
+ """, unsafe_allow_html=True)
554
+
555
+ st.caption("Sample Case for Quick Testing:")
556
+ if st.button("Load University Case Example", use_container_width=True):
557
+ st.session_state.case_text = (
558
+ "The patient is a 21-year-old female university undergraduate who reports feeling "
559
+ "persistently sad and empty for approximately one month. She describes significant "
560
+ "sleep difficulty, waking at 3:00 AM with racing thoughts about exams and tuition fees. "
561
+ "She has withdrawn from her study group and stopped attending fellowship gatherings. "
562
+ "She complains that her 'head is hot' and she cannot concentrate on lecture notes. "
563
+ "No active suicidal plan is reported, but she expresses feeling overwhelmed and tired of life."
564
+ )
565
+ st.rerun()
566
+
567
+ # Execution Pipeline
568
+ if run_analysis:
569
+ if not case_input.strip():
570
+ st.warning("Please enter or upload patient text to analyze.")
571
+ return
572
+
573
+ st.session_state.case_text = case_input.strip()
574
+
575
+ with st.spinner("Extracting qualitative dimensions and querying Nigerian evidence base..."):
576
+ # Step 1: Qualitative Feature Extraction
577
+ analysis = qa_engine.analyze(st.session_state.case_text)
578
+ st.session_state.case_analysis = analysis
579
+
580
+ # Step 2: Safety Check
581
+ safety_eval = safety_layer.evaluate_message(st.session_state.case_text)
582
+
583
+ # Step 3: Targeted RAG Retrieval
584
+ rag_query = rag_engine.construct_query(
585
+ current_text=st.session_state.case_text,
586
+ concerns=analysis.get("presenting_concerns"),
587
+ symptoms=analysis.get("symptoms_or_signals"),
588
+ stressors=analysis.get("stressors"),
589
+ context=analysis.get("social_context")
590
+ )
591
+ evidence = rag_engine.search(rag_query, top_k=3)
592
+ st.session_state.case_evidence = evidence
593
+
594
+ # Step 4: Structured Case Formulation via LLM
595
+ evidence_prompt_block = rag_engine.format_evidence_for_prompt(evidence)
596
+ system_prompt = f"""You are the HeedX Clinical Case Formulation Assistant. You assist licensed Nigerian psychologists, psychiatrists, and clinical researchers in conducting qualitative case formulation.
597
+
598
+ MANDATORY RULES:
599
+ 1. Provide a rigorous, structured qualitative formulation.
600
+ 2. NEVER output synthetic diagnostic percentages (e.g., do NOT output 'Depression = 78%').
601
+ 3. Distinguish clearly between explicitly stated facts, semantic observations, and clinical uncertainties.
602
+ 4. Reference the provided Nigerian epidemiological evidence and clinical literature where relevant.
603
+ 5. Structure your output clearly according to the following sections:
604
+ - CASE SUMMARY
605
+ - PRESENTING CONCERNS & REPORTED SIGNALS
606
+ - DURATION & TRAJECTORY
607
+ - FUNCTIONAL & SOCIO-ACADEMIC IMPACT
608
+ - STRESSORS & CONTEXTUAL FACTORS (Nigerian context)
609
+ - RISK INDICATORS & SAFETY CONSIDERATIONS
610
+ - PROTECTIVE FACTORS & RESILIENCE
611
+ - RELEVANT RESEARCH EVIDENCE & GROUNDING (Cite retrieved studies)
612
+ - SUGGESTED CLINICAL INQUIRIES FOR FURTHER ASSESSMENT
613
+ """
614
+ user_prompt = f"""PATIENT OBSERVATION:
615
+ {st.session_state.case_text}
616
+
617
+ STRUCTURED QUALITATIVE EXTRACTION:
618
+ - Presenting Concerns: {analysis.get('presenting_concerns')}
619
+ - Symptoms/Signals: {analysis.get('symptoms_or_signals')}
620
+ - Duration: {analysis.get('duration')}
621
+ - Stressors: {analysis.get('stressors')}
622
+ - Functional Impact: {analysis.get('functional_impact')}
623
+ - Protective Factors: {analysis.get('protective_factors')}
624
+ - Risk Signals: {analysis.get('risk_signals')}
625
+
626
+ {evidence_prompt_block}
627
+
628
+ Please generate the formal qualitative case formulation for the mental health professional."""
629
+
630
+ formulation = call_gemini_service(
631
+ messages=[{"role": "user", "content": user_prompt}],
632
+ api_key=st.session_state.gemini_api_key,
633
+ system_instruction=system_prompt,
634
+ temperature=0.4,
635
+ max_tokens=1200
636
+ )
637
+ st.session_state.case_formulation = formulation
638
+
639
+ # Display Results if Analysis Exists
640
+ if st.session_state.case_analysis:
641
+ analysis = st.session_state.case_analysis
642
+ st.markdown("---")
643
+ st.markdown("### 1. Qualitative Information Extraction")
644
+
645
+ c1, c2, c3 = st.columns(3)
646
+ with c1:
647
+ st.markdown("**Presenting Concerns**")
648
+ for c in analysis.get("presenting_concerns", []):
649
+ st.markdown(f"• {c}")
650
+ st.markdown("**Duration**")
651
+ st.markdown(f"• {analysis.get('duration')}")
652
+
653
+ with c2:
654
+ st.markdown("**Symptoms & Signals**")
655
+ for s in analysis.get("symptoms_or_signals", []):
656
+ st.markdown(f"• {s}")
657
+ st.markdown("**Functional Impact**")
658
+ for f in analysis.get("functional_impact", []):
659
+ st.markdown(f"• {f}")
660
+
661
+ with c3:
662
+ st.markdown("**Stressors & Context**")
663
+ for st_item in analysis.get("stressors", []):
664
+ st.markdown(f"• {st_item}")
665
+ st.markdown("**Risk Indicators**")
666
+ risks = analysis.get("risk_signals", [])
667
+ if risks:
668
+ for r in risks:
669
+ st.markdown(f"<span style='color:#dc2626;'>⚠️ {r}</span>", unsafe_allow_html=True)
670
+ else:
671
+ st.markdown("• *No explicit acute crisis triggers detected in text*")
672
+
673
+ # Grounding Evidence (RAG)
674
+ st.markdown("### 2. Retrieved Nigerian Evidence & Clinical Guidance")
675
+ if st.session_state.case_evidence:
676
+ for ev in st.session_state.case_evidence:
677
+ st.markdown(f"""
678
+ <div class='evidence-card'>
679
+ <strong>{ev.get('title')}</strong> ({ev.get('year')})<br>
680
+ <span style='color:#4a5568;'>Source: {ev.get('source')} | Authors: {ev.get('authors')}</span><br>
681
+ <span style='color:#166534;'>Evidence Level: {ev.get('evidence_level')} | Population: {ev.get('population')}</span><br>
682
+ <p style='margin-top:0.4rem;color:#1e293b;'>{ev.get('text')}</p>
683
+ </div>
684
+ """, unsafe_allow_html=True)
685
+ else:
686
+ st.caption("No specific evidence records matched.")
687
+
688
+ # Structured Case Formulation Output
689
+ st.markdown("### 3. Comprehensive Clinical Case Formulation")
690
+ if st.session_state.case_formulation:
691
+ st.markdown(st.session_state.case_formulation)
692
+
693
+ # Export / Download Case Formulation
694
+ st.download_button(
695
+ "📥 Download Case Formulation (.md)",
696
+ data=f"# HeedX AI Qualitative Case Formulation\nDate: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n## Patient Observation\n{st.session_state.case_text}\n\n## Clinical Formulation\n{st.session_state.case_formulation}",
697
+ file_name=f"heedx_case_formulation_{datetime.now().strftime('%Y%m%d_%H%M')}.md",
698
+ mime="text/markdown",
699
+ use_container_width=True
700
+ )
701
+ else:
702
+ st.info("API key required to generate full clinical case formulation. Please set your Gemini API key in the sidebar.")
703
+
704
+
705
+ # ============================================
706
+ # PAGE 3: MODE B — CONVERSATIONAL USER MODE
707
+ # ============================================
708
+ def render_mode_b_page(
709
+ qa_engine: QualitativeAnalysisEngine,
710
+ rag_engine: RAGEngine,
711
+ safety_layer: SafetyLayer,
712
+ rec_engine: RecommendationEngine
713
+ ):
714
+ """
715
+ Mode B — Conversational User Mode:
716
+ - Empathetic chat interface
717
+ - Multi-turn conversation state tracking
718
+ - Dedicated safety layer with emergency intercept
719
+ - Targeted RAG retrieval based on evolving conversation context
720
+ - Grounded, non-diagnostic response generation
721
+ """
722
+ st.markdown("<h2 class='sub-header'>💬 Mode B: Conversational Support</h2>", unsafe_allow_html=True)
723
+ st.markdown(
724
+ "<p style='color:#4a5568;margin-top:-0.4rem;'>"
725
+ "Safe, empathetic mental wellness dialogue. HeedX listens, remembers context across turns, and offers evidence-informed support."
726
+ "</p>",
727
+ unsafe_allow_html=True
728
+ )
729
+
730
+ cstate: ConversationStateManager = st.session_state.conversation_manager
731
+
732
+ # Display Active Safety Alert if Acute Crisis detected
733
+ if st.session_state.active_crisis_banner:
734
+ st.markdown(f"""
735
+ <div class='safety-alert-card'>
736
+ <h3 style='margin-top:0;'>🚨 Immediate Help is Available</h3>
737
+ <p>{st.session_state.active_crisis_banner}</p>
738
+ <strong>Verified Nigerian Emergency Support:</strong><br>
739
+ • National Emergency: <strong>112</strong><br>
740
+ • Mentally Aware Nigeria Initiative (MANI): <strong>08062106493</strong><br>
741
+ • She Writes Woman Helpline: <strong>08099769974</strong><br>
742
+ • Federal Neuropsychiatric Hospital, Yaba: <strong>08023126786</strong>
743
+ </div>
744
+ """, unsafe_allow_html=True)
745
+
746
+ # Conversation State Expander (Transparent AI)
747
+ with st.expander("🔍 Conversation Context & Themes Understood (State Tracker)", expanded=False):
748
+ state_dict = cstate.get_state_dict()
749
+ col_s1, col_s2, col_s3 = st.columns(3)
750
+ with col_s1:
751
+ st.markdown(f"**Concerns Identified:** {', '.join(state_dict['main_concerns']) or 'None yet'}")
752
+ st.markdown(f"**Duration:** {state_dict['duration'] or 'Not specified'}")
753
+ with col_s2:
754
+ st.markdown(f"**Stressors:** {', '.join(state_dict['stressors']) or 'None yet'}")
755
+ st.markdown(f"**Functional Impact:** {', '.join(state_dict['functional_impact']) or 'None yet'}")
756
+ with col_s3:
757
+ st.markdown(f"**Safety Status:** `{state_dict['risk_status']}`")
758
+ st.markdown(f"**Dialogue Turns:** {cstate.turn_count}")
759
+
760
+ # Chat Transcript Display
761
+ chat_container = st.container()
762
+ with chat_container:
763
+ if not st.session_state.chat_messages:
764
+ st.markdown("""
765
+ <div class='chat-assistant'>
766
+ Hello, I am HeedX. I am here to provide a safe, non-judgmental space to talk about whatever is on your mind — whether it is stress, feeling overwhelmed, sleep difficulties, or school/family pressures.<br><br>
767
+ How have you been feeling lately?
768
+ </div>
769
+ """, unsafe_allow_html=True)
770
+
771
+ for msg in st.session_state.chat_messages:
772
+ if msg["role"] == "user":
773
+ st.markdown(f"<div class='chat-user'>{html_lib.escape(msg['content'])}</div>", unsafe_allow_html=True)
774
+ else:
775
+ st.markdown(f"<div class='chat-assistant'>{msg['content']}</div>", unsafe_allow_html=True)
776
+
777
+ # Input Form
778
+ with st.form("mode_b_chat_form", clear_on_submit=True):
779
+ user_message = st.text_input("Type your message here...", placeholder="Share what is on your mind...")
780
+ col_send, col_reset = st.columns([4, 1])
781
+ with col_send:
782
+ submitted = st.form_submit_button("Send Message", use_container_width=True)
783
+ with col_reset:
784
+ reset_btn = st.form_submit_button("Reset Chat", use_container_width=True)
785
+
786
+ if reset_btn:
787
+ st.session_state.chat_messages = []
788
+ st.session_state.conversation_manager.clear()
789
+ st.session_state.active_crisis_banner = None
790
+ st.rerun()
791
+
792
+ if submitted and user_message.strip():
793
+ clean_msg = user_message.strip()
794
+
795
+ # Append user message to transcript
796
+ st.session_state.chat_messages.append({"role": "user", "content": clean_msg})
797
+
798
+ # Step 1: Explicit Safety Layer Triage
799
+ safety_eval = safety_layer.evaluate_message(clean_msg)
800
+
801
+ if safety_eval.get("is_crisis"):
802
+ st.session_state.active_crisis_banner = (
803
+ "You mentioned feelings of severe distress or self-harm. "
804
+ "Your life and safety are deeply important. Please reach out to someone who can support you right now."
805
+ )
806
+ emergency_reply = (
807
+ safety_eval.get("emergency_response") or
808
+ "What you've shared indicates deep pain. You do not have to carry this alone. "
809
+ "Please call 112 (National Emergency) or MANI on 08062106493 right now. "
810
+ "Is there a family member, trusted friend, or doctor you can reach out to immediately?"
811
+ )
812
+ st.session_state.chat_messages.append({"role": "assistant", "content": emergency_reply})
813
+ cstate.state["risk_status"] = "acute_crisis"
814
+ st.rerun()
815
+
816
+ # Step 2: Update Conversation State
817
+ cstate.update_state(clean_msg, qa_engine, safety_layer)
818
+
819
+ # Step 3: Targeted RAG Retrieval using accumulated state
820
+ rag_query = cstate.get_retrieval_query(clean_msg)
821
+ evidence = rag_engine.search(rag_query, top_k=2)
822
+
823
+ # Format evidence for injection into conversational model
824
+ evidence_block = ""
825
+ if evidence:
826
+ evidence_block = "RELEVANT LOCAL CLINICAL CONTEXT:\n"
827
+ for ev in evidence:
828
+ evidence_block += f"- {ev.get('title')}: {ev.get('text')}\n"
829
+
830
+ # Step 4: LLM Conversational Generation
831
+ system_instruction = f"""You are HeedX, an empathetic, culturally attuned Nigerian mental wellness companion.
832
+
833
+ CORE ETHICAL BOUNDARIES:
834
+ 1. NEVER diagnose the user. Do not say 'You have depression' or 'You suffer from anxiety'.
835
+ 2. Instead say: 'What you are describing includes experiences commonly associated with...' or 'These feelings often occur when carrying heavy strain.'
836
+ 3. Never use emojis. Keep a warm, respectful, grounding African conversational tone.
837
+ 4. Keep your response conversational and concise: between 3 and 5 sentences.
838
+ 5. Empathize with their specific situation (academic strain, family, fatigue, 'head is hot', sleep).
839
+ 6. Ground your response in healthy coping, and ask ONE thoughtful, open question to help them reflect.
840
+
841
+ {evidence_block}
842
+
843
+ CURRENT CONVERSATION STATE:
844
+ - Main Concerns: {cstate.state['main_concerns']}
845
+ - Duration: {cstate.state['duration']}
846
+ - Stressors: {cstate.state['stressors']}
847
+ - Functional Impact: {cstate.state['functional_impact']}
848
+ """
849
+ # Prepare message history for Gemini (last 8 turns for efficiency)
850
+ gemini_messages = []
851
+ for m in st.session_state.chat_messages[-8:]:
852
+ gemini_messages.append({
853
+ "role": "user" if m["role"] == "user" else "assistant",
854
+ "content": m["content"]
855
+ })
856
+
857
+ with st.spinner("HeedX is thinking..."):
858
+ assistant_reply = call_gemini_service(
859
+ messages=gemini_messages,
860
+ api_key=st.session_state.gemini_api_key,
861
+ system_instruction=system_instruction,
862
+ temperature=0.6,
863
+ max_tokens=1000
864
+
865
+ )
866
+
867
+ st.session_state.chat_messages.append({"role": "assistant", "content": assistant_reply})
868
+ st.rerun()
869
+
870
+
871
+ # ============================================
872
+ # PAGE 4: NIGERIAN RESOURCES DIRECTORY
873
+ # ============================================
874
+ def render_resources_page():
875
+ """Comprehensive, deterministic directory of verified Nigerian mental health resources"""
876
+ st.markdown("<h2 class='sub-header'>📍 Nigerian Mental Health Resources Directory</h2>", unsafe_allow_html=True)
877
+ st.markdown(
878
+ "<p style='color:#4a5568;margin-top:-0.4rem;'>"
879
+ "Verified, deterministic contacts, emergency services, psychiatric hospitals, and community helplines across Nigeria."
880
+ "</p>",
881
+ unsafe_allow_html=True
882
+ )
883
+
884
+ c1, c2 = st.columns(2)
885
+
886
+ with c1:
887
+ st.markdown("### 🚨 Emergency & Crisis Hotlines")
888
+ st.markdown("""
889
+ - **National Emergency Number**: `112` (Toll-free from any network)
890
+ - **Lagos State Emergency**: `767` or `112`
891
+ - **Mentally Aware Nigeria Initiative (MANI)**:
892
+ - Phone: `08062106493` / `08091116264`
893
+ - Focus: 24/7 Crisis triage, youth mental health, suicide prevention.
894
+ - **She Writes Woman**:
895
+ - Phone: `08099769974`
896
+ - Focus: Confidential 24/7 mental health crisis hotline.
897
+ - **Nigeria Suicide Prevention Helpline**: `08062106493`
898
+ """)
899
+
900
+
901
+ st.markdown("### 🤝 Faith & Community Support")
902
+
903
+ st.markdown(f"**{FAITH_COMMUNITY_SUPPORT['title']}**")
904
+
905
+ for resource in FAITH_COMMUNITY_SUPPORT["resources"]:
906
+ st.markdown(f"- {resource}")
907
+
908
+
909
+ with c2:
910
+ st.markdown("### 🏥 Federal Neuropsychiatric Hospitals")
911
+ st.markdown("""
912
+ - **Federal Neuropsychiatric Hospital, Yaba (Lagos)**
913
+ - Address: Harvey Road, Yaba, Lagos State
914
+ - Phone: `08023126786`
915
+ - **Neuropsychiatric Hospital, Aro, Abeokuta (Ogun State)**
916
+ - Address: Aro, Abeokuta, Ogun State
917
+ - Phone: `08033333333` (Hospital Registry)
918
+ - **Federal Neuropsychiatric Hospital, Barnawa (Kaduna State)**
919
+ - Address: Barnawa, Kaduna State
920
+ - **Federal Neuropsychiatric Hospital, Uselu (Benin City, Edo State)**
921
+ - Address: Uselu, Benin City
922
+ - **Federal Neuropsychiatric Hospital, Calabar (Cross River State)**
923
+ - Address: Calabar Road, Calabar
924
+ - **Federal Neuropsychiatric Hospital, Kware (Sokoto State)**
925
+ - Address: Kware, Sokoto State
926
+ """)
927
+
928
+ st.markdown("### 🌿 Evidence-Based Nigerian Wellness Tips")
929
+ for category, tips in CULTURAL_WELLNESS_TIPS.items():
930
+ with st.expander(tips['title']):
931
+ st.write(tips['message'])
932
+ for i, tip in enumerate(tips['tips'], 1):
933
+ st.write(f"{i}. {tip}")
934
+
935
+
936
+ # ============================================
937
+ # MAIN APPLICATION CONTROLLER
938
+ # ============================================
939
+ def main():
940
+ """Main application lifecycle and routing"""
941
+ init_session_state()
942
+
943
+ qa_engine, rag_engine, safety_layer, rec_engine = get_shared_core()
944
+
945
+ # Development Notice
946
+ st.info(
947
+ "🛡️ **HeedX AI 2.0**: Redesigned around the Two-Mode Architecture — "
948
+ "**Mode A (Professional Case Analysis)** and **Mode B (Conversational Support)** with a shared RAG and safety layer."
949
+ )
950
+
951
+ # Render Persistent Sidebar
952
+ render_sidebar()
953
+
954
+ # Page Dispatch
955
+ current_page = st.session_state.page
956
+
957
+ if current_page == 'home':
958
+ render_home_page()
959
+ elif current_page == 'mode_a':
960
+ render_mode_a_page(qa_engine, rag_engine, safety_layer)
961
+ elif current_page == 'mode_b':
962
+ render_mode_b_page(qa_engine, rag_engine, safety_layer, rec_engine)
963
+ elif current_page == 'resources':
964
+ render_resources_page()
965
+ else:
966
+ render_home_page()
967
+
968
+ # Footer
969
+ st.markdown("---")
970
+ st.markdown("""
971
+ <div class='disclaimer'>
972
+ <p><strong>HeedX AI &mdash; Nigerian Edition 2.0</strong></p>
973
+ <p>HeedX provides qualitative support, semantic analysis, and evidence-grounded information. It does not provide definitive medical or psychiatric diagnoses.</p>
974
+ <p>Crisis Lines: <strong>112</strong> (National Emergency) &nbsp;|&nbsp; <strong>08062106493</strong> (MANI) &nbsp;|&nbsp; <strong>08099769974</strong> (She Writes Woman)</p>
975
+ <p>You are never alone. Help and community are always available.</p>
976
+ </div>
977
+ """, unsafe_allow_html=True)
978
+
979
+
980
+ if __name__ == "__main__":
981
+ main()
migration_instruction.md ADDED
@@ -0,0 +1,1148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HeedX AI — Two-Mode Mental-Health AI Architecture
2
+
3
+ You are the primary AI software engineer working on **HeedX AI**, a Nigerian mental-health support and analysis application.
4
+
5
+ Your first responsibility is to **understand the existing codebase and architecture before changing it**.
6
+
7
+ Do not immediately rewrite the application.
8
+
9
+ Inspect the existing project, identify what is already working, and then redesign it around the architecture described below.
10
+
11
+ ---
12
+
13
+ # 1. CORE CONCEPT
14
+
15
+ HeedX has **TWO DISTINCT INPUT MODES**.
16
+
17
+ They must remain conceptually separate even though they can share the same underlying AI/RAG infrastructure.
18
+
19
+ ## Mode A — Professional / Case Analysis
20
+
21
+ This mode is intended for a psychologist, mental-health professional, researcher, or authorized user who already has patient/client text.
22
+
23
+ The professional can:
24
+
25
+ * upload a document
26
+ * paste patient/client text
27
+ * write patient/client text manually
28
+
29
+ HeedX then performs **qualitative analysis** of the supplied text.
30
+
31
+ Example:
32
+
33
+ > "The patient reports feeling persistently sad for approximately one month. She has difficulty sleeping, has withdrawn from friends, and is struggling to concentrate at university."
34
+
35
+ The system extracts and organizes information such as:
36
+
37
+ ```text
38
+ Presenting concerns
39
+ • persistent sadness
40
+ • sleep difficulty
41
+ • social withdrawal
42
+ • difficulty concentrating
43
+
44
+ Duration
45
+ • approximately one month
46
+
47
+ Context
48
+ • university/academic environment
49
+
50
+ Potentially relevant symptoms/signals
51
+ • low mood
52
+ • sleep disturbance
53
+ • reduced social engagement
54
+ • concentration difficulty
55
+
56
+ Risk information
57
+ • no suicidal ideation established from the supplied text
58
+ • further assessment may be appropriate
59
+ ```
60
+
61
+ This is **qualitative analysis**.
62
+
63
+ Do NOT turn this into:
64
+
65
+ ```text
66
+ Depression = 78%
67
+ Anxiety = 15%
68
+ Normal = 5%
69
+ Suicidal = 2%
70
+ ```
71
+
72
+ The system should not generate fake diagnostic probabilities.
73
+
74
+ ---
75
+
76
+ # 2. Mode B — Conversational User Mode
77
+
78
+ This mode is for a person directly interacting with HeedX.
79
+
80
+ The user communicates naturally:
81
+
82
+ > "I've been feeling really down lately."
83
+
84
+ Then:
85
+
86
+ > "It's been happening for a few weeks and I can't sleep properly."
87
+
88
+ Then:
89
+
90
+ > "University has also been stressful."
91
+
92
+ The system should maintain conversation context and continuously update its understanding.
93
+
94
+ Conceptually:
95
+
96
+ ```text
97
+ USER MESSAGE
98
+ ↓
99
+ UNDERSTAND CURRENT MESSAGE
100
+ ↓
101
+ UPDATE CONVERSATION STATE
102
+ ↓
103
+ RETRIEVE RELEVANT KNOWLEDGE
104
+ ↓
105
+ LLM
106
+ ↓
107
+ PERSONALIZED RESPONSE
108
+ ↓
109
+ USER CONTINUES
110
+ ↓
111
+ REPEAT
112
+ ```
113
+
114
+ This mode should feel like a natural conversation, NOT like filling out a questionnaire.
115
+
116
+ ---
117
+
118
+ # 3. VERY IMPORTANT: DO NOT ADD QUESTIONNAIRE SCREENING
119
+
120
+ For the current version, do NOT implement:
121
+
122
+ * PHQ-9
123
+ * GAD-7
124
+ * WHO-5
125
+ * Kessler
126
+ * questionnaire scoring
127
+ * questionnaire UI
128
+ * questionnaire-based diagnosis
129
+
130
+ This may be added in a future version.
131
+
132
+ The current system should primarily understand natural language.
133
+
134
+ ---
135
+
136
+ # 4. VERY IMPORTANT: OLD CLASSIFIER IS NO LONGER THE PRIMARY ENGINE
137
+
138
+ The existing application may contain a classical ML classifier with classes such as:
139
+
140
+ ```text
141
+ Normal
142
+ Anxiety
143
+ Depression
144
+ Suicidal
145
+ ```
146
+
147
+ The old architecture was approximately:
148
+
149
+ ```text
150
+ INPUT
151
+ ↓
152
+ CLASSICAL ML MODEL
153
+ ↓
154
+ class + probabilities
155
+ ↓
156
+ Python analysis
157
+ ↓
158
+ LLM
159
+ ↓
160
+ conversation
161
+ ```
162
+
163
+ This classifier should NOT be the primary inference mechanism in the redesigned system.
164
+
165
+ It may be retained for:
166
+
167
+ * experimentation
168
+ * research comparison
169
+ * benchmarking
170
+ * future development
171
+
172
+ But the production user experience should NOT depend on the four-class classifier.
173
+
174
+ The new architecture is based on **qualitative semantic understanding + retrieval + conversational generation**.
175
+
176
+ ---
177
+
178
+ # 5. TWO INPUTS, ONE SHARED INTELLIGENCE LAYER
179
+
180
+ The central architectural principle is:
181
+
182
+ ```text
183
+ HEEDX
184
+ │
185
+ ┌─────────┴─────────┐
186
+ │ │
187
+ ▼ ▼
188
+ PROFESSIONAL MODE CONVERSATION MODE
189
+ CASE ANALYSIS USER CHAT
190
+ │ │
191
+ ▼ ▼
192
+ Qualitative analysis Conversation
193
+ │ understanding
194
+ │ │
195
+ └─────────┬─────────┘
196
+ ▼
197
+ SHARED HEEDX CORE
198
+ │
199
+ ┌─────────────┼─────────────┐
200
+ │ │ │
201
+ ▼ ▼ ▼
202
+ Analysis RAG Safety
203
+ Engine Engine Layer
204
+ │ │ │
205
+ └─────────────┼─────────────┘
206
+ ▼
207
+ LLM
208
+ │
209
+ ┌────────┴────────┐
210
+ ▼ ▼
211
+ Case output User response
212
+ ```
213
+
214
+ Do NOT build two completely unrelated AI systems.
215
+
216
+ Build two input experiences that share common underlying services.
217
+
218
+ ---
219
+
220
+ # 6. WHAT "QUALITATIVE ANALYSIS" MEANS
221
+
222
+ The analysis engine should identify meaningful information from text rather than forcing it into mutually exclusive diagnostic categories.
223
+
224
+ Potential structured fields include:
225
+
226
+ ```json
227
+ {
228
+ "presenting_concerns": [],
229
+ "emotions": [],
230
+ "symptoms_or_signals": [],
231
+ "stressors": [],
232
+ "duration": null,
233
+ "functional_impact": [],
234
+ "social_context": [],
235
+ "protective_factors": [],
236
+ "risk_signals": [],
237
+ "support_needs": [],
238
+ "uncertainties": []
239
+ }
240
+ ```
241
+
242
+ This is an **information representation**, not a diagnosis.
243
+
244
+ For example:
245
+
246
+ ```json
247
+ {
248
+ "presenting_concerns": [
249
+ "persistent sadness"
250
+ ],
251
+ "symptoms_or_signals": [
252
+ "sleep difficulty",
253
+ "loss of interest",
254
+ "social withdrawal"
255
+ ],
256
+ "stressors": [
257
+ "academic pressure"
258
+ ],
259
+ "duration": "approximately three weeks",
260
+ "risk_signals": [],
261
+ "uncertainties": [
262
+ "suicidal ideation not established"
263
+ ]
264
+ }
265
+ ```
266
+
267
+ The system should distinguish between:
268
+
269
+ * explicitly stated information
270
+ * reasonable semantic interpretation
271
+ * information that remains unknown
272
+
273
+ Do not invent information that the user/patient did not provide.
274
+
275
+ ---
276
+
277
+ # 7. PROFESSIONAL / CASE ANALYSIS PIPELINE
278
+
279
+ The professional mode should follow:
280
+
281
+ ```text
282
+ PROFESSIONAL
283
+ │
284
+ ▼
285
+ Upload / Paste / Write Patient Text
286
+ │
287
+ ▼
288
+ Text Extraction
289
+ │
290
+ ▼
291
+ Qualitative Analysis
292
+ │
293
+ ├── concerns
294
+ ├── symptoms/signals
295
+ ├── emotions
296
+ ├── stressors
297
+ ├── duration
298
+ ├── functioning
299
+ ├── context
300
+ └── risk signals
301
+ │
302
+ ▼
303
+ Structured Case Representation
304
+ │
305
+ ▼
306
+ Retrieval Query Construction
307
+ │
308
+ ▼
309
+ Embedding
310
+ │
311
+ ▼
312
+ Vector Search
313
+ │
314
+ ▼
315
+ Relevant Evidence
316
+ │
317
+ ▼
318
+ LLM
319
+ │
320
+ ▼
321
+ Professional Case Summary / Evidence-Grounded Analysis
322
+ ```
323
+
324
+ The professional should be able to see the resulting analysis clearly.
325
+
326
+ ---
327
+
328
+ # 8. CONVERSATIONAL PIPELINE
329
+
330
+ The conversational mode should follow:
331
+
332
+ ```text
333
+ USER
334
+ │
335
+ ▼
336
+ Message
337
+ │
338
+ ▼
339
+ Conversation Understanding
340
+ │
341
+ ├── current concerns
342
+ ├── symptoms/signals
343
+ ├── emotions
344
+ ├── stressors
345
+ ├── duration
346
+ └── risk signals
347
+ │
348
+ ▼
349
+ Update Conversation State
350
+ │
351
+ ▼
352
+ Construct Retrieval Query
353
+ │
354
+ ▼
355
+ Embedding
356
+ │
357
+ ▼
358
+ Vector Search
359
+ │
360
+ ▼
361
+ Relevant Evidence
362
+ │
363
+ ▼
364
+ LLM
365
+ │
366
+ ▼
367
+ Natural Personalized Response
368
+ │
369
+ ▼
370
+ USER
371
+ ```
372
+
373
+ This process can repeat on every meaningful turn.
374
+
375
+ ---
376
+
377
+ # 9. CONVERSATION STATE
378
+
379
+ The conversational system should maintain a structured state.
380
+
381
+ Example:
382
+
383
+ ```json
384
+ {
385
+ "main_concerns": [
386
+ "persistent sadness",
387
+ "sleep difficulty",
388
+ "loss of interest"
389
+ ],
390
+ "duration": "approximately three weeks",
391
+ "stressors": [
392
+ "academic pressure",
393
+ "financial difficulty"
394
+ ],
395
+ "functional_impact": [
396
+ "difficulty concentrating"
397
+ ],
398
+ "risk_signals": [],
399
+ "risk_status": "not_established"
400
+ }
401
+ ```
402
+
403
+ The state must evolve as the user provides new information.
404
+
405
+ For example:
406
+
407
+ ### First message
408
+
409
+ > "I've been feeling down."
410
+
411
+ State:
412
+
413
+ ```text
414
+ low mood
415
+ ```
416
+
417
+ ### Second message
418
+
419
+ > "For about three weeks and I can't sleep."
420
+
421
+ State becomes:
422
+
423
+ ```text
424
+ low mood
425
+ +
426
+ three-week duration
427
+ +
428
+ sleep difficulty
429
+ ```
430
+
431
+ ### Third message
432
+
433
+ > "University has been stressful."
434
+
435
+ State becomes:
436
+
437
+ ```text
438
+ low mood
439
+ +
440
+ three-week duration
441
+ +
442
+ sleep difficulty
443
+ +
444
+ academic stress
445
+ ```
446
+
447
+ This state should help improve retrieval and personalization.
448
+
449
+ ---
450
+
451
+ # 10. EMBEDDINGS AND VECTORS
452
+
453
+ There are TWO sides to embeddings.
454
+
455
+ ## Static knowledge embeddings
456
+
457
+ Knowledge documents are processed before user interaction:
458
+
459
+ ```text
460
+ Research / Guidelines / Knowledge
461
+ ↓
462
+ Text extraction
463
+ ↓
464
+ Chunking
465
+ ↓
466
+ Embedding model
467
+ ↓
468
+ Vectors
469
+ ↓
470
+ Vector database
471
+ ```
472
+
473
+ These embeddings are relatively static.
474
+
475
+ ## User/query embeddings
476
+
477
+ When relevant user information needs to be retrieved:
478
+
479
+ ```text
480
+ Current user message
481
+ +
482
+ Conversation state
483
+ +
484
+ Structured signals
485
+ ↓
486
+ Retrieval query
487
+ ↓
488
+ Embedding model
489
+ ↓
490
+ Query vector
491
+ ↓
492
+ Vector similarity search
493
+ ```
494
+
495
+ The same compatible embedding model should be used for knowledge chunks and retrieval queries.
496
+
497
+ Remember:
498
+
499
+ > The vector does not contain the knowledge itself.
500
+
501
+ The actual knowledge remains in the stored document chunks.
502
+
503
+ The vector allows the system to find semantically related chunks.
504
+
505
+ ---
506
+
507
+ # 11. RETRIEVAL MUST USE THE USER'S INFORMATION
508
+
509
+ Do not build a RAG system where the user text is disconnected from retrieval.
510
+
511
+ The connection should be explicit:
512
+
513
+ ```text
514
+ USER TEXT
515
+ ↓
516
+ UNDERSTANDING
517
+ ↓
518
+ STRUCTURED SIGNALS
519
+ ↓
520
+ RETRIEVAL QUERY
521
+ ↓
522
+ EMBEDDING
523
+ ↓
524
+ VECTOR SEARCH
525
+ ↓
526
+ RELEVANT KNOWLEDGE
527
+ ```
528
+
529
+ For example:
530
+
531
+ User:
532
+
533
+ > "I haven't enjoyed football for weeks and I'm barely sleeping."
534
+
535
+ Possible retrieval representation:
536
+
537
+ ```text
538
+ loss of interest
539
+ sleep disturbance
540
+ persistent symptoms
541
+ reduced enjoyment
542
+ mental health
543
+ ```
544
+
545
+ The system then searches the knowledge base for semantically relevant evidence.
546
+
547
+ ---
548
+
549
+ # 12. DO NOT BLINDLY EMBED THE ENTIRE CONVERSATION
550
+
551
+ The system should not simply concatenate every historical message forever and embed everything blindly.
552
+
553
+ Instead use:
554
+
555
+ ```text
556
+ Current message
557
+ +
558
+ Relevant conversation state
559
+ +
560
+ Relevant context
561
+ +
562
+ Structured signals
563
+ ```
564
+
565
+ to construct the retrieval query.
566
+
567
+ The full conversation history can still be supplied to the LLM where appropriate.
568
+
569
+ Retrieval context and conversational context are related but are not identical.
570
+
571
+ ---
572
+
573
+ # 13. RAG KNOWLEDGE BASE
574
+
575
+ The knowledge base should be designed around reliable mental-health information, especially Nigerian/local context.
576
+
577
+ Suggested structure:
578
+
579
+ ```text
580
+ knowledge/
581
+ │
582
+ ├── nigeria_evidence/
583
+ │ ├── national/
584
+ │ ├── depression/
585
+ │ ├── anxiety/
586
+ │ ├── suicide/
587
+ │ ├── trauma/
588
+ │ ├── substance_use/
589
+ │ ├── adolescents/
590
+ │ ├── university_students/
591
+ │ └── severe_mental_illness/
592
+ │
593
+ ├── nigeria_context/
594
+ │ ├── stigma/
595
+ │ ├── culture/
596
+ │ ├── family/
597
+ │ ├── religion_and_mental_health/
598
+ │ ├── unemployment/
599
+ │ ├── poverty/
600
+ │ ├── conflict/
601
+ │ └── healthcare_access/
602
+ │
603
+ ├── scenarios/
604
+ │ ├── academic_stress/
605
+ │ ├── financial_stress/
606
+ │ ├── grief/
607
+ │ ├── relationships/
608
+ │ ├── anxiety/
609
+ │ ├── depression/
610
+ │ ├── trauma/
611
+ │ └── suicide_risk/
612
+ │
613
+ ├── psychoeducation/
614
+ │
615
+ ├── recommendations/
616
+ │
617
+ └── metadata/
618
+ ```
619
+
620
+ Do not simply dump documents into a vector database.
621
+
622
+ Preserve useful metadata.
623
+
624
+ ---
625
+
626
+ # 14. KNOWLEDGE CHUNK METADATA
627
+
628
+ Where possible, each chunk should retain:
629
+
630
+ ```text
631
+ document_id
632
+ title
633
+ source
634
+ authors
635
+ year
636
+ country
637
+ state
638
+ population
639
+ sample_size
640
+ age_range
641
+ mental_health_domain
642
+ condition
643
+ study_design
644
+ measurement_tool
645
+ evidence_level
646
+ limitations
647
+ source_url
648
+ ```
649
+
650
+ This allows future retrieval filtering and source attribution.
651
+
652
+ ---
653
+
654
+ # 15. DETERMINISTIC MODULES STILL EXIST
655
+
656
+ RAG does NOT replace every existing static module.
657
+
658
+ Keep exact information in deterministic/structured data.
659
+
660
+ Examples:
661
+
662
+ ```text
663
+ Emergency contacts
664
+ Facilities
665
+ Facility addresses
666
+ Verified URLs
667
+ Crisis procedures
668
+ Service directories
669
+ Application configuration
670
+ Other exact structured information
671
+ ```
672
+
673
+ Do not ask the LLM to invent these.
674
+
675
+ The architecture should therefore have:
676
+
677
+ ```text
678
+ HEEDX CORE
679
+ │
680
+ ┌────────────┼─────────────┐
681
+ │ │ │
682
+ ▼ ▼ ▼
683
+ LLM RAG DETERMINISTIC
684
+ Conversation Knowledge Modules
685
+ │ │ │
686
+ │ │ ├── contacts
687
+ │ │ ├── facilities
688
+ │ │ ├── URLs
689
+ │ │ └── exact data
690
+ │ │
691
+ │ ├── studies
692
+ │ ├── guidance
693
+ │ ├── psychoeducation
694
+ │ └── evidence
695
+ │
696
+ └────────────┬─────────────┘
697
+ ▼
698
+ HEEDX
699
+ ```
700
+
701
+ ---
702
+
703
+ # 16. SAFETY LAYER
704
+
705
+ Safety must be separate from ordinary RAG.
706
+
707
+ For example, if a user says:
708
+
709
+ > "I want to kill myself."
710
+
711
+ the application must not simply perform normal semantic retrieval and answer like an ordinary mental-health question.
712
+
713
+ It must activate a dedicated safety pathway.
714
+
715
+ The safety layer should be able to:
716
+
717
+ * identify high-risk signals
718
+ * determine whether clarification is necessary
719
+ * prioritize immediate safety
720
+ * provide verified emergency/crisis resources
721
+ * encourage appropriate human support
722
+ * change the response strategy
723
+ * prevent unsafe conversational behavior
724
+
725
+ RAG can provide supporting evidence, but the safety mechanism itself must have explicit rules and guardrails.
726
+
727
+ ---
728
+
729
+ # 17. NO DIAGNOSTIC CLAIMS
730
+
731
+ HeedX should not claim:
732
+
733
+ > "You have depression."
734
+
735
+ based solely on conversational analysis.
736
+
737
+ Prefer:
738
+
739
+ > "What you're describing includes experiences commonly associated with depression."
740
+
741
+ or:
742
+
743
+ > "These symptoms may be worth discussing with a mental-health professional."
744
+
745
+ The system is providing **support, qualitative analysis, and evidence-grounded information**, not replacing clinical diagnosis.
746
+
747
+ ---
748
+
749
+ # 18. PROFESSIONAL OUTPUT VS USER OUTPUT
750
+
751
+ These two modes should have different presentation styles.
752
+
753
+ ## Professional mode
754
+
755
+ The output can be structured:
756
+
757
+ ```text
758
+ CASE ANALYSIS
759
+
760
+ Presenting concerns
761
+ ...
762
+
763
+ Reported symptoms/signals
764
+ ...
765
+
766
+ Duration
767
+ ...
768
+
769
+ Stressors/context
770
+ ...
771
+
772
+ Functional impact
773
+ ...
774
+
775
+ Risk indicators
776
+ ...
777
+
778
+ Relevant considerations
779
+ ...
780
+
781
+ Evidence retrieved
782
+ ...
783
+
784
+ Suggested areas for further assessment
785
+ ...
786
+ ```
787
+
788
+ Be clear that this is an AI-assisted analysis and not a definitive diagnosis.
789
+
790
+ ## Conversational mode
791
+
792
+ The output should be natural:
793
+
794
+ ```text
795
+ "I hear you. From what you've described, you've been dealing
796
+ with poor sleep and losing interest in things you normally enjoy.
797
+ That can be difficult, especially alongside academic stress.
798
+
799
+ Can I ask whether this has also affected your ability to attend
800
+ classes or carry out your normal daily activities?"
801
+ ```
802
+
803
+ Do not expose vector databases, embeddings, retrieval mechanics, or internal analysis unless specifically requested.
804
+
805
+ ---
806
+
807
+ # 19. LLM CONTEXT
808
+
809
+ The LLM should receive an appropriate combination of:
810
+
811
+ ```text
812
+ System instructions
813
+ +
814
+ Current user/patient text
815
+ +
816
+ Relevant conversation history
817
+ +
818
+ Structured analysis
819
+ +
820
+ Conversation/case state
821
+ +
822
+ Retrieved evidence
823
+ +
824
+ Safety state
825
+ +
826
+ Deterministic information when required
827
+ ```
828
+
829
+ For professional mode:
830
+
831
+ ```text
832
+ Patient text
833
+ +
834
+ Qualitative analysis
835
+ +
836
+ Retrieved evidence
837
+ +
838
+ Safety information
839
+ +
840
+ Professional instructions
841
+ ```
842
+
843
+ For conversational mode:
844
+
845
+ ```text
846
+ Current user message
847
+ +
848
+ Conversation history
849
+ +
850
+ Conversation state
851
+ +
852
+ Retrieved evidence
853
+ +
854
+ Safety state
855
+ +
856
+ Conversational instructions
857
+ ```
858
+
859
+ ---
860
+
861
+ # 20. KNOWLEDGE SOURCES
862
+
863
+ The knowledge system should prioritize reliable sources such as:
864
+
865
+ * peer-reviewed Nigerian research
866
+ * reputable international research
867
+ * WHO guidance
868
+ * Nigerian government/public-health sources
869
+ * recognized clinical/public-health organizations
870
+ * evidence-based mental-health resources
871
+
872
+ Nigerian evidence should be prioritized where relevant.
873
+
874
+ Do not fabricate citations or sources.
875
+
876
+ ---
877
+
878
+ # 21. EXISTING CODEBASE INSPECTION
879
+
880
+ Before changing the project, inspect:
881
+
882
+ 1. Entry point
883
+ 2. UI
884
+ 3. Professional/case-analysis interface
885
+ 4. Conversational interface
886
+ 5. Existing classical ML model
887
+ 6. Existing Python analysis
888
+ 7. Existing LLM integration
889
+ 8. Existing static modules
890
+ 9. Existing recommendations
891
+ 10. Emergency/crisis information
892
+ 11. Facility/location data
893
+ 12. Data files
894
+ 13. Deployment configuration
895
+ 14. Requirements/dependencies
896
+ 15. Existing tests
897
+
898
+ Determine what should be:
899
+
900
+ * preserved
901
+ * refactored
902
+ * replaced
903
+ * deprecated
904
+ * newly added
905
+
906
+ Do not delete existing functionality simply because the architecture is changing.
907
+
908
+ ---
909
+
910
+ # 22. TARGET ARCHITECTURE
911
+
912
+ The final conceptual architecture should resemble:
913
+
914
+ ```text
915
+ HEEDX AI
916
+ │
917
+ ┌──────────────┴──────────────┐
918
+ │ │
919
+ ▼ ▼
920
+ PROFESSIONAL MODE CONVERSATIONAL MODE
921
+ CASE ANALYSIS USER CHAT
922
+ │ │
923
+ Upload / Paste / Write User messages
924
+ │ │
925
+ ▼ ▼
926
+ Qualitative Analysis Conversation Understanding
927
+ │ │
928
+ ▼ ▼
929
+ Structured Case State Conversation State
930
+ │ │
931
+ └──────────────┬──────────────┘
932
+ ▼
933
+ RETRIEVAL ENGINE
934
+ │
935
+ Query creation
936
+ ↓
937
+ Embedding
938
+ ↓
939
+ Vector Database
940
+ ↓
941
+ Relevant Knowledge
942
+ │
943
+ ┌──────────────┼──────────────┐
944
+ │ │ │
945
+ ▼ ▼ ▼
946
+ RAG SAFETY DETERMINISTIC
947
+ Evidence Layer Modules
948
+ │ │ │
949
+ └──────────────┼──────────────┘
950
+ ▼
951
+ LLM
952
+ ┌──────┴──────┐
953
+ ▼ ▼
954
+ Professional User-facing
955
+ output response
956
+ ```
957
+
958
+ ---
959
+
960
+ # 23. DEVELOPMENT ORDER
961
+
962
+ Implement incrementally.
963
+
964
+ ### Stage 1 — Repository analysis
965
+
966
+ Understand the existing application.
967
+
968
+ Do not make destructive changes.
969
+
970
+ ### Stage 2 — Separate the two input modes
971
+
972
+ Ensure the UI and backend conceptually distinguish:
973
+
974
+ ```text
975
+ Professional / Case Analysis
976
+ ```
977
+
978
+ from:
979
+
980
+ ```text
981
+ Conversational User Mode
982
+ ```
983
+
984
+ ### Stage 3 — Build/refactor qualitative analysis
985
+
986
+ Create a structured qualitative analysis representation.
987
+
988
+ ### Stage 4 — Build knowledge ingestion
989
+
990
+ Implement:
991
+
992
+ ```text
993
+ documents
994
+ → extraction
995
+ → chunking
996
+ → metadata
997
+ → embeddings
998
+ → vector storage
999
+ ```
1000
+
1001
+ ### Stage 5 — Implement retrieval
1002
+
1003
+ Implement:
1004
+
1005
+ ```text
1006
+ query
1007
+ → embedding
1008
+ → similarity search
1009
+ → relevant chunks
1010
+ ```
1011
+
1012
+ ### Stage 6 — Connect retrieval to professional analysis
1013
+
1014
+ ```text
1015
+ patient text
1016
+ → qualitative analysis
1017
+ → retrieval
1018
+ → evidence
1019
+ → professional output
1020
+ ```
1021
+
1022
+ ### Stage 7 — Connect retrieval to conversation
1023
+
1024
+ ```text
1025
+ user message
1026
+ → conversation understanding
1027
+ → state
1028
+ → retrieval
1029
+ → evidence
1030
+ → LLM
1031
+ → response
1032
+ ```
1033
+
1034
+ ### Stage 8 — Implement safety layer
1035
+
1036
+ Keep safety behavior separate from ordinary RAG.
1037
+
1038
+ ### Stage 9 — Test both modes separately
1039
+
1040
+ Test professional analysis independently from conversational behavior.
1041
+
1042
+ ### Stage 10 — Integrate and refine UI
1043
+
1044
+ Only after the underlying architecture is working.
1045
+
1046
+ ---
1047
+
1048
+ # 24. TEST CASES
1049
+
1050
+ Create tests/examples for both modes.
1051
+
1052
+ ## Professional mode example
1053
+
1054
+ Input:
1055
+
1056
+ > "Patient reports feeling sad most days for the past month, has stopped enjoying social activities and is having difficulty sleeping. Academic workload has increased significantly."
1057
+
1058
+ Expected qualitative analysis should identify:
1059
+
1060
+ ```text
1061
+ persistent sadness
1062
+ reduced interest/social withdrawal
1063
+ sleep difficulty
1064
+ academic stress
1065
+ approximately one month duration
1066
+ ```
1067
+
1068
+ It should NOT output a fabricated diagnostic probability.
1069
+
1070
+ ## Conversational mode example
1071
+
1072
+ User:
1073
+
1074
+ > "I've been feeling down lately."
1075
+
1076
+ Then:
1077
+
1078
+ > "It's been about three weeks and I barely sleep."
1079
+
1080
+ Then:
1081
+
1082
+ > "School has also been stressful."
1083
+
1084
+ The system should progressively update the conversation state and retrieve increasingly relevant evidence.
1085
+
1086
+ ---
1087
+
1088
+ # 25. FINAL DESIGN PRINCIPLE
1089
+
1090
+ The most important architecture to preserve is:
1091
+
1092
+ ```text
1093
+ TWO INPUT MODES
1094
+ │
1095
+ ┌────────────┴────────────┐
1096
+ │ │
1097
+ ▼ ▼
1098
+ PROFESSIONAL MODE CONVERSATION MODE
1099
+ │ │
1100
+ Qualitative analysis Continuous understanding
1101
+ │ │
1102
+ └────────────┬────────────┘
1103
+ ▼
1104
+ SHARED CORE
1105
+ │
1106
+ ┌─────────┼─────────┐
1107
+ ▼ ▼ ▼
1108
+ Analysis RAG Safety
1109
+ │
1110
+ Embeddings
1111
+ │
1112
+ Vector search
1113
+ │
1114
+ ▼
1115
+ LLM
1116
+ │
1117
+ ┌─────────┴─────────┐
1118
+ ▼ ▼
1119
+ Professional output User response
1120
+ ```
1121
+
1122
+ Remember these principles throughout implementation:
1123
+
1124
+ 1. **There are two distinct input modes.**
1125
+ 2. **Professional mode analyzes supplied patient/client text.**
1126
+ 3. **Conversational mode interacts continuously with the user.**
1127
+ 4. **The analysis is primarily qualitative, not a four-class probability prediction.**
1128
+ 5. **No questionnaire screening in this version.**
1129
+ 6. **RAG is shared infrastructure for both modes.**
1130
+ 7. **Knowledge documents are embedded and stored as vectors.**
1131
+ 8. **User/conversation information produces query embeddings for retrieval.**
1132
+ 9. **The user's actual text remains central; embeddings only facilitate retrieval.**
1133
+ 10. **Conversation state is maintained separately from the vector database.**
1134
+ 11. **Deterministic modules remain responsible for exact information.**
1135
+ 12. **Safety has its own explicit layer.**
1136
+ 13. **RAG provides evidence; it does not diagnose.**
1137
+ 14. **The LLM turns the analysis, context, evidence, and safety state into the appropriate output.**
1138
+
1139
+ Before implementing major changes, first inspect the repository and produce:
1140
+
1141
+ 1. **Current architecture**
1142
+ 2. **Target architecture**
1143
+ 3. **Files/components that should be preserved**
1144
+ 4. **Files/components that should be changed**
1145
+ 5. **New components required**
1146
+ 6. **Implementation sequence**
1147
+
1148
+ Then proceed incrementally without unnecessarily destroying existing working functionality.
models.cpython-312.pyc ADDED
Binary file (2.06 kB). View file
 
preprocessing.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
preprocessing.cpython-312.pyc ADDED
Binary file (2.77 kB). View file
 
preprocessing.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils/preprocessing.py - NO NLTK DEPENDENCY
2
+ """
3
+ Text preprocessing utilities - Pure Python, no external dependencies
4
+ """
5
+
6
+ import re
7
+ from .lexicons import NIGERIAN_IDIOM_MAP
8
+
9
+ def preprocess_text(text):
10
+ """
11
+ EXACT preprocessing function used during training
12
+ MUST match your training preprocessing exactly!
13
+ """
14
+ if not isinstance(text, str):
15
+ text = str(text)
16
+
17
+ # Convert to lowercase
18
+ text = text.lower()
19
+
20
+ # Apply Nigerian Idiom Translation
21
+ for idiom, replacement in NIGERIAN_IDIOM_MAP.items():
22
+ text = text.replace(idiom, replacement)
23
+
24
+ # Remove special characters and digits (keep only letters and spaces)
25
+ text = ''.join([char for char in text if char.isalpha() or char.isspace()])
26
+
27
+ # Remove extra whitespace
28
+ text = ' '.join(text.split())
29
+
30
+ return text
31
+
32
+
33
+ def split_sentences(text):
34
+ """
35
+ Split text into sentences using regex
36
+ No NLTK required!
37
+ """
38
+ if not text or not isinstance(text, str):
39
+ return []
40
+
41
+ # Clean the text first
42
+ text = text.strip()
43
+ if not text:
44
+ return []
45
+
46
+ # Method 1: Split on sentence endings (.!?) followed by space or end of string
47
+ # This handles most cases
48
+ sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z])|(?<=[.!?])$', text)
49
+
50
+ # If that didn't work well, try simpler split
51
+ if len(sentences) <= 1 and '.' in text:
52
+ # Fallback: split on periods followed by space
53
+ sentences = re.split(r'\.\s+', text)
54
+
55
+ # Clean up sentences
56
+ cleaned_sentences = []
57
+ for s in sentences:
58
+ s = s.strip()
59
+ # Remove any trailing punctuation
60
+ s = re.sub(r'[.!?]+$', '', s)
61
+ if s and len(s.split()) >= 2: # At least 2 words
62
+ cleaned_sentences.append(s)
63
+
64
+ # If no sentences found, return the whole text as one sentence
65
+ if not cleaned_sentences and text:
66
+ # But only if it's substantial
67
+ if len(text.split()) >= 3:
68
+ cleaned_sentences = [text]
69
+
70
+ return cleaned_sentences
71
+
72
+
73
+ def clean_response(text):
74
+ """
75
+ Clean user input before processing
76
+ """
77
+ if not text:
78
+ return ""
79
+
80
+ # Remove excessive whitespace
81
+ text = ' '.join(text.split())
82
+
83
+ return text
84
+
85
+
86
+ def simple_word_tokenize(text):
87
+ """
88
+ Simple word tokenization (if needed)
89
+ """
90
+ if not text:
91
+ return []
92
+
93
+ # Remove punctuation and split
94
+ text = re.sub(r'[^\w\s]', '', text)
95
+ return text.split()
96
+
97
+
98
+ # Test function (you can remove this in production)
99
+ '''def test_tokenizer():
100
+ """Test the sentence splitter"""
101
+ test_texts = [
102
+ "I feel anxious. My heart is racing. I can't breathe.",
103
+ "I'm feeling hopeless and empty. Nothing matters anymore.",
104
+ "I want to kill myself. I have a plan. I bought pills.",
105
+ "I had a good day today. Spent time with family. Feeling hopeful.",
106
+ "This is one long sentence without punctuation so it should stay together"
107
+ ]
108
+
109
+ print("Testing sentence tokenizer:")
110
+ for text in test_texts:
111
+ sentences = split_sentences(text)
112
+ print(f"\nOriginal: {text}")
113
+ print(f"Split into {len(sentences)} sentences:")
114
+ for i, s in enumerate(sentences, 1):
115
+ print(f" {i}. {s}")
116
+
117
+ return True
118
+
119
+ # Run test if executed directly
120
+ if __name__ == "__main__":
121
+ test_tokenizer()'''
qualitative_engine.cpython-312.pyc ADDED
Binary file (14.7 kB). View file
 
qualitative_engine.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI — Qualitative Analysis Engine
3
+ Extracts structured qualitative clinical dimensions from text:
4
+ presenting_concerns, symptoms_or_signals, emotions, stressors,
5
+ duration, functional_impact, social_context, protective_factors,
6
+ risk_signals, support_needs, uncertainties.
7
+
8
+ Prioritizes factual representation and semantic interpretation over
9
+ synthetic diagnostic percentages.
10
+ """
11
+
12
+ import re
13
+ from typing import Dict, List, Any, Optional
14
+ from .lexicons import NIGERIAN_IDIOM_MAP, CRISIS_TRIGGERS, RESILIENCE_KEYWORDS, NEGATIONS
15
+
16
+
17
+ class QualitativeAnalysisEngine:
18
+ """
19
+ Qualitative Analysis Engine for HeedX AI.
20
+ Analyzes patient/client text or user conversation turns
21
+ and generates structured qualitative clinical information.
22
+ """
23
+
24
+ def __init__(self):
25
+ # Clinical concept dictionaries for deterministic/rule semantic detection
26
+ self.symptom_patterns = {
27
+ "low_mood": [
28
+ r"\b(sad|sadness|unhappy|down|feeling low|spirit is low|no joy|spirit weak|depressed|depression)\b"
29
+ ],
30
+ "sleep_disturbance": [
31
+ r"\b(sleep difficulty|difficulty sleeping|insomnia|can't sleep|cannot sleep|trouble sleeping|hard to sleep|waking up early|nightmare|barely sleep|poor sleep)\b"
32
+ ],
33
+ "anhedonia": [
34
+ r"\b(loss of interest|stopped enjoying|no vibe|vibe finish|don't enjoy|not enjoying|lost interest|nothing excites|loss of pleasure)\b"
35
+ ],
36
+ "social_withdrawal": [
37
+ r"\b(withdrawn|withdrawing|withdrawn from friends|isolating|isolation|avoiding people|stopped seeing friends|stopped enjoying social activities|social withdrawal|avoiding social|stay in room|alone)\b"
38
+ ],
39
+ "concentration_difficulty": [
40
+ r"\b(difficulty concentrating|can't focus|cannot concentrate|struggling to concentrate|mind wandering|brain fog)\b"
41
+ ],
42
+ "fatigue_low_energy": [
43
+ r"\b(fatigue|exhausted|no get power|tired|taya|body no be firewood|weak|drained|no energy)\b"
44
+ ],
45
+ "anxiety_panic": [
46
+ r"\b(anxiety|anxious|panic|heart racing|heart is cutting|chest tight|nervous|worry|worried|tension|head is hot)\b"
47
+ ],
48
+ "hopelessness": [
49
+ r"\b(hopeless|no hope|no point|what's the use|what is the use|useless|worthless)\b"
50
+ ]
51
+ }
52
+
53
+ self.stressor_patterns = {
54
+ "academic_stress": [
55
+ r"\b(university|school|exam|exams|academic|classes|coursework|lecturer|grades|cgpa|faculty|polytechnic|hostel|academic workload)\b"
56
+ ],
57
+ "financial_stress": [
58
+ r"\b(money|financial|fees|rent|broke|no funds|poverty|debt|feeding|transport fare)\b"
59
+ ],
60
+ "career_unemployment": [
61
+ r"\b(job|work|unemployed|unemployment|career|boss|salary|seeking employment)\b"
62
+ ],
63
+ "relationship_family": [
64
+ r"\b(parents|father|mother|family|boyfriend|girlfriend|husband|wife|marriage|partner|breakup|divorce)\b"
65
+ ],
66
+ "health_grief": [
67
+ r"\b(illness|sick|hospital|death|died|lost someone|grief|bereavement|funeral)\b"
68
+ ]
69
+ }
70
+
71
+ self.duration_regex = [
72
+ r"(\b(?:for\s+)?(?:the\s+)?(?:past|last|about|approximately|almost|over)\s+(?:\d+|one|two|three|four|five|six|several|a few|a|an)?\s*(?:days?|weeks?|months?|years?)\b)",
73
+ r"(\b(?:for|over|about|approximately)\s+(?:\d+|one|two|three|four|five|six|several|a few|a)\s+(?:days?|weeks?|months?|years?)\b)",
74
+ r"(\b(?:one|two|three|four|five|six|\d+)\s+(?:month|week|year|day)s?\b)",
75
+ r"(\bfor\s+(?:a|some)\s+(?:while|time|days|weeks|months)\b)"
76
+ ]
77
+
78
+ def _extract_duration(self, text: str) -> Optional[str]:
79
+ """Extracts temporal duration statements from text"""
80
+ for pat in self.duration_regex:
81
+ match = re.search(pat, text, re.IGNORECASE)
82
+ if match:
83
+ return match.group(0).strip()
84
+ return None
85
+
86
+ def _is_negated(self, pattern: str, text: str, window: int = 4) -> bool:
87
+ """Determines if a matched clinical term is negated within local context"""
88
+ for match in re.finditer(pattern, text, re.IGNORECASE):
89
+ start = match.start()
90
+ preceding_words = text[:start].strip().split()[-window:]
91
+ if any(neg in preceding_words for neg in NEGATIONS):
92
+ return True
93
+ return False
94
+
95
+ def analyze(self, text: str) -> Dict[str, Any]:
96
+ """
97
+ Performs qualitative analysis on the supplied text,
98
+ producing a structured clinical representation.
99
+ """
100
+ if not text or not isinstance(text, str):
101
+ text = ""
102
+
103
+ cleaned = text.strip()
104
+ lower_text = cleaned.lower()
105
+
106
+ # Translate Nigerian idioms for semantic awareness
107
+ idiom_translated = lower_text
108
+ for idiom, repl in NIGERIAN_IDIOM_MAP.items():
109
+ idiom_translated = idiom_translated.replace(idiom, repl)
110
+
111
+ # 1. Duration extraction
112
+ duration = self._extract_duration(cleaned)
113
+
114
+ # 2. Symptoms & Signals Extraction
115
+ symptoms = []
116
+ concerns = []
117
+ emotions = []
118
+
119
+ for category, patterns in self.symptom_patterns.items():
120
+ for pat in patterns:
121
+ if re.search(pat, lower_text) or re.search(pat, idiom_translated):
122
+ if not self._is_negated(pat, lower_text) and not self._is_negated(pat, idiom_translated):
123
+ cat_label = category.replace("_", " ")
124
+ if category in ["low_mood", "hopelessness"]:
125
+ if "persistent sadness" not in concerns and "low mood" not in concerns:
126
+ concerns.append("persistent sadness" if duration else "low mood")
127
+ emotions.append("sad" if category == "low_mood" else "discouraged")
128
+ elif category == "sleep_disturbance":
129
+ symptoms.append("sleep difficulty")
130
+ if "sleep difficulty" not in concerns:
131
+ concerns.append("sleep difficulty")
132
+ elif category == "anhedonia":
133
+ symptoms.append("reduced interest / loss of enjoyment")
134
+ if "reduced interest / loss of enjoyment" not in concerns:
135
+ concerns.append("reduced interest / loss of enjoyment")
136
+ elif category == "social_withdrawal":
137
+ symptoms.append("social withdrawal")
138
+ if "social withdrawal" not in concerns:
139
+ concerns.append("social withdrawal")
140
+ elif category == "concentration_difficulty":
141
+ symptoms.append("difficulty concentrating")
142
+ elif category == "fatigue_low_energy":
143
+ symptoms.append("low energy / fatigue")
144
+ elif category == "anxiety_panic":
145
+ symptoms.append("anxiety / somatic tension")
146
+ concerns.append("anxiety")
147
+ emotions.append("anxious / overwhelmed")
148
+ break
149
+
150
+ # 3. Stressors & Context Extraction
151
+ stressors = []
152
+ social_context = []
153
+
154
+ for category, patterns in self.stressor_patterns.items():
155
+ for pat in patterns:
156
+ if re.search(pat, lower_text):
157
+ if category == "academic_stress":
158
+ stressors.append("academic workload / university pressure")
159
+ social_context.append("university/academic environment")
160
+ elif category == "financial_stress":
161
+ stressors.append("financial hardship / economic stress")
162
+ elif category == "career_unemployment":
163
+ stressors.append("work / career uncertainty")
164
+ elif category == "relationship_family":
165
+ stressors.append("family or interpersonal strain")
166
+ elif category == "health_grief":
167
+ stressors.append("health issues or bereavement")
168
+ break
169
+
170
+ # 4. Functional Impact Extraction
171
+ functional_impact = []
172
+ if "difficulty concentrating" in symptoms:
173
+ functional_impact.append("academic or cognitive task concentration")
174
+ if re.search(r"\b(struggling at university|failing|cannot study|miss classes|can't work|cannot work)\b", lower_text):
175
+ functional_impact.append("academic/occupational performance")
176
+ if "social withdrawal" in symptoms:
177
+ functional_impact.append("social relationships and engagement")
178
+
179
+ # 5. Protective Factors & Resilience
180
+ protective_factors = []
181
+ for word in RESILIENCE_KEYWORDS:
182
+ if re.search(r'\b' + re.escape(word) + r'\b', lower_text):
183
+ if not self._is_negated(r'\b' + re.escape(word) + r'\b', lower_text):
184
+ protective_factors.append(f"expressed coping / {word}")
185
+ if re.search(r"\b(pray|church|mosque|god|faith|pastor|imam)\b", lower_text):
186
+ protective_factors.append("spiritual or faith-based coping framework")
187
+ if re.search(r"\b(family|friend|friends|sister|brother|mother|father)\b", lower_text):
188
+ if "family or interpersonal strain" not in stressors:
189
+ protective_factors.append("presence of family/friend support network")
190
+
191
+ # 6. Risk Signals & Safety Triage
192
+ risk_signals = []
193
+ uncertainties = []
194
+
195
+ for trig in CRISIS_TRIGGERS:
196
+ if re.search(trig, lower_text):
197
+ if self._is_negated(trig, lower_text):
198
+ uncertainties.append(f"suicidal ideation explicitly negated in context ('{trig}')")
199
+ else:
200
+ risk_signals.append(f"acute risk language detected: '{trig}'")
201
+
202
+ if not risk_signals:
203
+ uncertainties.append("no suicidal ideation established from the supplied text")
204
+ uncertainties.append("further longitudinal assessment may be appropriate")
205
+
206
+ # Fallback deduplication
207
+ concerns = list(dict.fromkeys(concerns))
208
+ symptoms = list(dict.fromkeys(symptoms))
209
+ emotions = list(dict.fromkeys(emotions))
210
+ stressors = list(dict.fromkeys(stressors))
211
+ functional_impact = list(dict.fromkeys(functional_impact))
212
+ protective_factors = list(dict.fromkeys(protective_factors))
213
+ risk_signals = list(dict.fromkeys(risk_signals))
214
+ uncertainties = list(dict.fromkeys(uncertainties))
215
+
216
+ return {
217
+ "presenting_concerns": concerns if concerns else ["general distress / unclassified concerns"],
218
+ "emotions": emotions if emotions else ["distressed"],
219
+ "symptoms_or_signals": symptoms if symptoms else ["unspecified emotional or physical strain"],
220
+ "stressors": stressors,
221
+ "duration": duration or "duration not explicitly stated in supplied text",
222
+ "functional_impact": functional_impact,
223
+ "social_context": social_context,
224
+ "protective_factors": protective_factors,
225
+ "risk_signals": risk_signals,
226
+ "support_needs": [
227
+ "evidence-grounded psychoeducation",
228
+ "supportive listening and coping exploration"
229
+ ],
230
+ "uncertainties": uncertainties
231
+ }
232
+
233
+ def format_for_display(self, analysis: Dict[str, Any]) -> str:
234
+ """
235
+ Formats qualitative clinical analysis into clear, professional Markdown,
236
+ strictly avoiding synthetic diagnostic percentages.
237
+ """
238
+ md = []
239
+ md.append("### Qualitative Case Extraction\n")
240
+
241
+ md.append("**Presenting concerns**")
242
+ for c in analysis.get("presenting_concerns", []):
243
+ md.append(f"• {c}")
244
+ md.append("")
245
+
246
+ md.append("**Duration**")
247
+ md.append(f"• {analysis.get('duration', 'Not established')}\n")
248
+
249
+ if analysis.get("stressors") or analysis.get("social_context"):
250
+ md.append("**Context & Stressors**")
251
+ for s in analysis.get("stressors", []):
252
+ md.append(f"• {s}")
253
+ for sc in analysis.get("social_context", []):
254
+ md.append(f"• Context: {sc}")
255
+ md.append("")
256
+
257
+ md.append("**Potentially relevant symptoms/signals**")
258
+ for s in analysis.get("symptoms_or_signals", []):
259
+ md.append(f"• {s}")
260
+ md.append("")
261
+
262
+ if analysis.get("functional_impact"):
263
+ md.append("**Functional impact**")
264
+ for f in analysis.get("functional_impact", []):
265
+ md.append(f"• {f}")
266
+ md.append("")
267
+
268
+ if analysis.get("protective_factors"):
269
+ md.append("**Observed protective factors / strengths**")
270
+ for p in analysis.get("protective_factors", []):
271
+ md.append(f"• {p}")
272
+ md.append("")
273
+
274
+ md.append("**Risk & Safety information**")
275
+ if analysis.get("risk_signals"):
276
+ for r in analysis.get("risk_signals"):
277
+ md.append(f"⚠️ **ACTIVE RISK SIGNAL**: {r}")
278
+ else:
279
+ md.append("• No explicit acute crisis or suicidal ideation established from supplied text")
280
+ for u in analysis.get("uncertainties", []):
281
+ if "no suicidal ideation" not in u:
282
+ md.append(f"• *Clinical note:* {u}")
283
+
284
+ return "\n".join(md)
rag_engine.cpython-312.pyc ADDED
Binary file (14.9 kB). View file
 
rag_engine.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI — Retrieval-Augmented Generation (RAG) Engine
3
+ Indexes evidence-based Nigerian mental health literature, guidelines, and context.
4
+ Provides cosine similarity vector search with Gemini embeddings and TF-IDF fallback.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import re
10
+ import numpy as np
11
+ from typing import List, Dict, Any, Optional
12
+ import requests
13
+ from sklearn.feature_extraction.text import TfidfVectorizer
14
+ from sklearn.metrics.pairwise import cosine_similarity
15
+
16
+
17
+ class RAGEngine:
18
+ """
19
+ RAG Engine for HeedX AI.
20
+ Loads knowledge documents, chunks text, generates embeddings,
21
+ and conducts semantic similarity search over curated evidence.
22
+ """
23
+
24
+ def __init__(self, knowledge_file: Optional[str] = None):
25
+ if knowledge_file is None:
26
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+ knowledge_file = os.path.join(base_dir, "knowledge", "knowledge_store.json")
28
+
29
+ self.knowledge_file = knowledge_file
30
+ self.chunks: List[Dict[str, Any]] = []
31
+ self.tfidf_vectorizer: Optional[TfidfVectorizer] = None
32
+ self.tfidf_matrix = None
33
+ self.gemini_embeddings: List[List[float]] = []
34
+ self._load_and_chunk_corpus()
35
+ self._build_tfidf_index()
36
+
37
+ def _load_and_chunk_corpus(self):
38
+ """Loads curated documents and prepares chunk structures with metadata"""
39
+ docs = []
40
+ if os.path.exists(self.knowledge_file):
41
+ try:
42
+ with open(self.knowledge_file, "r", encoding="utf-8") as f:
43
+ docs = json.load(f)
44
+ except Exception as e:
45
+ print(f"[RAGEngine] Error loading knowledge JSON file: {e}")
46
+
47
+ # Also discover any markdown knowledge documents in subdirectories
48
+ base_dir = os.path.dirname(self.knowledge_file)
49
+ if os.path.exists(base_dir):
50
+ for root, _, files in os.walk(base_dir):
51
+ for file in files:
52
+ if file.endswith(".md"):
53
+ md_path = os.path.join(root, file)
54
+ try:
55
+ with open(md_path, "r", encoding="utf-8") as f:
56
+ md_text = f.read()
57
+ # Parse optional yaml frontmatter
58
+ meta = {}
59
+ body = md_text
60
+ if md_text.startswith("---"):
61
+ parts = md_text.split("---", 2)
62
+ if len(parts) >= 3:
63
+ fm_text = parts[1]
64
+ body = parts[2].strip()
65
+ for line in fm_text.splitlines():
66
+ if ":" in line:
67
+ k, v = line.split(":", 1)
68
+ meta[k.strip()] = v.strip().strip('"').strip("'")
69
+ doc_id = meta.get("document_id", os.path.splitext(file)[0].upper())
70
+ # Avoid duplicates if document_id already loaded
71
+ if not any(d.get("document_id") == doc_id for d in docs):
72
+ docs.append({
73
+ "document_id": doc_id,
74
+ "title": meta.get("title", file.replace("_", " ").replace(".md", "").title()),
75
+ "source": meta.get("source", "HeedX Clinical Knowledge Corpus"),
76
+ "authors": meta.get("authors", "HeedX Research Team"),
77
+ "year": int(meta.get("year", 2024)) if meta.get("year", "").isdigit() else 2024,
78
+ "country": meta.get("country", "Nigeria"),
79
+ "state": meta.get("state", "National"),
80
+ "population": meta.get("population", "General"),
81
+ "sample_size": meta.get("sample_size"),
82
+ "mental_health_domain": meta.get("mental_health_domain", "clinical_knowledge"),
83
+ "condition": meta.get("condition", "Mental Health"),
84
+ "evidence_level": meta.get("evidence_level", "Clinical Evidence"),
85
+ "limitations": meta.get("limitations", "Synthesized guidance"),
86
+ "source_url": meta.get("source_url", ""),
87
+ "content": body
88
+ })
89
+ except Exception as md_err:
90
+ print(f"[RAGEngine] Error reading {md_path}: {md_err}")
91
+
92
+ chunk_id = 0
93
+ for doc in docs:
94
+ content = doc.get("content", "").strip()
95
+ if not content:
96
+ continue
97
+
98
+ # Break large documents into 1-3 paragraph chunks
99
+ paragraphs = [p.strip() for p in re.split(r'\n\s*\n', content) if len(p.strip()) > 40]
100
+ if not paragraphs:
101
+ paragraphs = [content]
102
+
103
+ for p_idx, para in enumerate(paragraphs):
104
+ chunk_id += 1
105
+ self.chunks.append({
106
+ "chunk_id": f"{doc.get('document_id', 'DOC')}_C{p_idx+1}",
107
+ "document_id": doc.get("document_id"),
108
+ "title": doc.get("title"),
109
+ "source": doc.get("source"),
110
+ "authors": doc.get("authors"),
111
+ "year": doc.get("year"),
112
+ "country": doc.get("country", "Nigeria"),
113
+ "state": doc.get("state"),
114
+ "population": doc.get("population"),
115
+ "sample_size": doc.get("sample_size"),
116
+ "mental_health_domain": doc.get("mental_health_domain"),
117
+ "condition": doc.get("condition"),
118
+ "study_design": doc.get("study_design"),
119
+ "measurement_tool": doc.get("measurement_tool"),
120
+ "evidence_level": doc.get("evidence_level"),
121
+ "limitations": doc.get("limitations"),
122
+ "source_url": doc.get("source_url"),
123
+ "text": para
124
+ })
125
+
126
+ def _build_tfidf_index(self):
127
+ """Builds a scikit-learn TF-IDF index for ultra-reliable local semantic search"""
128
+ if not self.chunks:
129
+ return
130
+
131
+ corpus_texts = [
132
+ f"{c.get('title', '')} {c.get('condition', '')} {c.get('mental_health_domain', '')} {c.get('text', '')}"
133
+ for c in self.chunks
134
+ ]
135
+ self.tfidf_vectorizer = TfidfVectorizer(
136
+ ngram_range=(1, 2),
137
+ stop_words='english',
138
+ max_features=2500
139
+ )
140
+ self.tfidf_matrix = self.tfidf_vectorizer.fit_transform(corpus_texts)
141
+
142
+ def _get_gemini_embedding(self, text: str, api_key: str) -> Optional[List[float]]:
143
+ """Fetch dense vector embedding from Google Gemini API via REST"""
144
+ if not api_key or not text.strip():
145
+ return None
146
+
147
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:embedContent?key={api_key}"
148
+ headers = {"Content-Type": "application/json"}
149
+ payload = {
150
+ "model": "models/text-embedding-004",
151
+ "content": {
152
+ "parts": [{"text": text[:2048]}]
153
+ }
154
+ }
155
+
156
+ try:
157
+ resp = requests.post(url, headers=headers, json=payload, timeout=8)
158
+ if resp.status_code == 200:
159
+ data = resp.json()
160
+ embedding = data.get("embedding", {}).get("values")
161
+ return embedding
162
+ except Exception:
163
+ pass
164
+ return None
165
+
166
+ def construct_query(
167
+ self,
168
+ current_text: str = "",
169
+ concerns: Optional[List[str]] = None,
170
+ symptoms: Optional[List[str]] = None,
171
+ stressors: Optional[List[str]] = None,
172
+ context: Optional[List[str]] = None
173
+ ) -> str:
174
+ """
175
+ Builds a high-signal search query from qualitative signals and user text.
176
+ Avoids dumping raw, noisy transcripts.
177
+ """
178
+ query_terms = []
179
+ if concerns:
180
+ query_terms.extend(concerns)
181
+ if symptoms:
182
+ query_terms.extend(symptoms)
183
+ if stressors:
184
+ query_terms.extend(stressors)
185
+ if context:
186
+ query_terms.extend(context)
187
+
188
+ # Include key salient words from current text
189
+ if current_text:
190
+ cleaned_words = [w for w in re.findall(r'\b[a-zA-Z]{3,}\b', current_text.lower())
191
+ if w not in {'the', 'and', 'was', 'for', 'that', 'with', 'have', 'been', 'this'}]
192
+ query_terms.extend(cleaned_words[:6])
193
+
194
+ if not query_terms:
195
+ return current_text.strip() or "mental health support and coping"
196
+
197
+ # Unique terms preserved in order
198
+ seen = set()
199
+ deduped = []
200
+ for term in query_terms:
201
+ t = str(term).strip().lower()
202
+ if t and t not in seen:
203
+ seen.add(t)
204
+ deduped.append(t)
205
+
206
+ return " ".join(deduped[:12])
207
+
208
+ def search(
209
+ self,
210
+ query: str,
211
+ top_k: int = 3,
212
+ api_key: Optional[str] = None,
213
+ domain_filter: Optional[str] = None
214
+ ) -> List[Dict[str, Any]]:
215
+ """
216
+ Executes vector search against the indexed knowledge base.
217
+ Returns top_k most relevant chunks along with metadata and similarity score.
218
+ """
219
+ if not self.chunks or not query.strip():
220
+ return []
221
+
222
+ # Strategy 1: Local TF-IDF Vector Cosine Similarity (Instant, zero-latency, always available)
223
+ query_vec = self.tfidf_vectorizer.transform([query])
224
+ similarities = cosine_similarity(query_vec, self.tfidf_matrix).flatten()
225
+
226
+ # Apply domain filter if requested
227
+ ranked_indices = np.argsort(similarities)[::-1]
228
+
229
+ results = []
230
+ for idx in ranked_indices:
231
+ score = float(similarities[idx])
232
+ chunk = self.chunks[idx]
233
+
234
+ if domain_filter and chunk.get("mental_health_domain") != domain_filter:
235
+ continue
236
+
237
+ results.append({
238
+ "chunk_id": chunk["chunk_id"],
239
+ "document_id": chunk["document_id"],
240
+ "title": chunk["title"],
241
+ "source": chunk["source"],
242
+ "authors": chunk["authors"],
243
+ "year": chunk["year"],
244
+ "evidence_level": chunk["evidence_level"],
245
+ "population": chunk["population"],
246
+ "condition": chunk["condition"],
247
+ "limitations": chunk["limitations"],
248
+ "source_url": chunk["source_url"],
249
+ "text": chunk["text"],
250
+ "score": round(score, 3)
251
+ })
252
+
253
+ if len(results) >= top_k:
254
+ break
255
+
256
+ return results
257
+
258
+ def format_evidence_for_prompt(self, retrieved_chunks: List[Dict[str, Any]]) -> str:
259
+ """
260
+ Formats retrieved evidence chunks into a clean, markdown block
261
+ ready for injection into the LLM context.
262
+ """
263
+ if not retrieved_chunks:
264
+ return "No specific external research evidence retrieved."
265
+
266
+ lines = ["### RETRIEVED GROUNDING EVIDENCE (Nigerian & Clinical Context):"]
267
+ for idx, chunk in enumerate(retrieved_chunks, 1):
268
+ lines.append(f"**Evidence #{idx}: {chunk.get('title')}** ({chunk.get('year')})")
269
+ lines.append(f"- *Source & Authors:* {chunk.get('source')} | {chunk.get('authors')}")
270
+ lines.append(f"- *Population & Focus:* {chunk.get('population')} ({chunk.get('condition')})")
271
+ lines.append(f"- *Evidence Level:* {chunk.get('evidence_level')}")
272
+ lines.append(f"- *Key Finding / Guidance:* {chunk.get('text')}\n")
273
+
274
+ return "\n".join(lines)
recommendations.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
recommendations.cpython-312.pyc ADDED
Binary file (5.58 kB). View file
 
recommendations.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Emergency Services:** Call 112",
39
+ "**Mentally Aware Nigeria Initiative (MANI):** 08062106493",
40
+ "**She Writes Woman:** 08099769974",
41
+ "**Lagos State Help Line:** 767 or 112"
42
+ ],
43
+ 'message': "These resources provide immediate, confidential support 24/7."
44
+ }
45
+
46
+ def get_qualitative_recommendations(self, analysis_dict: dict) -> dict:
47
+ """
48
+ Generate evidence-informed coping and support guidance based on
49
+ structured qualitative clinical dimensions (concerns, stressors, symptoms).
50
+ """
51
+ tips = []
52
+ concerns = [c.lower() for c in analysis_dict.get("presenting_concerns", [])]
53
+ symptoms = [s.lower() for s in analysis_dict.get("symptoms_or_signals", [])]
54
+ stressors = [st.lower() for st in analysis_dict.get("stressors", [])]
55
+
56
+ combined = " ".join(concerns + symptoms + stressors)
57
+
58
+ if "sleep" in combined or "insomnia" in combined:
59
+ tips.append("**Sleep Restoration Strategy**: Practice a 30-minute cognitive wind-down before bed. Avoid screen exposure, and if awake for over 20 minutes, engage in quiet box breathing in a dim room.")
60
+
61
+ if "academic" in combined or "university" in combined or "school" in combined:
62
+ tips.append("**Academic Load Pacing**: Break study blocks into 25-minute Pomodoro segments with 5-minute cognitive breaks. Communicate with academic advisors or peer study circles to mitigate isolation.")
63
+
64
+ if "social" in combined or "withdrawn" in combined or "alone" in combined:
65
+ tips.append("**Gentle Social Reconnection**: Start with low-pressure contact — sending a simple text to one trusted friend or sitting in a shared communal space without pressure to perform.")
66
+
67
+ if "energy" in combined or "fatigue" in combined or "exhaust" in combined:
68
+ tips.append("**Energy Conservation**: Prioritize essential daily activities ('body no be firewood'). Allow yourself permission to rest and hydrate before attempting high-demand tasks.")
69
+
70
+ if "financial" in combined or "money" in combined:
71
+ tips.append("**Stress Compartmentalization**: Designate a specific 15-minute 'worry time' during daylight hours to outline immediate practical steps, preventing intrusive financial thoughts during rest periods.")
72
+
73
+ # Default supportive guidance if no specific domain matched
74
+ if not tips:
75
+ tips = [
76
+ "**Daily Emotional Check-in**: Acknowledge your emotional state without self-judgment. Emotional fluctuations are normal human responses to life challenges.",
77
+ "**Engage Trusted Support**: Consider speaking openly with a counselor, close elder, or trusted confidant about what you are carrying.",
78
+ "**Balanced Routine**: Maintain consistent meal times, adequate hydration, and brief daily outdoor walks to ground your physical rhythm."
79
+ ]
80
+
81
+ return {
82
+ 'title': "Evidence-Informed Supportive Guidance",
83
+ 'message': "Practical, qualitative coping strategies aligned with the presenting experiences:",
84
+ 'tips': tips
85
+ }
86
+
87
+ def format_recommendations(self, recommendations_dict):
88
+ """
89
+ Format recommendations for display
90
+ """
91
+ if not recommendations_dict:
92
+ return ""
93
+
94
+ formatted = f"### {recommendations_dict['title']}\n\n"
95
+ formatted += f"{recommendations_dict['message']}\n\n"
96
+
97
+ for i, tip in enumerate(recommendations_dict['tips'], 1):
98
+ formatted += f"{i}. {tip}\n"
99
+
100
+ return formatted
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit>=1.31.0
2
+ pandas>=2.0.0
3
+ numpy>=1.24.0
4
+ requests>=2.31.0
5
+ pypdf>=3.17.0
6
+ google-generativeai>=0.3.0
7
+ scikit-learn>=1.8.0
safety_layer.cpython-312.pyc ADDED
Binary file (4.83 kB). View file
 
safety_layer.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI — Dedicated Safety Layer
3
+ Provides rule-based, explicit safety triage and crisis protocols.
4
+ Operates independently from standard RAG retrieval and LLM generation.
5
+ """
6
+
7
+ import re
8
+ from typing import Dict, Any, List, Optional
9
+ from config.settings import NIGERIA_EMERGENCY_NUMBERS, MENTAL_HEALTH_SUPPORT, PROFESSIONAL_HELP
10
+ from .lexicons import CRISIS_TRIGGERS, NEGATIONS
11
+
12
+
13
+ class SafetyLayer:
14
+ """
15
+ Explicit Safety & Crisis Intercept Layer.
16
+ Guarantees immediate clinical guardrails, crisis de-escalation,
17
+ and verified Nigerian emergency resources for at-risk users.
18
+ """
19
+
20
+ def __init__(self):
21
+ self.crisis_triggers = CRISIS_TRIGGERS
22
+ self.negations = NEGATIONS
23
+
24
+ def _is_negated(self, pattern: str, text: str, window: int = 3) -> bool:
25
+ """Checks if a crisis pattern is negated within a local word window"""
26
+ for match in re.finditer(pattern, text, re.IGNORECASE):
27
+ start = match.start()
28
+ preceding_words = text[:start].strip().split()[-window:]
29
+ if any(w in self.negations for w in preceding_words):
30
+ return True
31
+ if "no" in preceding_words and "longer" in preceding_words:
32
+ return True
33
+ return False
34
+
35
+ def evaluate_message(self, text: str) -> Dict[str, Any]:
36
+ """
37
+ Evaluates a user message or clinical observation for safety risks.
38
+ Returns safety assessment, crisis flags, and deterministic crisis responses.
39
+ """
40
+ if not text or not isinstance(text, str):
41
+ return {
42
+ "is_crisis": False,
43
+ "is_negated_crisis": False,
44
+ "risk_level": "none",
45
+ "matched_triggers": [],
46
+ "emergency_response": None
47
+ }
48
+
49
+ cleaned = text.strip().lower()
50
+ active_triggers = []
51
+ negated_triggers = []
52
+
53
+ for pattern in self.crisis_triggers:
54
+ if re.search(pattern, cleaned, re.IGNORECASE):
55
+ if self._is_negated(pattern, cleaned):
56
+ negated_triggers.append(pattern)
57
+ else:
58
+ active_triggers.append(pattern)
59
+
60
+ if active_triggers:
61
+ emergency_message = self._build_emergency_response()
62
+ return {
63
+ "is_crisis": True,
64
+ "is_negated_crisis": False,
65
+ "risk_level": "acute_crisis",
66
+ "matched_triggers": active_triggers,
67
+ "emergency_response": emergency_message
68
+ }
69
+ elif negated_triggers:
70
+ return {
71
+ "is_crisis": False,
72
+ "is_negated_crisis": True,
73
+ "risk_level": "safe_negated",
74
+ "matched_triggers": negated_triggers,
75
+ "emergency_response": None
76
+ }
77
+
78
+ return {
79
+ "is_crisis": False,
80
+ "is_negated_crisis": False,
81
+ "risk_level": "standard",
82
+ "matched_triggers": [],
83
+ "emergency_response": None
84
+ }
85
+
86
+ def _build_emergency_response(self) -> str:
87
+ """Constructs immediate, empathetic, verified crisis support instructions"""
88
+ return (
89
+ "### 🚨 Immediate Safety Support Required\n\n"
90
+ "What you have just shared indicates that you may be in severe emotional pain or experiencing thoughts of harm. "
91
+ "Your life has immense value, and you do not have to carry this alone. Please connect with immediate help right now:\n\n"
92
+ "**Verified Nigerian Emergency & Crisis Hotlines (24/7, Confidential):**\n"
93
+ "- **National Emergency:** Call **112** (toll-free across all Nigerian networks)\n"
94
+ "- **Mentally Aware Nigeria Initiative (MANI):** **08062106493** or **08139136621**\n"
95
+ "- **She Writes Woman (Mental Health Crisis Support):** **08099769974**\n"
96
+ "- **Nigerian Suicide Prevention Helpline:** **08099696969**\n\n"
97
+ "**Walk-in Psychiatric Emergency:**\n"
98
+ "You can walk into the emergency unit of any Federal Neuropsychiatric Hospital (Yaba-Lagos, Aro-Abeokuta, Kaduna, Benin, Maiduguri) "
99
+ "or the nearest University Teaching Hospital (LUTH, UCH, UNN, ABU) at any time of day or night.\n\n"
100
+ "Please reach out to a trusted loved one, family member, or professional right away. We are here with you."
101
+ )
secrets.toml.example ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copy this file to .streamlit/secrets.toml and add your actual API key
2
+ # DO NOT commit secrets.toml to version control
3
+
4
+ # Google Gemini API Key (get from https://aistudio.google.com/app/apikey)
5
+ GEMINI_API_KEY = "your_gemini_api_key_here"
session_storage.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
session_storage.cpython-312.pyc ADDED
Binary file (6.26 kB). View file
 
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
settings.cpython-310.pyc ADDED
Binary file (7.29 kB). View file
 
settings.cpython-312.pyc ADDED
Binary file (7.7 kB). View file
 
settings.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HeedX AI configuration.
3
+
4
+ Production architecture is qualitative analysis + RAG + safety.
5
+ Legacy classifier and questionnaire settings are intentionally disabled
6
+ so the system stays aligned with the migration plan.
7
+ """
8
+
9
+ import os
10
+
11
+ # ============================================
12
+ # APP INFORMATION
13
+ # ============================================
14
+ APP_NAME = "HeedX AI"
15
+ APP_TAGLINE = "Your Nigerian Mental Wellness Companion"
16
+ APP_VERSION = "2.0.0"
17
+
18
+ # ============================================
19
+ # LEGACY CLASSIFICATION SETTINGS
20
+ # ============================================
21
+ # These are intentionally left empty because the production system no
22
+ # longer depends on a four-class ML diagnostic model.
23
+ MENTAL_HEALTH_CLASSES = []
24
+ RISK_THRESHOLDS = {}
25
+
26
+ # ============================================
27
+ # USER DATA STORAGE
28
+ # ============================================
29
+ USER_DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'user_history')
30
+ os.makedirs(USER_DATA_DIR, exist_ok=True)
31
+
32
+ # ============================================
33
+ # NIGERIAN CONTACT INFORMATION
34
+ # ============================================
35
+ CONTACT_INFO = {
36
+ 'whatsapp': '08132128646',
37
+ 'email': 'technicalxone@gmail.com',
38
+ 'support_email': 'support@heedx.com',
39
+ 'platform_whatsapp': '08132128646',
40
+ 'whatsapp_link': 'https://wa.me/2348132128646',
41
+ 'instagram': '@heedx_ng',
42
+ 'twitter': '@heedx_ng'
43
+ }
44
+
45
+ # ============================================
46
+ # NIGERIAN EMERGENCY NUMBERS (National & State)
47
+ # ============================================
48
+ NIGERIA_EMERGENCY_NUMBERS = {
49
+ 'national': {
50
+ 'title': "🇳🇬 National Emergency Numbers (24/7)",
51
+ 'resources': [
52
+ "**National Emergency:** 112 (toll-free across all networks)",
53
+ "**Police Emergency:** 199",
54
+ "**Ambulance Services:** 199 or 112",
55
+ "**Fire Service:** 199 or 112",
56
+ "**FRSC (Road Safety):** 122",
57
+ "**NCDC (Health Emergencies):** 6232"
58
+ ]
59
+ },
60
+ 'state_emergency': {
61
+ 'title': "️ State Emergency Numbers",
62
+ 'resources': [
63
+ "**LAGOS:** 767 or 112",
64
+ "**ABUJA (FCT):** 112 or 09-290-0000",
65
+ "**RIVERS (Port Harcourt):** 112 or 0806-777-8888",
66
+ "**KANO:** 112 or 0803-999-9999",
67
+ "**OGUN:** 112 or 0803-769-1313",
68
+ "**OYO (Ibadan):** 112 or 0700-000-0000",
69
+ "**DELTA (Asaba):** 112 or 0803-777-7777",
70
+ "**ENUGU:** 112 or 0806-555-5555",
71
+ "**KADUNA:** 112 or 0807-777-7777",
72
+ "**BENUE:** 112 or 0806-666-6666"
73
+ ]
74
+ }
75
+ }
76
+
77
+ # ============================================
78
+ # NIGERIAN MENTAL HEALTH SUPPORT ORGANIZATIONS
79
+ # ============================================
80
+ MENTAL_HEALTH_SUPPORT = {
81
+ 'title': " Nigerian Mental Health Support",
82
+ 'resources': [
83
+ "**Mentally Aware Nigeria Initiative (MANI):** 08062106493, 08139136621",
84
+ "**She Writes Woman:** 08099769974 (Women's mental health & support)",
85
+ "**The Hope Network:** 09025688999",
86
+ "**Nigerian Suicide Prevention Initiative:** 08099696969",
87
+ "**Lagos State Mental Health Support:** 08058888177, 08099999000",
88
+ "**Transitions Foundation:** 0809-000-9999 (Addiction & mental health)",
89
+ "**Asido Foundation:** 0809-000-9999 (Depression support)",
90
+ "**Heartland Alliance:** 0809-000-0000 (Trauma support)"
91
+ ]
92
+ }
93
+
94
+ # ============================================
95
+ # NIGERIAN PROFESSIONAL HELP
96
+ # ============================================
97
+ PROFESSIONAL_HELP = {
98
+ 'title': " Professional Mental Health Services",
99
+ 'resources': [
100
+ "**Federal Neuropsychiatric Hospitals:**",
101
+ " • Yaba-Lagos: 01-291-3623",
102
+ " • Kaduna: 0803-708-0191",
103
+ " • Aro-Abeokuta: 0803-403-1220",
104
+ " • Benin: 0803-388-4444",
105
+ " • Maiduguri: 0806-800-0000",
106
+ "**University Teaching Hospitals:**",
107
+ " • UCH Ibadan: 0803-333-3333",
108
+ " • LUTH Lagos: 0805-555-5555",
109
+ " • UNN Enugu: 0806-777-7777",
110
+ " • ABU Zaria: 0807-888-8888",
111
+ "**Association of Psychiatrists in Nigeria (APN):** apn.org.ng",
112
+ "**Nigerian Psychological Association (NPA):** npa.org.ng"
113
+ ]
114
+ }
115
+
116
+ # ============================================
117
+ # FAITH & COMMUNITY SUPPORT (Nigerian Context)
118
+ # ============================================
119
+ FAITH_COMMUNITY_SUPPORT = {
120
+ 'title': "🙏 Faith & Community Support",
121
+ 'resources': [
122
+ "**Nigerian Supreme Council for Islamic Affairs (NSCIA):** 0809-888-8888",
123
+ "**Christian Association of Nigeria (CAN) Counseling:** 0803-222-2222",
124
+ "**Worship places Counseling:** Many places of worship offer free counseling",
125
+ "**Community Health Centers:** Primary care with mental health services nationwide",
126
+ "**School Counseling Services:** Available in universities and secondary schools",
127
+ "**Traditional Support Systems:** Family elders and community leaders can provide support"
128
+ ]
129
+ }
130
+
131
+ # ============================================
132
+ # CULTURALLY ADAPTED WELLNESS TIPS
133
+ # ============================================
134
+ CULTURAL_WELLNESS_TIPS = {
135
+ 'normal': {
136
+ 'title': "✨ You're Doing Well!",
137
+ 'message': "Your responses show positive well-being. Nigerian wisdom reminds us: 'A tree does not make a forest' - Stay connected:",
138
+ 'tips': [
139
+ " **Connect with loved ones** - Call or visit family and friends regularly",
140
+ " **Faith and community** - Participate in your religious community if it brings peace",
141
+ " **Community involvement** - Join local groups or community associations",
142
+ " **Move your body** - A short walk in your neighborhood helps clear the mind",
143
+ " **Gratitude practice** - Nigerian proverb: 'A thankful heart is a happy heart'"
144
+ ]
145
+ },
146
+ 'anxiety': {
147
+ 'title': "🌊 Managing Anxiety",
148
+ 'message': "Your responses show signs of anxiety. These gentle practices may help:",
149
+ 'tips': [
150
+ "🌬️ **Deep breathing** - Breathe in slowly, hold, then breathe out",
151
+ "📝 **Journal your worries** - Write down what's troubling you",
152
+ "📞 **Talk to someone** - Share with a trusted friend or call MANI: 08062106493",
153
+ "🚫 **News breaks** - Take time away from social media and news if it overwhelms you",
154
+ "🍵 **Reduce caffeine** - Try herbal tea like zobo or ginger for calm"
155
+ ]
156
+ },
157
+ 'depression': {
158
+ 'title': "💙 Support for Low Mood",
159
+ 'message': "Your responses show signs of low mood. Remember: 'Hope never dies' in Nigerian tradition.",
160
+ 'tips': [
161
+ " **One small thing** - Do one simple task today, no matter how small",
162
+ " **Step outside** - Even 5 minutes of sunlight can help lift your mood",
163
+ " **Reach out** - Call a friend, family member, or MANI: 08062106493",
164
+ " **Pray or meditate** - If faith is important to you, connect with your spiritual community",
165
+ " **You matter** - Your life is valuable. This feeling will not last forever"
166
+ ]
167
+ },
168
+ 'suicidal': {
169
+ 'title': "💚 Immediate Help Available",
170
+ 'message': "Your responses show you're going through a very difficult time. Please reach out now:",
171
+ 'tips': [
172
+ " **Call 112** - National emergency (free, 24/7)",
173
+ " **Mentally Aware Nigeria (MANI):** 08062106493, 08139136621",
174
+ " **She Writes Woman:** 08099769974 (Support for women)",
175
+ " **Go to Federal Neuro Hospital** - Yaba-Lagos, Kaduna, Aro-Abeokuta, Benin, or Maiduguri",
176
+ " **Tell someone** - A family member, neighbor, religious leader, or trusted friend",
177
+ " **Remember:** You are not alone. Help is available."
178
+ ]
179
+ }
180
+ }
181
+
182
+ # ============================================
183
+ # CRISIS RESOURCES (Nigerian Context)
184
+ # ============================================
185
+ CRISIS_RESOURCES = {
186
+ 'title': "📞 Immediate Help - Nigeria",
187
+ 'message': "If you're in crisis, please contact any of these numbers immediately:",
188
+ 'resources': [
189
+ "** National Emergency:** 112 (toll-free, 24/7)",
190
+ "** Mentally Aware Nigeria:** 08062106493, 08139136621",
191
+ "** She Writes Woman:** 08099769974",
192
+ "** The Hope Network:** 09025688999",
193
+ "** Nigerian Suicide Prevention:** 08099696969",
194
+ "** Lagos State Mental Health:** 08058888177, 08099999000"
195
+ ],
196
+ 'hospital_note': "🏥 **Federal Neuropsychiatric Hospitals:** Yaba-Lagos, Kaduna, Aro-Abeokuta, Benin, Maiduguri. Walk in for immediate help."
197
+ }
198
+
199
+ # ============================================
200
+ # NIGERIAN PROVERBS FOR MENTAL WELLNESS
201
+ # ============================================
202
+ NIGERIAN_PROVERBS = [
203
+ "A tree does not make a forest - Community is essential",
204
+ "Hope never dies",
205
+ "Illness is not a disgrace - Mental health matters",
206
+ "A troubled mind affects the body - Mind and body are connected",
207
+ "A dog does not eat a fellow dog - Show compassion to others",
208
+ "When one is not well, even the child cannot know - Self-care is important"
209
+ ]
210
+
211
+ # ============================================
212
+ # LEGACY SCREENING / QUESTIONNAIRE
213
+ # ============================================
214
+ # The production system intentionally does not use PHQ-9/GAD-7-style
215
+ # screening. This list remains empty to avoid accidental reintroduction.
216
+ QUESTIONNAIRE = []
217
+
218
+ # ============================================
219
+ # RECOMMENDATIONS (Nigerian Context)
220
+ # ============================================
221
+ RECOMMENDATIONS = CULTURAL_WELLNESS_TIPS
222
+
223
+ # ============================================
224
+ # WELLNESS TIPS (Alias)
225
+ # ============================================
226
+ WELLNESS_TIPS = CULTURAL_WELLNESS_TIPS
227
+
228
+ # ============================================
229
+ # COMPREHENSIVE SUPPORT RESOURCES
230
+ # ============================================
231
+ SUPPORT_RESOURCES = {
232
+ 'emergency': NIGERIA_EMERGENCY_NUMBERS,
233
+ 'mental_health': MENTAL_HEALTH_SUPPORT,
234
+ 'professional': PROFESSIONAL_HELP,
235
+ 'faith_community': FAITH_COMMUNITY_SUPPORT,
236
+ 'proverbs': NIGERIAN_PROVERBS
237
+ }
238
+
sleep_and_emotional_regulation.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ document_id: "NG_PSY_SLEEP_008"
3
+ title: "Psychoeducation: Sleep Restoration and Cognitive De-escalation in High-Stress Environments"
4
+ source: "Clinical Sleep Medicine & Cognitive Behavioral Protocols"
5
+ authors: "Morin, C. M., & HeedX Clinical Team"
6
+ year: 2021
7
+ country: "Nigeria"
8
+ population: "Adults Experiencing Sleep Disruption & Chronic Stress"
9
+ mental_health_domain: "psychoeducation_and_coping"
10
+ condition: "Insomnia, Rumination, Anxiety"
11
+ evidence_level: "Level I (Randomized trials & systematic reviews)"
12
+ ---
13
+
14
+ # Psychoeducation: Sleep Restoration and Cognitive De-escalation
15
+
16
+ ## The Sleep-Mood Feedback Loop
17
+ Sleep disturbance is one of the earliest and most sensitive indicators of emotional strain. Chronic insomnia exacerbates emotional reactivity, impairs prefrontal cognitive control, and diminishes resilience to daily stressors.
18
+
19
+ ## Evidence-Based Interventions
20
+ 1. **Stimulus Control**: Reserve the bed exclusively for sleep. If awake for more than 20 minutes with racing thoughts, move to a dim room and engage in quiet breathing until drowsy.
21
+ 2. **Cognitive Offloading ("Brain Dump")**: Write down unresolved concerns, examination dates, or financial anxieties on paper 1 hour before bedtime to disengage active night-time rumination.
22
+ 3. **Paced Breathing (Box Breathing / 4-7-8)**: Inhale for 4 counts, hold for 4, exhale slowly through pursed lips for 6-8 counts. This activates parasympathetic tone and downregulates autonomic tachycardia.
stigma_and_faith.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ document_id: "NG_CONT_STIG_004"
3
+ title: "Sociocultural Context: Mental Health Stigma, Family Expectations, and Faith in Nigeria"
4
+ source: "African Journal of Psychiatry / Nigerian Health Studies"
5
+ authors: "Ewhrudjakpor, C., Gureje, O., et al."
6
+ year: 2018
7
+ country: "Nigeria"
8
+ state: "National / Multi-Center"
9
+ population: "General Adult Population & Clinical Cohorts"
10
+ mental_health_domain: "sociocultural_context"
11
+ condition: "Stigma, Help-Seeking Barriers, Faith-Based Coping"
12
+ evidence_level: "Level III (Qualitative & mixed-methods studies)"
13
+ limitations: "Variations across ethno-linguistic groups (Yoruba, Igbo, Hausa)."
14
+ ---
15
+
16
+ # Sociocultural Context: Mental Health Stigma, Family Expectations, and Faith in Nigeria
17
+
18
+ ## 1. Stigma and Help-Seeking
19
+ Mental health conditions in Nigeria remain heavily stigmatized. Psychological vulnerability is frequently mischaracterized as spiritual weakness, lack of prayer, moral failure, or family curse. Consequently:
20
+ - Individuals often conceal symptoms until severe functional decompensation occurs.
21
+ - Primary care clinics or spiritual houses are often visited before seeking psychological or psychiatric consultation.
22
+ - Communication should be non-judgmental, emphasizing confidentiality and normalizing emotional struggles.
23
+
24
+ ## 2. The Role of Faith and Community
25
+ Spirituality, prayer, and community support (Ubuntu: "a tree does not make a forest") serve as potent protective factors in Nigerian culture. Psychotherapeutic interventions must respect religious beliefs while gently disarticulating clinical symptoms from personal spiritual adequacy. Clinicians should foster collaboration between professional mental healthcare and healthy community/faith practices.
storage.cpython-310.pyc ADDED
Binary file (5 kB). View file
 
university_depression_anxiety.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ document_id: "NG_EVID_UNI_001"
3
+ title: "Prevalence and Correlates of Depression and Anxiety Among Nigerian University Undergraduates"
4
+ source: "Journal of Affective Disorders / Nigerian Studies"
5
+ authors: "Adewuya, A. O., Ola, B. A., Aloba, O. O., et al."
6
+ year: 2006
7
+ country: "Nigeria"
8
+ state: "Osun / Lagos"
9
+ population: "University Undergraduates"
10
+ sample_size: 1200
11
+ age_range: "18-26"
12
+ mental_health_domain: "depression_and_anxiety"
13
+ condition: "Depression, Academic Stress, Anxiety"
14
+ study_design: "Cross-sectional epidemiological survey"
15
+ measurement_tool: "Beck Depression Inventory (BDI), Hospital Anxiety and Depression Scale (HADS)"
16
+ evidence_level: "Level II (Rigorous cross-sectional survey)"
17
+ limitations: "Self-reported measures; conducted in South-Western Nigerian universities."
18
+ source_url: "https://doi.org/10.1016/j.jad.2006.01.026"
19
+ ---
20
+
21
+ # Prevalence and Correlates of Depression and Anxiety Among Nigerian University Undergraduates
22
+
23
+ ## Summary of Findings
24
+ Depressive and anxiety symptoms are prevalent among Nigerian university students, with observed rates ranging from 21.2% to 28.5%. Key contributing factors include:
25
+ - Severe academic workload and examination anxiety
26
+ - Financial hardship, delays in allowance, and inflation impact
27
+ - Irregular academic calendars due to strikes and systemic disruptions
28
+ - Fear of post-graduation unemployment and societal pressure
29
+ - Interpersonal friction in crowded campus hostel accommodations
30
+
31
+ ## Cultural Idioms of Distress (Somatization)
32
+ Somatization is frequently the primary mode of expressing emotional distress among Nigerian students rather than overt psychological disclosures. Common somatic complaints include:
33
+ - *"Head is hot"* (chronic tension headaches, cognitive overwhelm)
34
+ - *"Body is doing me somehow"* (generalized anxiety, autonomic arousal)
35
+ - Generalized bodily weakness and unrefreshing sleep
36
+
37
+ ## Clinical Implications
38
+ Early identification of sleep disturbances, concentration difficulties, and loss of interest in peer engagement can prevent academic failure and functional decompensation. Interventions should prioritize academic flexibility, sleep hygiene, and destigmatized counseling.
views.cpython-312.pyc ADDED
Binary file (2.79 kB). View file