phxdev commited on
Commit
ce583c7
·
verified ·
1 Parent(s): 7d21294

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +475 -53
app.py CHANGED
@@ -50,41 +50,14 @@ def load_model():
50
  print(f"❌ Error loading model: {e}")
51
  return False
52
 
53
- def psychology_support(message: str) -> str:
54
- """
55
- Provide empathetic psychology support and mental health guidance.
56
-
57
- This tool provides specialized psychological support using a fine-tuned AI model
58
- trained specifically for mental health conversations. It offers evidence-based
59
- coping strategies, emotional validation, and practical guidance.
60
-
61
- Args:
62
- message (str): The user's concern, struggle, or question about mental health
63
-
64
- Returns:
65
- str: Empathetic, evidence-based psychological guidance and support
66
- """
67
-
68
  if model is None:
69
  return "⚠️ Psychology model is loading. Please try again in a moment."
70
 
71
- # Lexical convergence prompt - match their language and energy while providing clinical-quality support
72
- formatted_prompt = f"""Someone just said: "{message}"
73
-
74
- Respond using their exact words and energy level. Match how they're talking - if they say "freaking out," say "freaking out." If they're casual, be casual. If they're intense, match that intensity.
75
-
76
- Give them evidence-based help without any clinical jargon:
77
- - Use their language, not therapy-speak
78
- - Acknowledge what they said is real and makes sense
79
- - Give 2-3 specific things they can do right now that actually work
80
- - Don't make their problem bigger than they're saying it is
81
- - If it's serious, give real resources without being dramatic about it
82
-
83
- Sound like someone who gets it and knows what helps:"""
84
-
85
  try:
