File size: 13,578 Bytes
6278909 |
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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
import streamlit as st
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
from transformers import pipeline
pipe = pipeline("text-classification", model="distilbert-base-uncased") # 67MB vs BERT's 440MB
classifier = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
import time
from datetime import datetime
@st.cache_data
def load_model():
return pipeline("text-classification", model="distilbert-base-uncased") # Cached after first run
# from transformers import pipeline
# pipe = pipeline('text-generation', model='gpt2', device=0 if torch.cuda.is_available() else -1)
# from transformers import pipeline
# classifier = pipeline("text-classification", model="distilbert-base-uncased", device="cpu") # Faster init
#########
# import os
# from fastapi import FastAPI
# from fastapi.middleware.wsgi import WSGIMiddleware
# from streamlit.web.server import Server
# app = FastAPI()
# app.mount("/", WSGIMiddleware(Server._get_app().wsgi_app))
# @app.get("/health")
# def health_check():
# return {"status": "healthy"}
# if os.getenv("STREAMLIT_CLOUD"):
# import uvicorn
# uvicorn.run(app, host="0.0.0.0", port=8501)
# @st.cache_resource(ttl=3600, max_entries=3)
# def load_model():
# return pipeline('text-generation', model='gpt2') # Use smaller models
########## health check for server
# 1. APP CONFIGURATION ================================================
st.set_page_config(
page_title="Counselor Guidance Assistant",
page_icon="π§ ",
layout="centered",
initial_sidebar_state="expanded"
)
# 2. CUSTOM STYLING ==================================================
st.markdown("""
<style>
:root {
--primary_clr: #43a573;
--secondary: #f8f9fa;
--font_clr: #1a1a1a;
--bg_clr: #e9f5ef;
--bg_clr_g2: #d9ede3;
--bg_clr_g3: #1b422e;
--border_clr: #1b422e;
/* Dark Mode Overrides */
--dark-primary: #43a573;
--dark-secondary: #2d3748;
--dark-font: #e2e8f0;
--dark-bg: #1a202c;
--dark-bg2: #2d3748;
--dark-bg3: #38a169;
--dark-border: #4a5568;
}
* {
box-sizing: border-box;
}
html,body {
font-family: sans-serif;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
-ms-overflow-style: scrollbar;
-webkit-tap-highlight-color: transparent;
margin:0;
height: 100%;
color: var(--font_clr);
background-color: var(--bg_clr)
}
@-ms-viewport {
width: device-width;
}
.stAppHeader, .stMain{
background-color: var(--bg_clr)
}
.stSidebar{
background-color: var(--bg_clr_g2);
}
.stTextArea textarea, .stTextArea > textarea {
min-height: 250px;
font-size: 16px;
background-color: var(--bg_clr_g2);
border-color: var(--border_clr);
resize: none;
}
.responseCard {
background-color: var(--bg_clr);
border-radius: 10px;
padding: 1.5rem;
margin: 1rem 0;
border-left: 4px solid var(--primary_clr);
}
.stButton button, .stButton > button {
background-color: var(--primary_clr);
color: white;
transition: all 0.3s;
border: 1px solid var(--border_clr);
}
.stButton button:hover, .stButton button:focus:not(:active) {
opacity: 0.9;
transform: translateY(-1px);
color: white;
background-color: var(--bg_clr_g3);
border: 1px solid var(--border_clr);
}
/*
.stSlider [role="slider"]{
background-color: var(--bg_clr_g3);
}
.stSlider [role="slider"] .st-an, .stSlider [role="slider"] .st-ap, .stSlider [role="slider"] .st-aq,
.stSlider [role="slider"] .st-ao, .stSlider [role="slider"] .st-cu, .stSlider [role="slider"] .st-cv,
.stSlider [role="slider"] .st-am, .stSlider [role="slider"] .st-cw, .stSlider [role="slider"] .st-cx{
background: linear-gradient(to right, rgb(27, 66, 46) 0%,
rgb(27, 66, 46) 72.2222%,
rgba(151, 166, 195, 0.25) 72.2222%,
rgba(151, 166, 195, 0.25) 100%) !important;
}*/
.progress-container {
margin-top: -10px;
margin-bottom: 15px;
}
summary[class*="st-emotion-cache-"]:hover{
font-weight:800;
color: var(--font_clr);
}
.crisis-alert {
background-color: #fff8f8;
border-left: 5px solid #ff4b4b;
padding: 1.5rem;
margin: 1rem 0;
border-radius: 0 8px 8px 0;
box-shadow: 0 2px 8px rgba(255, 75, 75, 0.15);
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { border-left-color: #ff4b4b; }
50% { border-left-color: #ff9999; }
100% { border-left-color: #ff4b4b; }
}
.crisis-alert strong {
color: #d10000;
}
</style>
""", unsafe_allow_html=True)
# 3. MODEL LOADING ===================================================
@st.cache_resource(show_spinner=False)
def load_model():
return pipeline("text2text-generation", model="google/flan-t5-base")
# 4. PROMPT ENGINEERING ==============================================
def generate_prompt(user_input, counseling_style):
"""Generate context-aware prompts for different counseling approaches"""
style_prompts = {
"Cognitive Behavior Therapy": (
"As a CBT therapist, suggest techniques to address: '{input}'. "
"Focus on identifying cognitive distortions and suggest behavioral experiments. "
"Provide 2-3 concrete interventions."
),
"Psychodynamic": (
"From a psychodynamic perspective, analyze: '{input}'. "
"Consider unconscious patterns and childhood influences. "
"Suggest exploratory questions to reveal underlying conflicts."
),
"Humanistic": (
"Using humanistic approach, respond to: '{input}'. "
"Focus on unconditional positive regard and self-actualization. "
"Provide empathetic reflections and growth-oriented suggestions."
),
"Solution-Focused": (
"Using solution-focused therapy, address: '{input}'. "
"Identify exceptions to the problem and small achievable steps. "
"Suggest 2-3 scaling questions or miracle questions."
)
}
return style_prompts[counseling_style].format(input=user_input)
def get_references(approach):
"""Return evidence-based references with clinical guidelines"""
references = {
"Cognitive Behavior Therapy": {
"text": "Beck, J. S. (2011). Cognitive Behavior Therapy: Basics and Beyond",
"guide": "https://www.apa.org/pubs/books/cognitive-behavior-therapy"
},
"Psychodynamic": {
"text": "McWilliams, N. (2020). Psychoanalytic Diagnosis",
"guide": "https://www.guilford.com/books/Psychoanalytic-Diagnosis/McWilliams/9781462543694"
},
"Humanistic": {
"text": "Rogers, C. (1951). Client-Centered Therapy",
"guide": "https://www.nationalcounsellingsociety.org/about-therapy/types/humanistic"
},
"Solution-Focused": {
"text": "De Shazer, S. (1988). Clues: Investigating Solutions in Brief Therapy",
"guide": "https://www.solutionfocused.net/what-is-sfbt/"
}
}
ref = references.get(approach, {
"text": "Evidence-Based Practice in Psychology",
"guide": "https://www.apa.org/practice/guidelines/evidence-based"
})
return f"{ref['text']} | [Clinical Guidelines]({ref['guide']})"
# 5. MAIN APPLICATION ================================================
def main():
# Initialize session history
if 'history' not in st.session_state:
st.session_state.history = []
st.title("π§ Counselor Guidance Assistant")
st.markdown("""
*Professional support for mental health practitioners*
Enter a patient scenario below for evidence-based intervention suggestions.
""")
# Sidebar configuration
with st.sidebar:
st.title("Session Settings")
counseling_style = st.selectbox(
"Therapeutic Approach",
["Cognitive Behavior Therapy", "Psychodynamic", "Humanistic", "Solution-Focused"],
index=0
)
creativity = st.slider("Response Creativity", 0.1, 1.0, 0.7)
st.markdown("---")
st.caption("""
**Best Practices:**
1. Describe specific behaviors/symptoms
2. Include relevant history
3. Note attempted interventions
""")
# Session history viewer
if st.session_state.history:
with st.expander("π Session History (Last 5)"):
for i, session in enumerate(st.session_state.history[-5:][::-1]):
st.markdown(f"""
**Session {len(st.session_state.history)-i}** ({session['timestamp']})
- Approach: {session['approach']}
- Case: {session['case']}
""")
if st.button(f"View Details #{len(st.session_state.history)-i}", key=f"view_{i}"):
st.session_state.current_session = session
# Example cases for quick testing
with st.expander("π‘ Quick Start : Explore most commons challenges!! "):
examples = {
"Depression": "45yo male with treatment-resistant depression, expresses hopelessness about ever improving",
"Anxiety": "College student experiencing panic attacks before exams despite knowing the material well",
"Relationship": "Couple stuck in pursue-withdraw pattern, escalating arguments about household responsibilities"
}
cols = st.columns(3)
for i, (label, example) in enumerate(examples.items()):
with cols[i]:
if st.button(label):
case_description = example
# Main input area
case_description = st.text_area(
"Type your challenge below:",
placeholder="My 28-year-old patient with social anxiety avoids all group situations despite previous exposure work...",
height=250
)
# Crisis keywords detection
CRISIS_KEYWORDS = ['suicide', 'self-harm', 'homicide', 'abuse', 'abused', 'kill myself', 'kill',
'want to die', 'end my life', 'hurt myself', 'hurt someone','suicidal']
# Response generation
if st.button("Analyze && Suggest", type="primary"):
if not case_description.strip():
st.warning("Please describe the clinical situation")
else:
# Crisis detection
if any(keyword in case_description.lower() for keyword in CRISIS_KEYWORDS):
st.markdown("""
<div class="crisis-alert">
<div style="font-size: 1.3rem;">β οΈ <strong>CRISIS ALERT</strong> - Immediate Action Required</div>
<br>
<div><strong>Clinical Protocols:</strong></div>
<ol>
<li>Assess immediate safety risk using direct questioning</li>
<li>Implement safety planning if risk is present</li>
<li>Do not leave patient alone if active suicidal/homicidal ideation exists</li>
</ol>
<div><strong>Emergency Resources:</strong></div>
<ul>
<li>πΊπΈ <strong>988 Suicide & Crisis Lifeline</strong> (24/7)</li>
<li>π± <strong>Crisis Text Line</strong>: Text HOME to 741741</li>
<li>π <strong>International Association for Suicide Prevention</strong>: <a href="https://www.iasp.info/resources/Crisis_Centres/">Find Local Help</a></li>
</ul>
</div>
""", unsafe_allow_html=True)
with st.expander("π Clinician Guidance (Click for Protocol Details)"):
st.markdown("""
**Standard Crisis Response Protocol:**
1. **Direct Assessment**
"Are you having thoughts of ending your life?"
"Do you have a plan?"
"Have you ever attempted before?"
2. **Safety Planning**
- Remove access to means
- Identify support contacts
- Create step-by-step coping strategies
3. **Documentation**
- Risk assessment findings
- Actions taken
- Follow-up plan
""")
# Log crisis event
st.session_state.history.append({
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M"),
'approach': "CRISIS INTERVENTION",
'case': "CRISIS DETECTED - " + case_description[:50] + "...",
'recommendations': "Session halted - emergency protocols activated"
})
st.stop()
with st.spinner("Generating evidence-based suggestions..."):
try:
llm = load_model()
prompt = generate_prompt(case_description, counseling_style)
# Simulate processing steps for better UX
progress_bar = st.progress(0)
for percent in range(0, 101, 20):
time.sleep(0.1)
progress_bar.progress(percent)
response = llm(
prompt,
max_length=500,
do_sample=True,
temperature=creativity
)[0]['generated_text']
# Store session in history
st.session_state.history.append({
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M"),
'approach': counseling_style,
'case': case_description[:100] + "..." if len(case_description) > 100 else case_description,
'recommendations': response
})
# Display formatted response
st.markdown("## Clinical Recommendations")
with st.container():
st.markdown(f'<div class="responseCard">{response}</div>',
unsafe_allow_html=True)
# Add references
st.markdown("---")
st.caption(f"**Reference:** {get_references(counseling_style)}")
# Response tools
st.download_button(
"Save Recommendations",
data=f"Approach: {counseling_style}\n\n{response}",
file_name=f"clinical_suggestions_{counseling_style}.txt"
)
except Exception as e:
st.error(f"Error generating suggestions: {str(e)}")
if __name__ == "__main__":
main()
|