Spaces:
Paused
Paused
Delete utils
Browse files- utils/__init__.py +0 -2
- utils/__init__.py.py +0 -2
- utils/__pycache__/__init__.cpython-310.pyc +0 -0
- utils/__pycache__/analysis.cpython-310.pyc +0 -0
- utils/__pycache__/lexicons.cpython-310.pyc +0 -0
- utils/__pycache__/preprocessing.cpython-310.pyc +0 -0
- utils/__pycache__/recommendations.cpython-310.pyc +0 -0
- utils/__pycache__/session_storage.cpython-310.pyc +0 -0
- utils/__pycache__/storage.cpython-310.pyc +0 -0
- utils/analysis.py +0 -284
- utils/analysis_service.ts +0 -0
- utils/forms.py +0 -11
- utils/lexicons.py +0 -90
- utils/models.py +0 -26
- utils/my id.py +0 -0
- utils/preprocessing.py +0 -121
- utils/recommendations.py +0 -59
- utils/services.py +0 -0
- utils/session_storage.py +0 -122
- utils/urls.py +0 -8
- utils/views.py +0 -41
utils/__init__.py
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
# utils/__init__.py
|
| 2 |
-
# This file makes the utils directory a Python package
|
|
|
|
|
|
|
|
|
utils/__init__.py.py
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
# utils/__init__.py
|
| 2 |
-
# This file makes the utils directory a Python package
|
|
|
|
|
|
|
|
|
utils/__pycache__/__init__.cpython-310.pyc
DELETED
|
Binary file (136 Bytes)
|
|
|
utils/__pycache__/analysis.cpython-310.pyc
DELETED
|
Binary file (9.41 kB)
|
|
|
utils/__pycache__/lexicons.cpython-310.pyc
DELETED
|
Binary file (3.3 kB)
|
|
|
utils/__pycache__/preprocessing.cpython-310.pyc
DELETED
|
Binary file (1.85 kB)
|
|
|
utils/__pycache__/recommendations.cpython-310.pyc
DELETED
|
Binary file (2 kB)
|
|
|
utils/__pycache__/session_storage.cpython-310.pyc
DELETED
|
Binary file (3.66 kB)
|
|
|
utils/__pycache__/storage.cpython-310.pyc
DELETED
|
Binary file (5 kB)
|
|
|
utils/analysis.py
DELETED
|
@@ -1,284 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Core analysis engine: sentence-level prediction and aggregation
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
import pandas as pd
|
| 6 |
-
import numpy as np
|
| 7 |
-
from collections import Counter
|
| 8 |
-
import re
|
| 9 |
-
from .preprocessing import preprocess_text, split_sentences
|
| 10 |
-
from .lexicons import (
|
| 11 |
-
INTENSITY_KEYWORDS, RESILIENCE_KEYWORDS, CRISIS_TRIGGERS,
|
| 12 |
-
NEGATIONS, WELLNESS_KEYWORDS
|
| 13 |
-
)
|
| 14 |
-
from config.settings import RISK_THRESHOLDS
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class MentalHealthAnalyzer:
|
| 18 |
-
"""
|
| 19 |
-
Evolved Analysis Engine: Incorporates Sentiment, Intensity, Negation,
|
| 20 |
-
and Hybrid Rule-Based Safety logic.
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
def __init__(self, model, classes):
|
| 24 |
-
"""
|
| 25 |
-
Initialize with loaded pipeline model
|
| 26 |
-
"""
|
| 27 |
-
self.model = model
|
| 28 |
-
self.classes = classes
|
| 29 |
-
self.sentence_predictions = []
|
| 30 |
-
self.aggregated_results = {}
|
| 31 |
-
|
| 32 |
-
# Intensity and Crisis Lexicons for Explainable AI
|
| 33 |
-
self.intensity_keywords = INTENSITY_KEYWORDS
|
| 34 |
-
self.resilience_keywords = RESILIENCE_KEYWORDS
|
| 35 |
-
self.crisis_triggers = CRISIS_TRIGGERS
|
| 36 |
-
self.negations = NEGATIONS
|
| 37 |
-
self.wellness_keywords = WELLNESS_KEYWORDS
|
| 38 |
-
self.classes_list = list(self.classes)
|
| 39 |
-
self.thresholds = RISK_THRESHOLDS
|
| 40 |
-
|
| 41 |
-
def _detect_negation(self, sentence):
|
| 42 |
-
"""Detects if a negation word is present in the sentence"""
|
| 43 |
-
words = preprocess_text(sentence).split()
|
| 44 |
-
return any(neg in words for neg in self.negations)
|
| 45 |
-
|
| 46 |
-
def _calculate_intensity(self, sentence):
|
| 47 |
-
"""Calculates emotional intensity based on modifiers"""
|
| 48 |
-
score = 1.0
|
| 49 |
-
words = preprocess_text(sentence).split()
|
| 50 |
-
for word in words:
|
| 51 |
-
if word in self.intensity_keywords['high']: score += 0.5
|
| 52 |
-
if word in self.intensity_keywords['moderate']: score += 0.2
|
| 53 |
-
return min(score, 2.5) # Cap intensity multiplier
|
| 54 |
-
|
| 55 |
-
def _detect_resilience(self, sentence):
|
| 56 |
-
"""Detects if the user is expressing hope or recovery intent"""
|
| 57 |
-
words = preprocess_text(sentence).split()
|
| 58 |
-
return any(word in words for word in self.resilience_keywords)
|
| 59 |
-
|
| 60 |
-
def analyze_response(self, text, question_id=None):
|
| 61 |
-
"""
|
| 62 |
-
Analyze a single response by breaking into sentences
|
| 63 |
-
Returns list of sentence-level predictions
|
| 64 |
-
"""
|
| 65 |
-
if not text:
|
| 66 |
-
return []
|
| 67 |
-
|
| 68 |
-
# Split into sentences
|
| 69 |
-
sentences = split_sentences(text)
|
| 70 |
-
results = []
|
| 71 |
-
|
| 72 |
-
for sentence in sentences:
|
| 73 |
-
if len(sentence.split()) < 2: # Skip very short sentences
|
| 74 |
-
continue
|
| 75 |
-
|
| 76 |
-
# 1. Preprocessing & ML Classification
|
| 77 |
-
cleaned = preprocess_text(sentence)
|
| 78 |
-
prediction = self.model.predict([cleaned])[0]
|
| 79 |
-
|
| 80 |
-
# 2. Hybrid Safety Engine (Rule-based check on cleaned text)
|
| 81 |
-
is_crisis = any(re.search(pattern, cleaned) for pattern in self.crisis_triggers)
|
| 82 |
-
has_negation = self._detect_negation(sentence)
|
| 83 |
-
# Crisis intent is only confirmed if keywords are present AND NOT negated
|
| 84 |
-
actual_crisis_intent = is_crisis and not has_negation
|
| 85 |
-
intensity = self._calculate_intensity(sentence)
|
| 86 |
-
has_resilience = self._detect_resilience(sentence)
|
| 87 |
-
|
| 88 |
-
# Get prediction confidence (probabilities)
|
| 89 |
-
try:
|
| 90 |
-
decision_scores = self.model.decision_function([cleaned])[0]
|
| 91 |
-
exp_scores = np.exp(decision_scores - np.max(decision_scores))
|
| 92 |
-
probs = exp_scores / exp_scores.sum()
|
| 93 |
-
confidence = probs[self.classes_list.index(prediction)]
|
| 94 |
-
except:
|
| 95 |
-
confidence = None
|
| 96 |
-
|
| 97 |
-
# 3. Logic-Based Adjustments (Controlled Intelligence)
|
| 98 |
-
# If negation is found in a 'suicidal' or 'depression' prediction,
|
| 99 |
-
# reduce confidence significantly unless it's a crisis trigger.
|
| 100 |
-
if has_negation:
|
| 101 |
-
# Check if this is a "Negated Wellness" phrase (e.g., "not okay")
|
| 102 |
-
is_negated_wellness = any(word in sentence.lower() for word in self.wellness_keywords)
|
| 103 |
-
|
| 104 |
-
# Case 1: Negated Wellness Override (e.g., "not okay", "not ky")
|
| 105 |
-
if is_negated_wellness and prediction == 'normal':
|
| 106 |
-
prediction = 'depression' # Force to distress category
|
| 107 |
-
if confidence is not None: confidence = max(confidence, 0.5)
|
| 108 |
-
|
| 109 |
-
elif prediction == 'suicidal' or is_crisis:
|
| 110 |
-
if not is_negated_wellness:
|
| 111 |
-
# If they said "not suicidal" or "not kill myself", force to normal
|
| 112 |
-
prediction = 'normal'
|
| 113 |
-
if confidence: confidence = 0.9 # Confident it's a negation
|
| 114 |
-
|
| 115 |
-
elif prediction in ['depression', 'anxiety'] and not is_negated_wellness:
|
| 116 |
-
# General negation halving only applies if not negating wellness
|
| 117 |
-
if confidence: confidence *= 0.5
|
| 118 |
-
if confidence and confidence < 0.3: prediction = 'normal'
|
| 119 |
-
|
| 120 |
-
# Resilience Offset: If they express hope, slightly lower the distress confidence
|
| 121 |
-
if has_resilience and prediction in ['depression', 'anxiety']:
|
| 122 |
-
confidence *= 0.8
|
| 123 |
-
|
| 124 |
-
results.append({
|
| 125 |
-
'sentence': sentence,
|
| 126 |
-
'prediction': 'suicidal' if actual_crisis_intent else prediction,
|
| 127 |
-
'confidence': confidence,
|
| 128 |
-
'intensity': intensity,
|
| 129 |
-
'has_negation': has_negation,
|
| 130 |
-
'is_crisis_rule': actual_crisis_intent,
|
| 131 |
-
'question_id': question_id,
|
| 132 |
-
'markers': self._extract_markers(sentence),
|
| 133 |
-
'is_resilient': has_resilience
|
| 134 |
-
})
|
| 135 |
-
|
| 136 |
-
return results
|
| 137 |
-
|
| 138 |
-
def analyze_all_responses(self, responses_dict):
|
| 139 |
-
"""
|
| 140 |
-
Analyze all questionnaire responses
|
| 141 |
-
responses_dict: {question_id: response_text}
|
| 142 |
-
"""
|
| 143 |
-
all_predictions = []
|
| 144 |
-
|
| 145 |
-
for q_id, response in responses_dict.items():
|
| 146 |
-
if response and response.strip():
|
| 147 |
-
sentence_results = self.analyze_response(response, q_id)
|
| 148 |
-
all_predictions.extend(sentence_results)
|
| 149 |
-
|
| 150 |
-
self.sentence_predictions = all_predictions
|
| 151 |
-
self.aggregated_results = self._aggregate_predictions()
|
| 152 |
-
|
| 153 |
-
return self.sentence_predictions
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def _extract_markers(self, sentence):
|
| 157 |
-
"""Extracts explainable signals for the UI"""
|
| 158 |
-
cleaned = preprocess_text(sentence)
|
| 159 |
-
words = cleaned.split()
|
| 160 |
-
|
| 161 |
-
# Extract from intensity, resilience, and crisis patterns
|
| 162 |
-
|
| 163 |
-
# Extract from intensity, resilience, and crisis patterns
|
| 164 |
-
found = []
|
| 165 |
-
|
| 166 |
-
# Prioritize high-risk and specific overrides first
|
| 167 |
-
if any(re.search(p, cleaned) for p in self.crisis_triggers): found.append("crisis-intent")
|
| 168 |
-
if any(neg in words for neg in self.negations) and any(well in words for well in self.wellness_keywords):
|
| 169 |
-
found.append("negated-wellness")
|
| 170 |
-
found += [w for w in words if any(w in l for l in self.intensity_keywords.values())]
|
| 171 |
-
found += [w for w in words if w in self.resilience_keywords]
|
| 172 |
-
return list(dict.fromkeys(found))[:3] # Remove duplicates while keeping order
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
def _aggregate_predictions(self):
|
| 178 |
-
"""
|
| 179 |
-
Advanced Aggregation: Uses weighted scores based on intensity and confidence
|
| 180 |
-
"""
|
| 181 |
-
if not self.sentence_predictions:
|
| 182 |
-
return {}
|
| 183 |
-
|
| 184 |
-
total = len(self.sentence_predictions)
|
| 185 |
-
|
| 186 |
-
# Weighted Aggregation Logic
|
| 187 |
-
weighted_scores = {cls: 0.0 for cls in self.classes}
|
| 188 |
-
|
| 189 |
-
for p in self.sentence_predictions:
|
| 190 |
-
# Weight = Confidence * Intensity
|
| 191 |
-
weight = (p['confidence'] or 0.5) * p['intensity']
|
| 192 |
-
weighted_scores[p['prediction']] += weight
|
| 193 |
-
|
| 194 |
-
total_weight = sum(weighted_scores.values())
|
| 195 |
-
|
| 196 |
-
# Safety check: avoid division by zero
|
| 197 |
-
if total_weight == 0:
|
| 198 |
-
weighted_scores['normal'] = 1.0
|
| 199 |
-
total_weight = 1.0
|
| 200 |
-
|
| 201 |
-
# Calculate percentages
|
| 202 |
-
distribution = {}
|
| 203 |
-
for class_name in self.classes:
|
| 204 |
-
distribution[class_name] = (weighted_scores[class_name] / total_weight * 100) if total_weight > 0 else 0
|
| 205 |
-
|
| 206 |
-
# Find primary and secondary indicators
|
| 207 |
-
sorted_classes = sorted(distribution.items(), key=lambda x: x[1], reverse=True)
|
| 208 |
-
|
| 209 |
-
# Contextual Continuity Logic: Detect if risk is escalating
|
| 210 |
-
escalation = False
|
| 211 |
-
if len(self.sentence_predictions) > 3:
|
| 212 |
-
# Check if latter half of sentences have higher distress than first half
|
| 213 |
-
half = len(self.sentence_predictions) // 2
|
| 214 |
-
first_half_distress = sum(1 for p in self.sentence_predictions[:half] if p['prediction'] != 'normal')
|
| 215 |
-
second_half_distress = sum(1 for p in self.sentence_predictions[half:] if p['prediction'] != 'normal')
|
| 216 |
-
if second_half_distress > first_half_distress:
|
| 217 |
-
escalation = True
|
| 218 |
-
|
| 219 |
-
result = {
|
| 220 |
-
'total_sentences': total,
|
| 221 |
-
'distribution': distribution,
|
| 222 |
-
'primary_indicator': sorted_classes[0][0] if sorted_classes else None,
|
| 223 |
-
'primary_percentage': sorted_classes[0][1] if sorted_classes else 0,
|
| 224 |
-
'secondary_indicator': sorted_classes[1][0] if len(sorted_classes) > 1 else None,
|
| 225 |
-
'secondary_percentage': sorted_classes[1][1] if len(sorted_classes) > 1 else 0,
|
| 226 |
-
'raw_predictions': self.sentence_predictions,
|
| 227 |
-
'continuity': {
|
| 228 |
-
'escalating_distress': escalation,
|
| 229 |
-
'resilience_count': sum(1 for p in self.sentence_predictions if p['is_resilient'])
|
| 230 |
-
}
|
| 231 |
-
}
|
| 232 |
-
|
| 233 |
-
return result
|
| 234 |
-
|
| 235 |
-
def get_risk_level(self):
|
| 236 |
-
"""
|
| 237 |
-
Determine risk level based on aggregated predictions
|
| 238 |
-
"""
|
| 239 |
-
if not self.aggregated_results:
|
| 240 |
-
return "unknown"
|
| 241 |
-
|
| 242 |
-
dist = self.aggregated_results['distribution']
|
| 243 |
-
suicidal_pct = dist.get('suicidal', 0)
|
| 244 |
-
|
| 245 |
-
# Base Risk Level
|
| 246 |
-
risk_level = "mild"
|
| 247 |
-
|
| 248 |
-
# High intensity suicidal indicators trigger high risk immediately
|
| 249 |
-
if suicidal_pct >= self.thresholds['suicidal_high_risk'] or \
|
| 250 |
-
any(p['is_crisis_rule'] for p in self.sentence_predictions):
|
| 251 |
-
risk_level = "high"
|
| 252 |
-
elif suicidal_pct >= self.thresholds['suicidal_moderate']:
|
| 253 |
-
risk_level = "moderate_high"
|
| 254 |
-
elif (dist.get('depression', 0) + dist.get('anxiety', 0)) >= self.thresholds['depression_anxiety_threshold']:
|
| 255 |
-
risk_level = "moderate"
|
| 256 |
-
elif dist.get('normal', 0) >= 60:
|
| 257 |
-
risk_level = "low"
|
| 258 |
-
|
| 259 |
-
# Contextual Escalation Adjustment: Promote risk if distress is growing
|
| 260 |
-
if self.aggregated_results.get('continuity', {}).get('escalating_distress'):
|
| 261 |
-
if risk_level == "moderate": risk_level = "moderate_high"
|
| 262 |
-
elif risk_level == "mild": risk_level = "moderate"
|
| 263 |
-
|
| 264 |
-
return risk_level
|
| 265 |
-
|
| 266 |
-
def get_suicidal_flagged_sentences(self):
|
| 267 |
-
"""
|
| 268 |
-
Return all sentences flagged as suicidal for review
|
| 269 |
-
"""
|
| 270 |
-
if not self.sentence_predictions:
|
| 271 |
-
return []
|
| 272 |
-
|
| 273 |
-
return [p for p in self.sentence_predictions if p['prediction'] == 'suicidal']
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def create_distribution_dataframe(distribution):
|
| 277 |
-
"""
|
| 278 |
-
Create a formatted DataFrame for visualization
|
| 279 |
-
"""
|
| 280 |
-
df = pd.DataFrame({
|
| 281 |
-
'Mental Health Indicator': list(distribution.keys()),
|
| 282 |
-
'Percentage': list(distribution.values())
|
| 283 |
-
})
|
| 284 |
-
return df.sort_values('Percentage', ascending=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/analysis_service.ts
DELETED
|
File without changes
|
utils/forms.py
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
from django import forms
|
| 2 |
-
|
| 3 |
-
class CheckInForm(forms.Form):
|
| 4 |
-
narration = forms.CharField(
|
| 5 |
-
widget=forms.Textarea(attrs={
|
| 6 |
-
'placeholder': 'Share your story or paste a professional observation here...',
|
| 7 |
-
'class': 'form-control',
|
| 8 |
-
'rows': 10
|
| 9 |
-
}),
|
| 10 |
-
label="Wellness Narration"
|
| 11 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/lexicons.py
DELETED
|
@@ -1,90 +0,0 @@
|
|
| 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 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/models.py
DELETED
|
@@ -1,26 +0,0 @@
|
|
| 1 |
-
from django.db import models
|
| 2 |
-
from django.contrib.auth.models import User
|
| 3 |
-
|
| 4 |
-
class CheckIn(models.Model):
|
| 5 |
-
"""Stores a single mental health assessment session."""
|
| 6 |
-
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
|
| 7 |
-
created_at = models.DateTimeField(auto_now_add=True)
|
| 8 |
-
|
| 9 |
-
# Aggregated Results
|
| 10 |
-
primary_indicator = models.CharField(max_length=50)
|
| 11 |
-
primary_percentage = models.FloatField()
|
| 12 |
-
risk_level = models.CharField(max_length=50)
|
| 13 |
-
|
| 14 |
-
# Raw Data and Distributions (PostgreSQL JSONField recommended)
|
| 15 |
-
responses = models.JSONField()
|
| 16 |
-
distribution = models.JSONField()
|
| 17 |
-
|
| 18 |
-
def __str__(self):
|
| 19 |
-
return f"Check-in {self.id} - {self.primary_indicator} ({self.created_at.date()})"
|
| 20 |
-
|
| 21 |
-
class SentenceAnalysis(models.Model):
|
| 22 |
-
"""Granular sentence-level analysis for the UI."""
|
| 23 |
-
checkin = models.ForeignKey(CheckIn, related_name='sentences', on_delete=models.CASCADE)
|
| 24 |
-
text = models.TextField()
|
| 25 |
-
label = models.CharField(max_length=50)
|
| 26 |
-
confidence = models.FloatField()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/my id.py
DELETED
|
File without changes
|
utils/preprocessing.py
DELETED
|
@@ -1,121 +0,0 @@
|
|
| 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()'''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/recommendations.py
DELETED
|
@@ -1,59 +0,0 @@
|
|
| 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 format_recommendations(self, recommendations_dict):
|
| 47 |
-
"""
|
| 48 |
-
Format recommendations for display
|
| 49 |
-
"""
|
| 50 |
-
if not recommendations_dict:
|
| 51 |
-
return ""
|
| 52 |
-
|
| 53 |
-
formatted = f"### {recommendations_dict['title']}\n\n"
|
| 54 |
-
formatted += f"{recommendations_dict['message']}\n\n"
|
| 55 |
-
|
| 56 |
-
for i, tip in enumerate(recommendations_dict['tips'], 1):
|
| 57 |
-
formatted += f"{i}. {tip}\n"
|
| 58 |
-
|
| 59 |
-
return formatted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/services.py
DELETED
|
File without changes
|
utils/session_storage.py
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/urls.py
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
from django.urls import path
|
| 2 |
-
from .views import CheckInCreateView, CheckInDetailView, HistoryListView
|
| 3 |
-
|
| 4 |
-
urlpatterns = [
|
| 5 |
-
path('checkin/', CheckInCreateView.as_view(), name='checkin-create'),
|
| 6 |
-
path('checkin/<int:pk>/', CheckInDetailView.as_view(), name='checkin-detail'),
|
| 7 |
-
path('history/', HistoryListView.as_view(), name='history'),
|
| 8 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/views.py
DELETED
|
@@ -1,41 +0,0 @@
|
|
| 1 |
-
from django.views.generic import FormView, DetailView, ListView
|
| 2 |
-
from django.shortcuts import redirect
|
| 3 |
-
from django.contrib.auth.mixins import LoginRequiredMixin
|
| 4 |
-
from django.core.exceptions import PermissionDenied
|
| 5 |
-
from .forms import CheckInForm
|
| 6 |
-
from .models import CheckIn
|
| 7 |
-
from .services import AnalysisService
|
| 8 |
-
|
| 9 |
-
class CheckInCreateView(LoginRequiredMixin, FormView):
|
| 10 |
-
template_name = 'backend/checkin_form.html'
|
| 11 |
-
form_class = CheckInForm
|
| 12 |
-
|
| 13 |
-
def form_valid(self, form):
|
| 14 |
-
service = AnalysisService()
|
| 15 |
-
# Match the dictionary structure the Analyzer expects
|
| 16 |
-
responses_dict = {'narration': form.cleaned_data['narration']}
|
| 17 |
-
|
| 18 |
-
checkin = service.perform_full_checkin(
|
| 19 |
-
user=self.request.user,
|
| 20 |
-
responses_dict=responses_dict
|
| 21 |
-
)
|
| 22 |
-
return redirect('checkin-detail', pk=checkin.pk)
|
| 23 |
-
|
| 24 |
-
class CheckInDetailView(LoginRequiredMixin, DetailView):
|
| 25 |
-
model = CheckIn
|
| 26 |
-
template_name = 'backend/checkin_detail.html'
|
| 27 |
-
context_object_name = 'checkin'
|
| 28 |
-
|
| 29 |
-
def get_object(self, queryset=None):
|
| 30 |
-
"""Ensure users can only access their own records."""
|
| 31 |
-
obj = super().get_object(queryset)
|
| 32 |
-
if obj.user != self.request.user and not self.request.user.is_staff:
|
| 33 |
-
raise PermissionDenied("You do not have permission to view this assessment.")
|
| 34 |
-
return obj
|
| 35 |
-
|
| 36 |
-
class HistoryListView(LoginRequiredMixin, ListView):
|
| 37 |
-
model = CheckIn
|
| 38 |
-
template_name = 'backend/history.html'
|
| 39 |
-
|
| 40 |
-
def get_queryset(self):
|
| 41 |
-
return CheckIn.objects.filter(user=self.request.user).order_by('-created_at')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|