86
  inputs = tokenizer(
87
- formatted_prompt,
88
  return_tensors="pt",
89
  truncation=True,
90
  max_length=512
@@ -103,7 +76,7 @@ Sound like someone who gets it and knows what helps:"""
103
  )
104
 
105
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
106
- generated_text = response[len(formatted_prompt):].strip()
107
 
108
  if generated_text.startswith('"') and generated_text.endswith('"'):
109
  generated_text = generated_text[1:-1]
@@ -113,9 +86,410 @@ Sound like someone who gets it and knows what helps:"""
113
  except Exception as e:
114
  return f"⚠️ Error generating response: {str(e)}"
115
 
116
- # Apply GPU optimization if available
117
- if HAS_SPACES:
118
- psychology_support = spaces.GPU(psychology_support)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  def crisis_resources() -> str:
121
  """
@@ -176,6 +550,25 @@ def mindfulness_exercise() -> str:
176
 
177
  You are safe. You are here. This moment will pass."""
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  # Initialize model
180
  print("🚀 Starting Psychology Personal Agent...")
181
  model_loaded = load_model()
@@ -183,25 +576,54 @@ model_loaded = load_model()
183
  if model_loaded:
184
  print("✅ Creating Personal Agent interface...")
185
 
186
- # Create simple interface
187
- demo = gr.Interface(
188
- fn=psychology_support,
189
- inputs=gr.Textbox(
190
- label="What's on your mind?",
191
- placeholder="Share your thoughts, concerns, or struggles...",
192
- lines=3
193
- ),
194
- outputs=gr.Textbox(label="Personal Agent Response"),
195
- title="🧠 Personal Agent - Psychology Support",
196
- description="Specialized mental health support • For Mark. For Josh. For everyone who needs someone.",
197
- examples=[
198
- "I've been having panic attacks at work and don't know what to do",
199
- "I can't stop worrying about things that might go wrong",
200
- "I feel like I'm not good enough at my job",
201
- "I'm going through a major life transition and feel lost",
202
- "I have trouble setting boundaries with people"
203
- ]
204
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  if __name__ == "__main__":
207
  demo.launch(
 
50
  print(f"❌ Error loading model: {e}")
51
  return False
52
 
53
+ def _generate_psychology_response(prompt: str) -> str:
54
+ """Helper function to generate responses using the psychology model"""
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if model is None:
56
  return "⚠️ Psychology model is loading. Please try again in a moment."
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  try:
59
  inputs = tokenizer(
60
+ prompt,
61
  return_tensors="pt",
62
  truncation=True,
63
  max_length=512
 
76
  )
77
 
78
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
79
+ generated_text = response[len(prompt):].strip()
80
 
81
  if generated_text.startswith('"') and generated_text.endswith('"'):
82
  generated_text = generated_text[1:-1]
 
86
  except Exception as e:
87
  return f"⚠️ Error generating response: {str(e)}"
88
 
89
+ def psychology_support(message: str) -> str:
90
+ """
91
+ Provide empathetic psychology support and mental health guidance.
92
+
93
+ This tool provides specialized psychological support using a fine-tuned AI model
94
+ trained specifically for mental health conversations. It offers evidence-based
95
+ coping strategies, emotional validation, and practical guidance.
96
+
97
+ Args:
98
+ message (str): The user's concern, struggle, or question about mental health
99
+
100
+ Returns:
101
+ str: Empathetic, evidence-based psychological guidance and support
102
+ """
103
+
104
+ formatted_prompt = f"""Someone just said: "{message}"
105
+
106
+ Respond using their exact words and energy level. Match how they're talking - if they say "freaking out," say "freaking out." If they're casual, be casual. If they're intense, match that intensity.
107
+
108
+ Give them evidence-based help without any clinical jargon:
109
+ - Use their language, not therapy-speak
110
+ - Acknowledge what they said is real and makes sense
111
+ - Give 2-3 specific things they can do right now that actually work
112
+ - Don't make their problem bigger than they're saying it is
113
+ - If it's serious, give real resources without being dramatic about it
114
+
115
+ Sound like someone who gets it and knows what helps:"""
116
+
117
+ return _generate_psychology_response(formatted_prompt)
118
+
119
+ def depression_support(message: str) -> str:
120
+ """
121
+ Provide specialized support for depression symptoms and concerns.
122
+
123
+ Args:
124
+ message (str): Depression-related concern or symptom description
125
+
126
+ Returns:
127
+ str: Targeted depression support and behavioral activation guidance
128
+ """
129
+
130
+ prompt = f"""Someone is sharing about depression: "{message}"
131
+
132
+ Provide depression-informed support:
133
+ - Acknowledge their courage in reaching out
134
+ - Validate that depression is real and treatable
135
+ - Suggest small, achievable activities (behavioral activation)
136
+ - Address any hopelessness with realistic hope
137
+ - Give them 2-3 immediate things they can do today
138
+ - Use their words, not clinical language
139
+
140
+ Focus on movement, connection, and tiny wins:"""
141
+
142
+ return _generate_psychology_response(prompt)
143
+
144
+ def anxiety_support(message: str) -> str:
145
+ """
146
+ Provide specialized support for anxiety symptoms and panic.
147
+
148
+ Args:
149
+ message (str): Anxiety-related concern or symptom description
150
+
151
+ Returns:
152
+ str: Targeted anxiety support and grounding techniques
153
+ """
154
+
155
+ prompt = f"""Someone is experiencing anxiety: "{message}"
156
+
157
+ Provide anxiety-informed support:
158
+ - Acknowledge their anxiety is real and makes sense
159
+ - Help them understand anxiety as false alarm, not real danger
160
+ - Give grounding techniques they can use right now
161
+ - Challenge catastrophic thinking gently
162
+ - Provide breathing exercises and body awareness
163
+ - Use their energy level and words
164
+
165
+ Help them feel less alone and more in control:"""
166
+
167
+ return _generate_psychology_response(prompt)
168
+
169
+ def trauma_support(message: str) -> str:
170
+ """
171
+ Provide trauma-informed support and stabilization techniques.
172
+
173
+ Args:
174
+ message (str): Trauma-related concern or trigger description
175
+
176
+ Returns:
177
+ str: Trauma-informed support focused on safety and stabilization
178
+ """
179
+
180
+ prompt = f"""Someone is sharing about trauma: "{message}"
181
+
182
+ Provide trauma-informed support:
183
+ - Prioritize safety and stabilization over processing
184
+ - Remind them they survived then and are surviving now
185
+ - Validate their responses as normal survival mechanisms
186
+ - Offer grounding techniques to stay present
187
+ - Emphasize their strength and resilience
188
+ - Give them control over the conversation pace
189
+
190
+ Focus on "that was then, this is now" and present safety:"""
191
+
192
+ return _generate_psychology_response(prompt)
193
+
194
+ def panic_attack_support(message: str) -> str:
195
+ """
196
+ Provide immediate support for panic attacks and intense anxiety.
197
+
198
+ Args:
199
+ message (str): Panic attack description or request for help
200
+
201
+ Returns:
202
+ str: Immediate panic attack intervention and coping strategies
203
+ """
204
+
205
+ prompt = f"""Someone is having or describing a panic attack: "{message}"
206
+
207
+ Provide immediate panic support:
208
+ - Remind them panic peaks at 10 minutes and will pass
209
+ - Give breathing techniques (4-7-8 or box breathing)
210
+ - Grounding exercises (5-4-3-2-1 technique)
211
+ - Remind them it's scary but not dangerous
212
+ - Help them feel less alone in this moment
213
+ - Use calm, reassuring language that matches their urgency
214
+
215
+ Help them ride the wave until it passes:"""
216
+
217
+ return _generate_psychology_response(prompt)
218
+
219
+ def ptsd_support(message: str) -> str:
220
+ """
221
+ Provide specialized support for PTSD symptoms and flashbacks.
222
+
223
+ Args:
224
+ message (str): PTSD-related symptom or flashback description
225
+
226
+ Returns:
227
+ str: PTSD-informed support and stabilization techniques
228
+ """
229
+
230
+ prompt = f"""Someone is experiencing PTSD symptoms: "{message}"
231
+
232
+ Provide PTSD-informed support:
233
+ - Help orient them to present time and safety
234
+ - Validate their survival responses as adaptive
235
+ - Offer grounding techniques for flashbacks
236
+ - Address hypervigilance with gentle reality testing
237
+ - Support their window of tolerance
238
+ - Emphasize post-traumatic growth alongside pain
239
+
240
+ Remind them they're not broken, they're injured and healing:"""
241
+
242
+ return _generate_psychology_response(prompt)
243
+
244
+ def anger_management_support(message: str) -> str:
245
+ """
246
+ Provide support for anger management and emotional regulation.
247
+
248
+ Args:
249
+ message (str): Anger-related concern or situation description
250
+
251
+ Returns:
252
+ str: Anger management strategies and emotional regulation techniques
253
+ """
254
+
255
+ prompt = f"""Someone is dealing with anger: "{message}"
256
+
257
+ Provide anger management support:
258
+ - Validate anger as a normal emotion with important information
259
+ - Help identify what's underneath the anger (hurt, fear, frustration)
260
+ - Give immediate cooling strategies (time-out, breathing, movement)
261
+ - Address triggers and early warning signs
262
+ - Suggest healthy expression methods
263
+ - Focus on empowerment, not suppression
264
+
265
+ Help them channel anger constructively:"""
266
+
267
+ return _generate_psychology_response(prompt)
268
+
269
+ def grief_support(message: str) -> str:
270
+ """
271
+ Provide specialized support for grief and loss.
272
+
273
+ Args:
274
+ message (str): Grief or loss-related concern or experience
275
+
276
+ Returns:
277
+ str: Compassionate grief support and coping guidance
278
+ """
279
+
280
+ prompt = f"""Someone is grieving: "{message}"
281
+
282
+ Provide grief-informed support:
283
+ - Acknowledge their loss and pain without trying to fix it
284
+ - Validate that grief is love with nowhere to go
285
+ - Normalize the messiness and unpredictability of grief
286
+ - Suggest gentle self-care and patience with themselves
287
+ - Honor their relationship with what/who they lost
288
+ - Avoid platitudes, focus on presence and validation
289
+
290
+ Sit with them in their pain while offering hope:"""
291
+
292
+ return _generate_psychology_response(prompt)
293
+
294
+ def relationship_boundaries_support(message: str) -> str:
295
+ """
296
+ Provide support for setting healthy boundaries in relationships.
297
+
298
+ Args:
299
+ message (str): Relationship or boundary-related concern
300
+
301
+ Returns:
302
+ str: Boundary-setting guidance and relationship support
303
+ """
304
+
305
+ prompt = f"""Someone needs help with boundaries: "{message}"
306
+
307
+ Provide boundary-setting support:
308
+ - Validate their right to have boundaries
309
+ - Help identify where boundaries are needed
310
+ - Give scripts for communicating boundaries clearly
311
+ - Address guilt or fear about setting limits
312
+ - Distinguish between healthy and unhealthy relationships
313
+ - Emphasize self-care isn't selfish
314
+
315
+ Help them protect their energy and wellbeing:"""
316
+
317
+ return _generate_psychology_response(prompt)
318
+
319
+ def sleep_support(message: str) -> str:
320
+ """
321
+ Provide support for sleep difficulties and sleep hygiene.
322
+
323
+ Args:
324
+ message (str): Sleep-related concern or insomnia description
325
+
326
+ Returns:
327
+ str: Sleep hygiene guidance and insomnia support
328
+ """
329
+
330
+ prompt = f"""Someone is having sleep problems: "{message}"
331
+
332
+ Provide sleep support:
333
+ - Validate how exhausting sleep problems can be
334
+ - Give practical sleep hygiene tips they can try tonight
335
+ - Address racing thoughts or anxiety at bedtime
336
+ - Suggest relaxation techniques for better sleep
337
+ - Help identify sleep disruptors in their routine
338
+ - Balance hope with realistic expectations
339
+
340
+ Help them create conditions for better rest:"""
341
+
342
+ return _generate_psychology_response(prompt)
343
+
344
+ def substance_use_support(message: str) -> str:
345
+ """
346
+ Provide non-judgmental support for substance use concerns.
347
+
348
+ Args:
349
+ message (str): Substance use concern or question about recovery
350
+
351
+ Returns:
352
+ str: Compassionate substance use support and harm reduction guidance
353
+ """
354
+
355
+ prompt = f"""Someone is struggling with substance use: "{message}"
356
+
357
+ Provide substance use support:
358
+ - Approach with zero judgment and maximum compassion
359
+ - Validate how hard it is to struggle with substances
360
+ - Support harm reduction and any positive steps
361
+ - Address underlying pain substances might be masking
362
+ - Give resources for support groups and treatment
363
+ - Emphasize recovery is possible and they're worth it
364
+
365
+ Meet them where they are with dignity and hope:"""
366
+
367
+ return _generate_psychology_response(prompt)
368
+
369
+ def safety_planning_support(message: str) -> str:
370
+ """
371
+ Provide support for creating safety plans and crisis preparation.
372
+
373
+ Args:
374
+ message (str): Safety concern or request for crisis planning help
375
+
376
+ Returns:
377
+ str: Safety planning guidance and crisis preparation support
378
+ """
379
+
380
+ prompt = f"""Someone needs help with safety planning: "{message}"
381
+
382
+ Provide safety planning support:
383
+ - Help identify warning signs of crisis
384
+ - Create coping strategies for difficult moments
385
+ - Identify support people they can reach out to
386
+ - List professional resources and crisis contacts
387
+ - Remove or secure means of self-harm if relevant
388
+ - Emphasize their commitment to staying safe
389
+
390
+ Help them build a concrete plan for tough moments:"""
391
+
392
+ return _generate_psychology_response(prompt)
393
+
394
+ def cbt_thought_challenging(message: str) -> str:
395
+ """
396
+ Provide CBT-based thought challenging and cognitive restructuring support.
397
+
398
+ Args:
399
+ message (str): Negative thought pattern or cognitive distortion description
400
+
401
+ Returns:
402
+ str: CBT-informed thought challenging guidance
403
+ """
404
+
405
+ prompt = f"""Someone has unhelpful thoughts: "{message}"
406
+
407
+ Provide CBT thought challenging:
408
+ - Help identify cognitive distortions in their thinking
409
+ - Ask questions to examine evidence for/against thoughts
410
+ - Suggest more balanced, realistic perspectives
411
+ - Teach them to be their own thought detective
412
+ - Focus on thoughts as mental events, not facts
413
+ - Give them tools to challenge future negative thoughts
414
+
415
+ Help them think more flexibly and accurately:"""
416
+
417
+ return _generate_psychology_response(prompt)
418
+
419
+ def dbt_distress_tolerance(message: str) -> str:
420
+ """
421
+ Provide DBT distress tolerance skills for overwhelming emotions.
422
+
423
+ Args:
424
+ message (str): Emotional overwhelm or distress description
425
+
426
+ Returns:
427
+ str: DBT distress tolerance techniques and emotional regulation support
428
+ """
429
+
430
+ prompt = f"""Someone is emotionally overwhelmed: "{message}"
431
+
432
+ Provide DBT distress tolerance support:
433
+ - Validate their pain while teaching survival skills
434
+ - Offer TIPP techniques (Temperature, Intense exercise, Paced breathing, Paired muscle relaxation)
435
+ - Suggest distraction and self-soothing methods
436
+ - Help them ride the wave without making it worse
437
+ - Focus on getting through this moment safely
438
+ - Emphasize that this feeling will pass
439
+
440
+ Help them survive crisis moments without destructive actions:"""
441
+
442
+ return _generate_psychology_response(prompt)
443
+
444
+ def behavioral_activation_support(message: str) -> str:
445
+ """
446
+ Provide behavioral activation support for depression and motivation.
447
+
448
+ Args:
449
+ message (str): Low motivation or depression-related inactivity description
450
+
451
+ Returns:
452
+ str: Behavioral activation guidance and motivation support
453
+ """
454
+
455
+ prompt = f"""Someone is struggling with motivation: "{message}"
456
+
457
+ Provide behavioral activation support:
458
+ - Start with tiny, achievable activities
459
+ - Focus on movement and engagement over mood
460
+ - Help schedule pleasant activities throughout their week
461
+ - Address the "I don't feel like it" barrier
462
+ - Celebrate small wins and progress
463
+ - Connect activities to their values and what matters
464
+
465
+ Help them take small steps toward feeling better:"""
466
+
467
+ return _generate_psychology_response(prompt)
468
+
469
+ def professional_resources_support(message: str) -> str:
470
+ """
471
+ Provide guidance on finding professional mental health support.
472
+
473
+ Args:
474
+ message (str): Request for professional help or therapy information
475
+
476
+ Returns:
477
+ str: Professional resource guidance and therapy navigation support
478
+ """
479
+
480
+ prompt = f"""Someone wants professional help: "{message}"
481
+
482
+ Provide professional resource guidance:
483
+ - Validate their wisdom in seeking professional support
484
+ - Explain different types of therapy and what to expect
485
+ - Give practical tips for finding the right therapist
486
+ - Address insurance, cost, and accessibility concerns
487
+ - Help them prepare for their first appointment
488
+ - Normalize the process of finding the right fit
489
+
490
+ Support their journey toward getting professional help:"""
491
+
492
+ return _generate_psychology_response(prompt)
493
 
494
  def crisis_resources() -> str:
495
  """
 
550
 
551
  You are safe. You are here. This moment will pass."""
552
 
553
+ # Apply GPU optimization if available
554
+ if HAS_SPACES:
555
+ psychology_support = spaces.GPU(psychology_support)
556
+ depression_support = spaces.GPU(depression_support)
557
+ anxiety_support = spaces.GPU(anxiety_support)
558
+ trauma_support = spaces.GPU(trauma_support)
559
+ panic_attack_support = spaces.GPU(panic_attack_support)
560
+ ptsd_support = spaces.GPU(ptsd_support)
561
+ anger_management_support = spaces.GPU(anger_management_support)
562
+ grief_support = spaces.GPU(grief_support)
563
+ relationship_boundaries_support = spaces.GPU(relationship_boundaries_support)
564
+ sleep_support = spaces.GPU(sleep_support)
565
+ substance_use_support = spaces.GPU(substance_use_support)
566
+ safety_planning_support = spaces.GPU(safety_planning_support)
567
+ cbt_thought_challenging = spaces.GPU(cbt_thought_challenging)
568
+ dbt_distress_tolerance = spaces.GPU(dbt_distress_tolerance)
569
+ behavioral_activation_support = spaces.GPU(behavioral_activation_support)
570
+ professional_resources_support = spaces.GPU(professional_resources_support)
571
+
572
  # Initialize model
573
  print("🚀 Starting Psychology Personal Agent...")
574
  model_loaded = load_model()
 
576
  if model_loaded:
577
  print("✅ Creating Personal Agent interface...")
578
 
579
+ # Create comprehensive interface
580
+ with gr.Blocks(title="🧠 Personal Agent - Psychology Support") as demo:
581
+ gr.Markdown("# 🧠 Personal Agent - Psychology Support")
582
+ gr.Markdown("Specialized mental health support • For Mark. For Josh. For everyone who needs someone.")
583
+
584
+ with gr.Tab("General Support"):
585
+ message_input = gr.Textbox(
586
+ label="What's on your mind?",
587
+ placeholder="Share your thoughts, concerns, or struggles...",
588
+ lines=3
589
+ )
590
+ support_output = gr.Textbox(label="Personal Agent Response")
591
+ support_button = gr.Button("Get Support")
592
+
593
+ support_button.click(
594
+ fn=psychology_support,
595
+ inputs=message_input,
596
+ outputs=support_output
597
+ )
598
+
599
+ gr.Examples(
600
+ examples=[
601
+ "I've been having panic attacks at work and don't know what to do",
602
+ "I can't stop worrying about things that might go wrong",
603
+ "I feel like I'm not good enough at my job",
604
+ "I'm going through a major life transition and feel lost",
605
+ "I have trouble setting boundaries with people"
606
+ ],
607
+ inputs=message_input
608
+ )
609
+
610
+ with gr.Tab("Crisis Resources"):
611
+ crisis_button = gr.Button("Get Crisis Resources")
612
+ crisis_output = gr.Textbox(label="Crisis Resources")
613
+
614
+ crisis_button.click(
615
+ fn=crisis_resources,
616
+ outputs=crisis_output
617
+ )
618
+
619
+ with gr.Tab("Mindfulness"):
620
+ mindfulness_button = gr.Button("Get Mindfulness Exercise")
621
+ mindfulness_output = gr.Textbox(label="Mindfulness Exercise")
622
+
623
+ mindfulness_button.click(
624
+ fn=mindfulness_exercise,
625
+ outputs=mindfulness_output
626
+ )
627
 
628
  if __name__ == "__main__":
629
  demo.launch(