Spaces:
Paused
Paused
File size: 12,117 Bytes
823a3a8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | """
Core analysis engine: sentence-level prediction and aggregation
"""
import pandas as pd
import numpy as np
from collections import Counter
import re
from .preprocessing import preprocess_text, split_sentences
from .lexicons import (
INTENSITY_KEYWORDS, RESILIENCE_KEYWORDS, CRISIS_TRIGGERS,
NEGATIONS, WELLNESS_KEYWORDS
)
from config.settings import RISK_THRESHOLDS
class MentalHealthAnalyzer:
"""
Evolved Analysis Engine: Incorporates Sentiment, Intensity, Negation,
and Hybrid Rule-Based Safety logic.
"""
def __init__(self, model, classes):
"""
Initialize with loaded pipeline model
"""
self.model = model
self.classes = classes
self.sentence_predictions = []
self.aggregated_results = {}
# Intensity and Crisis Lexicons for Explainable AI
self.intensity_keywords = INTENSITY_KEYWORDS
self.resilience_keywords = RESILIENCE_KEYWORDS
self.crisis_triggers = CRISIS_TRIGGERS
self.negations = NEGATIONS
self.wellness_keywords = WELLNESS_KEYWORDS
self.classes_list = list(self.classes)
self.thresholds = RISK_THRESHOLDS
def _detect_negation(self, sentence):
"""Detects if a negation word is present in the sentence"""
words = preprocess_text(sentence).split()
return any(neg in words for neg in self.negations)
def _calculate_intensity(self, sentence):
"""Calculates emotional intensity based on modifiers"""
score = 1.0
words = preprocess_text(sentence).split()
for word in words:
if word in self.intensity_keywords['high']: score += 0.5
if word in self.intensity_keywords['moderate']: score += 0.2
return min(score, 2.5) # Cap intensity multiplier
def _detect_resilience(self, sentence):
"""Detects if the user is expressing hope or recovery intent"""
words = preprocess_text(sentence).split()
return any(word in words for word in self.resilience_keywords)
def analyze_response(self, text, question_id=None):
"""
Analyze a single response by breaking into sentences
Returns list of sentence-level predictions
"""
if not text:
return []
# Split into sentences
sentences = split_sentences(text)
results = []
for sentence in sentences:
if len(sentence.split()) < 2: # Skip very short sentences
continue
# 1. Preprocessing & ML Classification
cleaned = preprocess_text(sentence)
prediction = self.model.predict([cleaned])[0]
# 2. Hybrid Safety Engine (Rule-based check on cleaned text)
is_crisis = any(re.search(pattern, cleaned) for pattern in self.crisis_triggers)
has_negation = self._detect_negation(sentence)
# Crisis intent is only confirmed if keywords are present AND NOT negated
actual_crisis_intent = is_crisis and not has_negation
intensity = self._calculate_intensity(sentence)
has_resilience = self._detect_resilience(sentence)
# Get prediction confidence (probabilities)
try:
decision_scores = self.model.decision_function([cleaned])[0]
exp_scores = np.exp(decision_scores - np.max(decision_scores))
probs = exp_scores / exp_scores.sum()
confidence = probs[self.classes_list.index(prediction)]
except:
confidence = None
# 3. Logic-Based Adjustments (Controlled Intelligence)
# If negation is found in a 'suicidal' or 'depression' prediction,
# reduce confidence significantly unless it's a crisis trigger.
if has_negation:
# Check if this is a "Negated Wellness" phrase (e.g., "not okay")
is_negated_wellness = any(word in sentence.lower() for word in self.wellness_keywords)
# Case 1: Negated Wellness Override (e.g., "not okay", "not ky")
if is_negated_wellness and prediction == 'normal':
prediction = 'depression' # Force to distress category
if confidence is not None: confidence = max(confidence, 0.5)
elif prediction == 'suicidal' or is_crisis:
if not is_negated_wellness:
# If they said "not suicidal" or "not kill myself", force to normal
prediction = 'normal'
if confidence: confidence = 0.9 # Confident it's a negation
elif prediction in ['depression', 'anxiety'] and not is_negated_wellness:
# General negation halving only applies if not negating wellness
if confidence: confidence *= 0.5
if confidence and confidence < 0.3: prediction = 'normal'
# Resilience Offset: If they express hope, slightly lower the distress confidence
if has_resilience and prediction in ['depression', 'anxiety']:
confidence *= 0.8
results.append({
'sentence': sentence,
'prediction': 'suicidal' if actual_crisis_intent else prediction,
'confidence': confidence,
'intensity': intensity,
'has_negation': has_negation,
'is_crisis_rule': actual_crisis_intent,
'question_id': question_id,
'markers': self._extract_markers(sentence),
'is_resilient': has_resilience
})
return results
def analyze_all_responses(self, responses_dict):
"""
Analyze all questionnaire responses
responses_dict: {question_id: response_text}
"""
all_predictions = []
for q_id, response in responses_dict.items():
if response and response.strip():
sentence_results = self.analyze_response(response, q_id)
all_predictions.extend(sentence_results)
self.sentence_predictions = all_predictions
self.aggregated_results = self._aggregate_predictions()
return self.sentence_predictions
def _extract_markers(self, sentence):
"""Extracts explainable signals for the UI"""
cleaned = preprocess_text(sentence)
words = cleaned.split()
# Extract from intensity, resilience, and crisis patterns
# Extract from intensity, resilience, and crisis patterns
found = []
# Prioritize high-risk and specific overrides first
if any(re.search(p, cleaned) for p in self.crisis_triggers): found.append("crisis-intent")
if any(neg in words for neg in self.negations) and any(well in words for well in self.wellness_keywords):
found.append("negated-wellness")
found += [w for w in words if any(w in l for l in self.intensity_keywords.values())]
found += [w for w in words if w in self.resilience_keywords]
return list(dict.fromkeys(found))[:3] # Remove duplicates while keeping order
def _aggregate_predictions(self):
"""
Advanced Aggregation: Uses weighted scores based on intensity and confidence
"""
if not self.sentence_predictions:
return {}
total = len(self.sentence_predictions)
# Weighted Aggregation Logic
weighted_scores = {cls: 0.0 for cls in self.classes}
for p in self.sentence_predictions:
# Weight = Confidence * Intensity
weight = (p['confidence'] or 0.5) * p['intensity']
weighted_scores[p['prediction']] += weight
total_weight = sum(weighted_scores.values())
# Safety check: avoid division by zero
if total_weight == 0:
weighted_scores['normal'] = 1.0
total_weight = 1.0
# Calculate percentages
distribution = {}
for class_name in self.classes:
distribution[class_name] = (weighted_scores[class_name] / total_weight * 100) if total_weight > 0 else 0
# Find primary and secondary indicators
sorted_classes = sorted(distribution.items(), key=lambda x: x[1], reverse=True)
# Contextual Continuity Logic: Detect if risk is escalating
escalation = False
if len(self.sentence_predictions) > 3:
# Check if latter half of sentences have higher distress than first half
half = len(self.sentence_predictions) // 2
first_half_distress = sum(1 for p in self.sentence_predictions[:half] if p['prediction'] != 'normal')
second_half_distress = sum(1 for p in self.sentence_predictions[half:] if p['prediction'] != 'normal')
if second_half_distress > first_half_distress:
escalation = True
result = {
'total_sentences': total,
'distribution': distribution,
'primary_indicator': sorted_classes[0][0] if sorted_classes else None,
'primary_percentage': sorted_classes[0][1] if sorted_classes else 0,
'secondary_indicator': sorted_classes[1][0] if len(sorted_classes) > 1 else None,
'secondary_percentage': sorted_classes[1][1] if len(sorted_classes) > 1 else 0,
'raw_predictions': self.sentence_predictions,
'continuity': {
'escalating_distress': escalation,
'resilience_count': sum(1 for p in self.sentence_predictions if p['is_resilient'])
}
}
return result
def get_risk_level(self):
"""
Determine risk level based on aggregated predictions
"""
if not self.aggregated_results:
return "unknown"
dist = self.aggregated_results['distribution']
suicidal_pct = dist.get('suicidal', 0)
# Base Risk Level
risk_level = "mild"
# High intensity suicidal indicators trigger high risk immediately
if suicidal_pct >= self.thresholds['suicidal_high_risk'] or \
any(p['is_crisis_rule'] for p in self.sentence_predictions):
risk_level = "high"
elif suicidal_pct >= self.thresholds['suicidal_moderate']:
risk_level = "moderate_high"
elif (dist.get('depression', 0) + dist.get('anxiety', 0)) >= self.thresholds['depression_anxiety_threshold']:
risk_level = "moderate"
elif dist.get('normal', 0) >= 60:
risk_level = "low"
# Contextual Escalation Adjustment: Promote risk if distress is growing
if self.aggregated_results.get('continuity', {}).get('escalating_distress'):
if risk_level == "moderate": risk_level = "moderate_high"
elif risk_level == "mild": risk_level = "moderate"
return risk_level
def get_suicidal_flagged_sentences(self):
"""
Return all sentences flagged as suicidal for review
"""
if not self.sentence_predictions:
return []
return [p for p in self.sentence_predictions if p['prediction'] == 'suicidal']
def create_distribution_dataframe(distribution):
"""
Create a formatted DataFrame for visualization
"""
df = pd.DataFrame({
'Mental Health Indicator': list(distribution.keys()),
'Percentage': list(distribution.values())
})
return df.sort_values('Percentage', ascending=False) |