File size: 14,144 Bytes
a2fd99a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import numpy as np
from typing import Dict, List, Optional
import json
from datetime import datetime, timedelta

class TreatmentPlanner:
    def __init__(self):
        self.treatment_protocols = self._load_treatment_protocols()
        self.intervention_strategies = self._load_intervention_strategies()
    
    def _load_treatment_protocols(self) -> Dict:
        """Load predefined treatment protocols"""
        return {
            'depression': {
                'psychotherapy': {
                    'primary': 'Cognitive Behavioral Therapy (CBT)',
                    'alternatives': [
                        'Interpersonal Therapy (IPT)',
                        'Behavioral Activation (BA)',
                        'Mindfulness-Based Cognitive Therapy (MBCT)'
                    ],
                    'duration': '12-16 weeks',
                    'frequency': 'Weekly'
                },
                'medication': {
                    'classes': [
                        'SSRIs',
                        'SNRIs',
                        'NDRIs',
                        'Atypical antidepressants'
                    ],
                    'duration': '6-12 months minimum',
                    'monitoring': 'Every 2-4 weeks initially'
                },
                'lifestyle': [
                    'Regular exercise (30 minutes daily)',
                    'Sleep hygiene improvement',
                    'Social engagement activities',
                    'Stress reduction techniques'
                ]
            },
            'anxiety': {
                'psychotherapy': {
                    'primary': 'Cognitive Behavioral Therapy (CBT)',
                    'alternatives': [
                        'Exposure Therapy',
                        'Acceptance and Commitment Therapy (ACT)',
                        'Dialectical Behavior Therapy (DBT)'
                    ],
                    'duration': '8-12 weeks',
                    'frequency': 'Weekly'
                },
                'medication': {
                    'classes': [
                        'SSRIs',
                        'SNRIs',
                        'Buspirone',
                        'Beta-blockers'
                    ],
                    'duration': 'As needed',
                    'monitoring': 'Every 2-4 weeks initially'
                },
                'lifestyle': [
                    'Relaxation techniques',
                    'Mindfulness meditation',
                    'Regular exercise',
                    'Stress management'
                ]
            },
            'ptsd': {
                'psychotherapy': {
                    'primary': 'Trauma-Focused CBT',
                    'alternatives': [
                        'EMDR',
                        'Prolonged Exposure Therapy',
                        'Cognitive Processing Therapy'
                    ],
                    'duration': '12-16 weeks',
                    'frequency': 'Weekly'
                },
                'medication': {
                    'classes': [
                        'SSRIs',
                        'SNRIs',
                        'Prazosin',
                        'Antipsychotics'
                    ],
                    'duration': '12 months minimum',
                    'monitoring': 'Every 2-4 weeks initially'
                },
                'lifestyle': [
                    'Stress management techniques',
                    'Sleep hygiene',
                    'Grounding exercises',
                    'Social support engagement'
                ]
            }
        }
    
    def _load_intervention_strategies(self) -> Dict:
        """Load intervention strategies based on severity and symptoms"""
        return {
            'mild': {
                'focus': 'Lifestyle modifications and psychoeducation',
                'monitoring': 'Monthly check-ins',
                'escalation_criteria': [
                    'Symptom worsening',
                    'Functional impairment',
                    'Lack of improvement after 4-6 weeks'
                ]
            },
            'moderate': {
                'focus': 'Psychotherapy with optional medication',
                'monitoring': 'Bi-weekly check-ins',
                'escalation_criteria': [
                    'Severe symptom exacerbation',
                    'Development of risk factors',
                    'Poor response to treatment'
                ]
            },
            'severe': {
                'focus': 'Intensive treatment with medication and therapy',
                'monitoring': 'Weekly check-ins',
                'escalation_criteria': [
                    'Crisis development',
                    'Safety concerns',
                    'Treatment resistance'
                ]
            }
        }
    
    def generate_plan(self, analysis_results: Dict) -> Dict:
        """Generate a comprehensive treatment plan based on analysis results"""
        try:
            # Extract relevant information from analysis
            conditions = analysis_results['condition_probabilities']
            severity = analysis_results['severity_assessment']
            
            # Generate treatment plan components
            treatment_plan = {
                'summary': self._generate_plan_summary(conditions, severity),
                'primary_interventions': self._select_primary_interventions(
                    conditions, severity
                ),
                'therapy_recommendations': self._generate_therapy_recommendations(
                    conditions, severity
                ),
                'medication_considerations': self._generate_medication_recommendations(
                    conditions, severity
                ),
                'lifestyle_modifications': self._generate_lifestyle_recommendations(
                    conditions
                ),
                'monitoring_plan': self._create_monitoring_plan(severity),
                'crisis_plan': self._create_crisis_plan(severity),
                'timeline': self._create_treatment_timeline(
                    conditions, severity
                )
            }
            
            return treatment_plan
            
        except Exception as e:
            return {
                'error': f'Error generating treatment plan: {str(e)}',
                'recommendations': self._generate_fallback_recommendations()
            }
    
    def _generate_plan_summary(
        self, conditions: Dict, severity: Dict
    ) -> Dict:
        """Generate a summary of the treatment plan"""
        primary_condition = max(conditions.items(), key=lambda x: x[1])[0]
        severity_level = self._determine_severity_level(severity['overall_severity'])
        
        return {
            'primary_condition': primary_condition,
            'severity_level': severity_level,
            'treatment_approach': self.intervention_strategies[severity_level]['focus'],
            'estimated_duration': self._estimate_treatment_duration(
                primary_condition, severity_level
            )
        }
    
    def _select_primary_interventions(
        self, conditions: Dict, severity: Dict
    ) -> List[str]:
        """Select primary interventions based on conditions and severity"""
        interventions = []
        severity_level = self._determine_severity_level(severity['overall_severity'])
        
        for condition, probability in conditions.items():
            if probability > 0.4:  # Consider conditions with significant probability
                protocol = self.treatment_protocols[condition]
                
                # Add primary therapy
                interventions.append(
                    f"Primary therapy: {protocol['psychotherapy']['primary']}"
                )
                
                # Add medication if moderate to severe
                if severity_level in ['moderate', 'severe']:
                    interventions.append(
                        f"Consider medication: {', '.join(protocol['medication']['classes'][:2])}"
                    )
        
        return interventions
    
    def _generate_therapy_recommendations(
        self, conditions: Dict, severity: Dict
    ) -> Dict:
        """Generate specific therapy recommendations"""
        therapy_plan = {}
        severity_level = self._determine_severity_level(severity['overall_severity'])
        
        for condition, probability in conditions.items():
            if probability > 0.3:
                protocol = self.treatment_protocols[condition]['psychotherapy']
                therapy_plan[condition] = {
                    'primary_therapy': protocol['primary'],
                    'alternatives': protocol['alternatives'][:2],
                    'frequency': protocol['frequency'],
                    'duration': protocol['duration']
                }
        
        return therapy_plan
    
    def _generate_medication_recommendations(
        self, conditions: Dict, severity: Dict
    ) -> Dict:
        """Generate medication recommendations"""
        medication_plan = {}
        severity_level = self._determine_severity_level(severity['overall_severity'])
        
        if severity_level in ['moderate', 'severe']:
            for condition, probability in conditions.items():
                if probability > 0.4:
                    protocol = self.treatment_protocols[condition]['medication']
                    medication_plan[condition] = {
                        'recommended_classes': protocol['classes'][:2],
                        'duration': protocol['duration'],
                        'monitoring': protocol['monitoring']
                    }
        
        return medication_plan
    
    def _generate_lifestyle_recommendations(self, conditions: Dict) -> List[str]:
        """Generate lifestyle modification recommendations"""
        recommendations = set()
        
        for condition, probability in conditions.items():
            if probability > 0.3:
                recommendations.update(
                    self.treatment_protocols[condition]['lifestyle']
                )
        
        return list(recommendations)
    
    def _create_monitoring_plan(self, severity: Dict) -> Dict:
        """Create a monitoring plan based on severity"""
        severity_level = self._determine_severity_level(severity['overall_severity'])
        strategy = self.intervention_strategies[severity_level]
        
        return {
            'frequency': strategy['monitoring'],
            'focus_areas': [
                'Symptom severity',
                'Treatment response',
                'Side effects',
                'Functional improvement'
            ],
            'escalation_criteria': strategy['escalation_criteria']
        }
    
    def _create_crisis_plan(self, severity: Dict) -> Dict:
        """Create a crisis intervention plan"""
        return {
            'warning_signs': [
                'Suicidal ideation',
                'Severe anxiety attacks',
                'Dissociative episodes',
                'Severe mood changes'
            ],
            'emergency_contacts': [
                'Primary therapist',
                'Crisis hotline',
                'Emergency services (911)',
                'Trusted support person'
            ],
            'immediate_actions': [
                'Contact emergency services if in immediate danger',
                'Use prescribed crisis medication if available',
                'Apply learned coping strategies',
                'Reach out to support system'
            ]
        }
    
    def _create_treatment_timeline(
        self, conditions: Dict, severity: Dict
    ) -> List[Dict]:
        """Create a timeline for treatment implementation"""
        timeline = []
        start_date = datetime.now()
        
        # Initial phase
        timeline.append({
            'phase': 'Initial Assessment and Stabilization',
            'duration': '1-2 weeks',
            'start_date': start_date.strftime('%Y-%m-%d'),
            'focus': 'Assessment and immediate interventions'
        })
        
        # Acute phase
        acute_start = start_date + timedelta(weeks=2)
        timeline.append({
            'phase': 'Acute Treatment',
            'duration': '8-12 weeks',
            'start_date': acute_start.strftime('%Y-%m-%d'),
            'focus': 'Primary interventions and symptom reduction'
        })
        
        # Continuation phase
        continuation_start = acute_start + timedelta(weeks=12)
        timeline.append({
            'phase': 'Continuation',
            'duration': '4-6 months',
            'start_date': continuation_start.strftime('%Y-%m-%d'),
            'focus': 'Maintaining improvements and preventing relapse'
        })
        
        return timeline
    
    def _determine_severity_level(self, severity_score: float) -> str:
        """Determine severity level from score"""
        if severity_score > 0.7:
            return 'severe'
        elif severity_score > 0.4:
            return 'moderate'
        else:
            return 'mild'
    
    def _estimate_treatment_duration(
        self, condition: str, severity_level: str
    ) -> str:
        """Estimate treatment duration based on condition and severity"""
        base_duration = {
            'mild': 3,
            'moderate': 6,
            'severe': 12
        }
        
        months = base_duration[severity_level]
        return f"{months}-{months+3} months"
    
    def _generate_fallback_recommendations(self) -> List[str]:
        """Generate basic recommendations when full plan generation fails"""
        return [
            "Seek professional mental health evaluation",
            "Consider psychotherapy",
            "Maintain regular sleep schedule",
            "Practice stress management techniques",
            "Engage in regular physical activity",
            "Build and maintain social support network"
        ]