amrutux commited on
Commit
6278909
Β·
verified Β·
1 Parent(s): 6c01688

Upload counselor_assistant.py

Browse files
Files changed (1) hide show
  1. counselor_assistant.py +416 -0
counselor_assistant.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
4
+
5
+ from transformers import pipeline
6
+ pipe = pipeline("text-classification", model="distilbert-base-uncased") # 67MB vs BERT's 440MB
7
+
8
+ classifier = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
9
+
10
+ import time
11
+ from datetime import datetime
12
+
13
+ @st.cache_data
14
+ def load_model():
15
+ return pipeline("text-classification", model="distilbert-base-uncased") # Cached after first run
16
+
17
+
18
+ # from transformers import pipeline
19
+ # pipe = pipeline('text-generation', model='gpt2', device=0 if torch.cuda.is_available() else -1)
20
+
21
+ # from transformers import pipeline
22
+ # classifier = pipeline("text-classification", model="distilbert-base-uncased", device="cpu") # Faster init
23
+
24
+ #########
25
+
26
+ # import os
27
+ # from fastapi import FastAPI
28
+ # from fastapi.middleware.wsgi import WSGIMiddleware
29
+ # from streamlit.web.server import Server
30
+
31
+ # app = FastAPI()
32
+ # app.mount("/", WSGIMiddleware(Server._get_app().wsgi_app))
33
+
34
+ # @app.get("/health")
35
+ # def health_check():
36
+ # return {"status": "healthy"}
37
+
38
+ # if os.getenv("STREAMLIT_CLOUD"):
39
+ # import uvicorn
40
+ # uvicorn.run(app, host="0.0.0.0", port=8501)
41
+
42
+ # @st.cache_resource(ttl=3600, max_entries=3)
43
+ # def load_model():
44
+ # return pipeline('text-generation', model='gpt2') # Use smaller models
45
+
46
+ ########## health check for server
47
+
48
+ # 1. APP CONFIGURATION ================================================
49
+ st.set_page_config(
50
+ page_title="Counselor Guidance Assistant",
51
+ page_icon="🧠",
52
+ layout="centered",
53
+ initial_sidebar_state="expanded"
54
+ )
55
+
56
+ # 2. CUSTOM STYLING ==================================================
57
+ st.markdown("""
58
+ <style>
59
+ :root {
60
+ --primary_clr: #43a573;
61
+ --secondary: #f8f9fa;
62
+ --font_clr: #1a1a1a;
63
+ --bg_clr: #e9f5ef;
64
+ --bg_clr_g2: #d9ede3;
65
+ --bg_clr_g3: #1b422e;
66
+ --border_clr: #1b422e;
67
+
68
+
69
+ /* Dark Mode Overrides */
70
+ --dark-primary: #43a573;
71
+ --dark-secondary: #2d3748;
72
+ --dark-font: #e2e8f0;
73
+ --dark-bg: #1a202c;
74
+ --dark-bg2: #2d3748;
75
+ --dark-bg3: #38a169;
76
+ --dark-border: #4a5568;
77
+ }
78
+
79
+
80
+
81
+ * {
82
+ box-sizing: border-box;
83
+ }
84
+
85
+ html,body {
86
+ font-family: sans-serif;
87
+ line-height: 1.5;
88
+ -webkit-text-size-adjust: 100%;
89
+ -ms-text-size-adjust: 100%;
90
+ -ms-overflow-style: scrollbar;
91
+ -webkit-tap-highlight-color: transparent;
92
+ margin:0;
93
+ height: 100%;
94
+ color: var(--font_clr);
95
+ background-color: var(--bg_clr)
96
+ }
97
+
98
+ @-ms-viewport {
99
+ width: device-width;
100
+ }
101
+
102
+ .stAppHeader, .stMain{
103
+ background-color: var(--bg_clr)
104
+ }
105
+
106
+ .stSidebar{
107
+ background-color: var(--bg_clr_g2);
108
+ }
109
+
110
+ .stTextArea textarea, .stTextArea > textarea {
111
+ min-height: 250px;
112
+ font-size: 16px;
113
+ background-color: var(--bg_clr_g2);
114
+ border-color: var(--border_clr);
115
+ resize: none;
116
+ }
117
+
118
+ .responseCard {
119
+ background-color: var(--bg_clr);
120
+ border-radius: 10px;
121
+ padding: 1.5rem;
122
+ margin: 1rem 0;
123
+ border-left: 4px solid var(--primary_clr);
124
+ }
125
+
126
+ .stButton button, .stButton > button {
127
+ background-color: var(--primary_clr);
128
+ color: white;
129
+ transition: all 0.3s;
130
+ border: 1px solid var(--border_clr);
131
+ }
132
+
133
+ .stButton button:hover, .stButton button:focus:not(:active) {
134
+ opacity: 0.9;
135
+ transform: translateY(-1px);
136
+ color: white;
137
+ background-color: var(--bg_clr_g3);
138
+ border: 1px solid var(--border_clr);
139
+ }
140
+
141
+ /*
142
+ .stSlider [role="slider"]{
143
+ background-color: var(--bg_clr_g3);
144
+ }
145
+
146
+ .stSlider [role="slider"] .st-an, .stSlider [role="slider"] .st-ap, .stSlider [role="slider"] .st-aq,
147
+ .stSlider [role="slider"] .st-ao, .stSlider [role="slider"] .st-cu, .stSlider [role="slider"] .st-cv,
148
+ .stSlider [role="slider"] .st-am, .stSlider [role="slider"] .st-cw, .stSlider [role="slider"] .st-cx{
149
+ background: linear-gradient(to right, rgb(27, 66, 46) 0%,
150
+ rgb(27, 66, 46) 72.2222%,
151
+ rgba(151, 166, 195, 0.25) 72.2222%,
152
+ rgba(151, 166, 195, 0.25) 100%) !important;
153
+ }*/
154
+
155
+
156
+ .progress-container {
157
+ margin-top: -10px;
158
+ margin-bottom: 15px;
159
+ }
160
+
161
+ summary[class*="st-emotion-cache-"]:hover{
162
+ font-weight:800;
163
+ color: var(--font_clr);
164
+ }
165
+
166
+ .crisis-alert {
167
+ background-color: #fff8f8;
168
+ border-left: 5px solid #ff4b4b;
169
+ padding: 1.5rem;
170
+ margin: 1rem 0;
171
+ border-radius: 0 8px 8px 0;
172
+ box-shadow: 0 2px 8px rgba(255, 75, 75, 0.15);
173
+ animation: pulse 2s infinite;
174
+ }
175
+
176
+ @keyframes pulse {
177
+ 0% { border-left-color: #ff4b4b; }
178
+ 50% { border-left-color: #ff9999; }
179
+ 100% { border-left-color: #ff4b4b; }
180
+ }
181
+
182
+ .crisis-alert strong {
183
+ color: #d10000;
184
+ }
185
+ </style>
186
+ """, unsafe_allow_html=True)
187
+
188
+ # 3. MODEL LOADING ===================================================
189
+ @st.cache_resource(show_spinner=False)
190
+ def load_model():
191
+ return pipeline("text2text-generation", model="google/flan-t5-base")
192
+
193
+
194
+ # 4. PROMPT ENGINEERING ==============================================
195
+ def generate_prompt(user_input, counseling_style):
196
+ """Generate context-aware prompts for different counseling approaches"""
197
+ style_prompts = {
198
+ "Cognitive Behavior Therapy": (
199
+ "As a CBT therapist, suggest techniques to address: '{input}'. "
200
+ "Focus on identifying cognitive distortions and suggest behavioral experiments. "
201
+ "Provide 2-3 concrete interventions."
202
+ ),
203
+ "Psychodynamic": (
204
+ "From a psychodynamic perspective, analyze: '{input}'. "
205
+ "Consider unconscious patterns and childhood influences. "
206
+ "Suggest exploratory questions to reveal underlying conflicts."
207
+ ),
208
+ "Humanistic": (
209
+ "Using humanistic approach, respond to: '{input}'. "
210
+ "Focus on unconditional positive regard and self-actualization. "
211
+ "Provide empathetic reflections and growth-oriented suggestions."
212
+ ),
213
+ "Solution-Focused": (
214
+ "Using solution-focused therapy, address: '{input}'. "
215
+ "Identify exceptions to the problem and small achievable steps. "
216
+ "Suggest 2-3 scaling questions or miracle questions."
217
+ )
218
+ }
219
+ return style_prompts[counseling_style].format(input=user_input)
220
+
221
+ def get_references(approach):
222
+ """Return evidence-based references with clinical guidelines"""
223
+ references = {
224
+ "Cognitive Behavior Therapy": {
225
+ "text": "Beck, J. S. (2011). Cognitive Behavior Therapy: Basics and Beyond",
226
+ "guide": "https://www.apa.org/pubs/books/cognitive-behavior-therapy"
227
+ },
228
+ "Psychodynamic": {
229
+ "text": "McWilliams, N. (2020). Psychoanalytic Diagnosis",
230
+ "guide": "https://www.guilford.com/books/Psychoanalytic-Diagnosis/McWilliams/9781462543694"
231
+ },
232
+ "Humanistic": {
233
+ "text": "Rogers, C. (1951). Client-Centered Therapy",
234
+ "guide": "https://www.nationalcounsellingsociety.org/about-therapy/types/humanistic"
235
+ },
236
+ "Solution-Focused": {
237
+ "text": "De Shazer, S. (1988). Clues: Investigating Solutions in Brief Therapy",
238
+ "guide": "https://www.solutionfocused.net/what-is-sfbt/"
239
+ }
240
+ }
241
+ ref = references.get(approach, {
242
+ "text": "Evidence-Based Practice in Psychology",
243
+ "guide": "https://www.apa.org/practice/guidelines/evidence-based"
244
+ })
245
+ return f"{ref['text']} | [Clinical Guidelines]({ref['guide']})"
246
+
247
+ # 5. MAIN APPLICATION ================================================
248
+ def main():
249
+ # Initialize session history
250
+ if 'history' not in st.session_state:
251
+ st.session_state.history = []
252
+
253
+ st.title("🧠 Counselor Guidance Assistant")
254
+ st.markdown("""
255
+ *Professional support for mental health practitioners*
256
+
257
+ Enter a patient scenario below for evidence-based intervention suggestions.
258
+ """)
259
+
260
+ # Sidebar configuration
261
+ with st.sidebar:
262
+ st.title("Session Settings")
263
+ counseling_style = st.selectbox(
264
+ "Therapeutic Approach",
265
+ ["Cognitive Behavior Therapy", "Psychodynamic", "Humanistic", "Solution-Focused"],
266
+ index=0
267
+ )
268
+ creativity = st.slider("Response Creativity", 0.1, 1.0, 0.7)
269
+ st.markdown("---")
270
+
271
+ st.caption("""
272
+ **Best Practices:**
273
+ 1. Describe specific behaviors/symptoms
274
+ 2. Include relevant history
275
+ 3. Note attempted interventions
276
+ """)
277
+
278
+ # Session history viewer
279
+ if st.session_state.history:
280
+ with st.expander("πŸ“š Session History (Last 5)"):
281
+ for i, session in enumerate(st.session_state.history[-5:][::-1]):
282
+ st.markdown(f"""
283
+ **Session {len(st.session_state.history)-i}** ({session['timestamp']})
284
+ - Approach: {session['approach']}
285
+ - Case: {session['case']}
286
+ """)
287
+ if st.button(f"View Details #{len(st.session_state.history)-i}", key=f"view_{i}"):
288
+ st.session_state.current_session = session
289
+
290
+ # Example cases for quick testing
291
+ with st.expander("πŸ’‘ Quick Start : Explore most commons challenges!! "):
292
+ examples = {
293
+ "Depression": "45yo male with treatment-resistant depression, expresses hopelessness about ever improving",
294
+ "Anxiety": "College student experiencing panic attacks before exams despite knowing the material well",
295
+ "Relationship": "Couple stuck in pursue-withdraw pattern, escalating arguments about household responsibilities"
296
+ }
297
+ cols = st.columns(3)
298
+ for i, (label, example) in enumerate(examples.items()):
299
+ with cols[i]:
300
+ if st.button(label):
301
+ case_description = example
302
+
303
+ # Main input area
304
+ case_description = st.text_area(
305
+ "Type your challenge below:",
306
+ placeholder="My 28-year-old patient with social anxiety avoids all group situations despite previous exposure work...",
307
+ height=250
308
+ )
309
+
310
+ # Crisis keywords detection
311
+ CRISIS_KEYWORDS = ['suicide', 'self-harm', 'homicide', 'abuse', 'abused', 'kill myself', 'kill',
312
+ 'want to die', 'end my life', 'hurt myself', 'hurt someone','suicidal']
313
+
314
+ # Response generation
315
+ if st.button("Analyze && Suggest", type="primary"):
316
+ if not case_description.strip():
317
+ st.warning("Please describe the clinical situation")
318
+ else:
319
+ # Crisis detection
320
+ if any(keyword in case_description.lower() for keyword in CRISIS_KEYWORDS):
321
+ st.markdown("""
322
+ <div class="crisis-alert">
323
+ <div style="font-size: 1.3rem;">⚠️ <strong>CRISIS ALERT</strong> - Immediate Action Required</div>
324
+ <br>
325
+ <div><strong>Clinical Protocols:</strong></div>
326
+ <ol>
327
+ <li>Assess immediate safety risk using direct questioning</li>
328
+ <li>Implement safety planning if risk is present</li>
329
+ <li>Do not leave patient alone if active suicidal/homicidal ideation exists</li>
330
+ </ol>
331
+ <div><strong>Emergency Resources:</strong></div>
332
+ <ul>
333
+ <li>πŸ‡ΊπŸ‡Έ <strong>988 Suicide & Crisis Lifeline</strong> (24/7)</li>
334
+ <li>πŸ“± <strong>Crisis Text Line</strong>: Text HOME to 741741</li>
335
+ <li>🌎 <strong>International Association for Suicide Prevention</strong>: <a href="https://www.iasp.info/resources/Crisis_Centres/">Find Local Help</a></li>
336
+ </ul>
337
+ </div>
338
+ """, unsafe_allow_html=True)
339
+
340
+ with st.expander("πŸ“‹ Clinician Guidance (Click for Protocol Details)"):
341
+ st.markdown("""
342
+ **Standard Crisis Response Protocol:**
343
+ 1. **Direct Assessment**
344
+ "Are you having thoughts of ending your life?"
345
+ "Do you have a plan?"
346
+ "Have you ever attempted before?"
347
+
348
+ 2. **Safety Planning**
349
+ - Remove access to means
350
+ - Identify support contacts
351
+ - Create step-by-step coping strategies
352
+
353
+ 3. **Documentation**
354
+ - Risk assessment findings
355
+ - Actions taken
356
+ - Follow-up plan
357
+ """)
358
+
359
+ # Log crisis event
360
+ st.session_state.history.append({
361
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M"),
362
+ 'approach': "CRISIS INTERVENTION",
363
+ 'case': "CRISIS DETECTED - " + case_description[:50] + "...",
364
+ 'recommendations': "Session halted - emergency protocols activated"
365
+ })
366
+ st.stop()
367
+
368
+ with st.spinner("Generating evidence-based suggestions..."):
369
+ try:
370
+ llm = load_model()
371
+ prompt = generate_prompt(case_description, counseling_style)
372
+
373
+ # Simulate processing steps for better UX
374
+ progress_bar = st.progress(0)
375
+ for percent in range(0, 101, 20):
376
+ time.sleep(0.1)
377
+ progress_bar.progress(percent)
378
+
379
+ response = llm(
380
+ prompt,
381
+ max_length=500,
382
+ do_sample=True,
383
+ temperature=creativity
384
+ )[0]['generated_text']
385
+
386
+ # Store session in history
387
+ st.session_state.history.append({
388
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M"),
389
+ 'approach': counseling_style,
390
+ 'case': case_description[:100] + "..." if len(case_description) > 100 else case_description,
391
+ 'recommendations': response
392
+ })
393
+
394
+ # Display formatted response
395
+ st.markdown("## Clinical Recommendations")
396
+ with st.container():
397
+ st.markdown(f'<div class="responseCard">{response}</div>',
398
+ unsafe_allow_html=True)
399
+
400
+ # Add references
401
+ st.markdown("---")
402
+ st.caption(f"**Reference:** {get_references(counseling_style)}")
403
+
404
+ # Response tools
405
+ st.download_button(
406
+ "Save Recommendations",
407
+ data=f"Approach: {counseling_style}\n\n{response}",
408
+ file_name=f"clinical_suggestions_{counseling_style}.txt"
409
+ )
410
+
411
+ except Exception as e:
412
+ st.error(f"Error generating suggestions: {str(e)}")
413
+
414
+ if __name__ == "__main__":
415
+ main()
416
+