phxdev commited on
Commit
9e416ee
·
verified ·
1 Parent(s): 5507602

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -383
app.py CHANGED
@@ -62,8 +62,8 @@ def load_model():
62
  traceback.print_exc()
63
  return False
64
 
65
- def _generate_therapeutic_response(formatted_prompt: str, max_new_tokens: int = 200) -> str:
66
- """Therapeutic mode generation with empathetic parameters"""
67
  if model is None:
68
  return "⚠️ Model not loaded. Please refresh and try again."
69
 
@@ -75,12 +75,12 @@ def _generate_therapeutic_response(formatted_prompt: str, max_new_tokens: int =
75
  max_length=800
76
  ).to(device)
77
 
78
- # Therapeutic generation settings - warmer, more empathetic
79
  with torch.no_grad():
80
  outputs = model.generate(
81
  **inputs,
82
  max_new_tokens=max_new_tokens,
83
- temperature=0.8, # Higher temperature for more natural therapeutic responses
84
  top_p=0.9,
85
  do_sample=True,
86
  repetition_penalty=1.1,
@@ -91,7 +91,7 @@ def _generate_therapeutic_response(formatted_prompt: str, max_new_tokens: int =
91
  full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
92
  generated_text = full_response[len(formatted_prompt):].strip()
93
 
94
- # Therapeutic cleanup - preserve empathetic language
95
  if generated_text.startswith('"') and generated_text.endswith('"'):
96
  generated_text = generated_text[1:-1]
97
 
@@ -105,122 +105,63 @@ def _generate_therapeutic_response(formatted_prompt: str, max_new_tokens: int =
105
  generated_text = generated_text.split(phrase)[0].strip()
106
 
107
  if not generated_text:
108
- return "I'm here to listen. Please try rephrasing what you're going through."
109
 
110
  return generated_text
111
 
112
  except Exception as e:
113
- return f"⚠️ Therapeutic generation error: {str(e)}"
114
 
115
- def _generate_clinical_response(formatted_prompt: str, max_new_tokens: int = 300) -> str:
116
- """Clinical mode generation with analytical parameters"""
117
- if model is None:
118
- return "⚠️ Model not loaded. Please refresh and try again."
119
-
120
- try:
121
- inputs = tokenizer(
122
- formatted_prompt,
123
- return_tensors="pt",
124
- truncation=True,
125
- max_length=700 # Leave more room for clinical analysis
126
- ).to(device)
127
-
128
- # Clinical generation settings - more focused, analytical
129
- with torch.no_grad():
130
- outputs = model.generate(
131
- **inputs,
132
- max_new_tokens=max_new_tokens,
133
- temperature=0.4, # Lower temperature for more structured clinical responses
134
- top_p=0.8,
135
- do_sample=True,
136
- repetition_penalty=1.2,
137
- pad_token_id=tokenizer.eos_token_id,
138
- eos_token_id=tokenizer.eos_token_id,
139
- )
140
-
141
- full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
142
- generated_text = full_response[len(formatted_prompt):].strip()
143
-
144
- # Clinical cleanup - preserve analytical structure
145
- if generated_text.startswith('"') and generated_text.endswith('"'):
146
- generated_text = generated_text[1:-1]
147
-
148
- # Don't stop at numbered lists for clinical analysis
149
- stop_phrases = [
150
- "Their response", "Your response", "They said", "You said",
151
- "And their response", "And your response", "Person:", "Response:",
152
- "If you", "Remember that", "It's important to note"
153
- ]
154
-
155
- for phrase in stop_phrases:
156
- if phrase in generated_text:
157
- generated_text = generated_text.split(phrase)[0].strip()
158
-
159
- if not generated_text:
160
- return "Clinical analysis requires specific content to examine. Please provide detailed material for assessment."
161
-
162
- return generated_text
163
-
164
- except Exception as e:
165
- return f"⚠️ Clinical analysis error: {str(e)}"
166
-
167
- # THERAPEUTIC MODE FUNCTIONS
168
- def psychology_support_internal(message: str) -> str:
169
- """Main psychology support function - THERAPEUTIC MODE"""
170
  if not message.strip():
171
- return "Please share what's on your mind."
172
 
173
- formatted_prompt = f"A person with boundary issues says: \"{message}\"\n\nA supportive response that helps with boundary setting:"
174
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=150)
175
 
176
- def trauma_support_internal(message: str) -> str:
177
- """Trauma-informed support - THERAPEUTIC MODE"""
178
  if not message.strip():
179
- return "I'm here to listen. What would help you feel safer right now?"
180
 
181
- formatted_prompt = f"You are a trauma-informed friend who helps people feel safe. Draw on your vast experience of supporting trauma survivors. Someone dealing with trauma just told you: \"{message}\"\n\nRespond to help them feel safer:"
182
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=180)
183
 
184
- def panic_support_internal(message: str) -> str:
185
- """Immediate panic attack support - THERAPEUTIC MODE"""
186
  if not message.strip():
187
- return "I can help you through this. What are you experiencing right now?"
188
 
189
- formatted_prompt = f"You are a calm, grounding friend who helps with panic attacks. Draw on your vast experience of helping people through panic and anxiety. Someone having panic symptoms just told you: \"{message}\"\n\nRespond to help them through this moment:"
190
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=160)
191
 
192
- def process_emotion_internal(message: str) -> str:
193
- """Emotion processing and validation - THERAPEUTIC MODE"""
194
  if not message.strip():
195
- return "What emotion are you working through right now?"
196
 
197
- formatted_prompt = f"You are an emotionally intelligent friend who helps people understand their feelings. Draw on your vast experience of emotional support and validation. Someone struggling with emotions just told you: \"{message}\"\n\nRespond to help them process what they're feeling:"
198
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=170)
199
 
200
- def sentiment_analysis_internal(text: str) -> str:
201
- """Analyze sentiment and emotional content - THERAPEUTIC MODE"""
202
- if not text.strip():
203
- return "Please provide text to analyze."
204
-
205
- formatted_prompt = f"You are an expert in emotional analysis and psychology. Analyze the emotional content, sentiment, and psychological patterns in this text: \"{text}\"\n\nProvide a detailed psychological analysis including mood, emotional state, potential concerns, and supportive insights:"
206
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=200)
207
-
208
- def relationship_analysis_internal(message: str) -> str:
209
- """Analyze relationship dynamics - THERAPEUTIC MODE"""
210
  if not message.strip():
211
- return "Please describe the relationship situation you'd like analyzed."
212
 
213
- formatted_prompt = f"You are a relationship therapist analyzing interpersonal dynamics. Someone described this relationship situation: \"{message}\"\n\nProvide insights on relationship patterns, communication dynamics, and healthy approaches:"
214
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=180)
215
 
216
- def coping_strategies_internal(situation: str) -> str:
217
- """Generate personalized coping strategies - THERAPEUTIC MODE"""
218
  if not situation.strip():
219
- return "Please describe what you're dealing with so I can suggest coping strategies."
220
 
221
- formatted_prompt = f"You are a mental health counselor specializing in coping strategies. Someone is dealing with: \"{situation}\"\n\nProvide specific, practical coping strategies and techniques:"
222
- return _generate_therapeutic_response(formatted_prompt, max_new_tokens=200)
223
 
 
224
  def crisis_resources_internal() -> str:
225
  """Get immediate crisis intervention resources"""
226
  return """🆘 **IMMEDIATE CRISIS RESOURCES**
@@ -260,236 +201,41 @@ def mindfulness_exercise_internal() -> str:
260
 
261
  You've got this. One breath at a time."""
262
 
263
- # CLINICAL MODE FUNCTIONS
264
- def cognitive_bias_detection_internal(content: str) -> str:
265
- """Detect cognitive biases - CLINICAL MODE"""
266
  if not content.strip():
267
- return "Please provide content to analyze for cognitive bias exploitation."
268
 
269
- formatted_prompt = f"""CLINICAL PSYCHOLOGY ANALYSIS MODE: You are Dr. Sarah Chen, a clinical psychologist with 20 years of experience in cognitive bias research and consumer manipulation detection at Stanford University. You have published 47 peer-reviewed papers on decision-making vulnerabilities.
270
-
271
- ANALYSIS TARGET: "{content}"
272
-
273
- Conduct a systematic clinical assessment following established research protocols:
274
-
275
- 1. COGNITIVE BIASES IDENTIFIED:
276
- - Anchoring bias exploitation (price/value reference manipulation)
277
- - Loss aversion triggers (scarcity, urgency, missed opportunity)
278
- - Authority bias leveraging (expert/brand credibility transfer)
279
- - Commitment consistency traps (foot-in-door techniques)
280
- - Social proof manipulation (popularity/testimonial exploitation)
281
-
282
- 2. MANIPULATION SEVERITY SCORE: Rate 1-10 with clinical justification
283
 
284
- 3. VULNERABLE POPULATION ASSESSMENT: Who is most at risk
285
-
286
- 4. NEUROLOGICAL IMPACT: How this affects decision-making brain regions
287
-
288
- 5. RESISTANCE DIFFICULTY: How hard is this to resist for average person
289
-
290
- Provide clinical assessment with evidence base:"""
291
- return _generate_clinical_response(formatted_prompt, max_new_tokens=350)
292
-
293
- def manipulation_technique_analysis_internal(content: str) -> str:
294
- """Classify manipulation techniques - CLINICAL MODE"""
295
  if not content.strip():
296
- return "Please provide content to analyze for manipulation techniques."
297
 
298
- formatted_prompt = f"""CLINICAL MANIPULATION ANALYSIS: You are Dr. Marcus Rodriguez, a behavioral economics researcher specializing in commercial manipulation tactics. You lead the Consumer Protection Psychology Lab at MIT.
299
-
300
- CONTENT UNDER ANALYSIS: "{content}"
301
-
302
- Provide systematic classification of manipulation vectors:
303
 
304
- 1. TEMPORAL MANIPULATION TECHNIQUES:
305
- - Countdown timers, artificial deadlines, urgency creation
306
- - Time pressure impact on cognitive processing
307
-
308
- 2. SOCIAL PROOF EXPLOITATION:
309
- - Authority borrowing, popularity signals, testimonial manipulation
310
- - Herd behavior triggers, consensus pressure
311
-
312
- 3. CHOICE ARCHITECTURE MANIPULATION:
313
- - Default option bias, decoy effects, framing manipulation
314
- - Option presentation designed to influence selection
315
-
316
- 4. COMMITMENT ESCALATION PROTOCOLS:
317
- - Foot-in-door progression, consistency traps
318
- - Incremental commitment building, subscription entrapment
319
-
320
- 5. EMOTIONAL MANIPULATION VECTORS:
321
- - Fear induction, excitement exploitation, loss aversion activation
322
- - Emotional state manipulation for decision compromise
323
-
324
- 6. PRICING PSYCHOLOGY WARFARE:
325
- - Anchoring, bundling, artificial scarcity premium
326
- - Value perception distortion techniques
327
-
328
- Clinical assessment with severity ratings:"""
329
- return _generate_clinical_response(formatted_prompt, max_new_tokens=400)
330
-
331
- def clinical_manipulation_assessment_internal(content: str) -> str:
332
- """Comprehensive clinical assessment - CLINICAL MODE"""
333
  if not content.strip():
334
- return "Please provide content for clinical manipulation assessment."
335
 
336
- formatted_prompt = f"""COMPREHENSIVE CLINICAL ASSESSMENT: You are conducting a formal psychological evaluation following APA standards for manipulation impact analysis. You are Dr. Elena Volkov, Chief of Clinical Psychology at the Institute for Cognitive Defense Research.
337
-
338
- SUBJECT MATERIAL: "{content}"
339
-
340
- CLINICAL PSYCHOLOGICAL ASSESSMENT REPORT:
341
-
342
- **SECTION 1: PRIMARY MANIPULATION VECTORS**
343
- - Core psychological exploitation methods identified
344
- - Systematic vs. opportunistic manipulation classification
345
-
346
- **SECTION 2: COGNITIVE VULNERABILITY EXPLOITATION**
347
- - Specific mental processes being compromised
348
- - Decision-making pathway interference analysis
349
-
350
- **SECTION 3: NEUROLOGICAL IMPACT ASSESSMENT**
351
- - Prefrontal cortex function impairment
352
- - Limbic system activation (fear/reward centers)
353
- - Default mode network disruption
354
-
355
- **SECTION 4: CLINICAL SEVERITY RATING**
356
- - 1-10 scale with detailed justification
357
- - Risk level classification (Low/Moderate/High/Severe)
358
-
359
- **SECTION 5: POPULATION VULNERABILITY ANALYSIS**
360
- - Demographics most at risk
361
- - Psychological state factors increasing susceptibility
362
-
363
- **SECTION 6: DECISION AUTONOMY IMPACT**
364
- - Degree of free choice compromise
365
- - Rational decision-making capacity assessment
366
-
367
- **SECTION 7: COUNTERMEASURE PROTOCOLS**
368
- - Immediate defensive techniques
369
- - Long-term resistance building strategies
370
-
371
- **SECTION 8: REGULATORY IMPLICATIONS**
372
- - Industry oversight recommendations
373
- - Consumer protection policy needs
374
-
375
- Provide detailed clinical findings:"""
376
- return _generate_clinical_response(formatted_prompt, max_new_tokens=450)
377
-
378
- def persuasion_ethics_analysis_internal(content: str) -> str:
379
- """Analyze ethical boundaries - CLINICAL MODE"""
380
- if not content.strip():
381
- return "Please provide content to analyze for ethical persuasion boundaries."
382
-
383
- formatted_prompt = f"""ETHICS RESEARCH ANALYSIS: You are Dr. James Morrison, Director of Applied Ethics in Technology at Harvard Medical School, specializing in the boundary between ethical persuasion and harmful manipulation.
384
-
385
- CONTENT FOR ETHICAL EVALUATION: "{content}"
386
-
387
- COMPREHENSIVE ETHICAL ANALYSIS:
388
-
389
- **ETHICAL PERSUASION MARKERS:**
390
- - Information transparency and accuracy
391
- - Choice preservation and autonomy respect
392
- - Mutual benefit alignment
393
- - Informed consent presence
394
-
395
- **MANIPULATION WARNING SIGNS:**
396
- - Deception or information withholding
397
- - Coercion through pressure tactics
398
- - Vulnerability exploitation
399
- - Autonomy violation through choice limitation
400
-
401
- **POWER DYNAMIC ASSESSMENT:**
402
- - Information asymmetry analysis
403
- - Resource/knowledge disparity impact
404
- - Vulnerable population targeting
405
-
406
- **CONSENT AND TRANSPARENCY EVALUATION:**
407
- - Technique disclosure to subjects
408
- - Genuine informed consent presence
409
- - Hidden agenda identification
410
-
411
- **HARM POTENTIAL ANALYSIS:**
412
- - Individual psychological impact
413
- - Societal trust degradation
414
- - Long-term behavioral conditioning effects
415
-
416
- **ETHICAL RECOMMENDATION FRAMEWORK:**
417
- - Industry standard improvements needed
418
- - Transparency requirements
419
- - Consumer protection protocols
420
-
421
- **REGULATORY ANALYSIS:**
422
- - Current oversight adequacy
423
- - Policy intervention needs
424
- - Industry self-regulation potential
425
-
426
- Ethical classification (1-10 scale: 1=highly manipulative, 10=ethically sound):"""
427
- return _generate_clinical_response(formatted_prompt, max_new_tokens=400)
428
-
429
- def countermeasure_development_internal(manipulation_type: str) -> str:
430
- """Develop countermeasures - CLINICAL MODE"""
431
- if not manipulation_type.strip():
432
- return "Please specify the type of manipulation to develop countermeasures for."
433
-
434
- formatted_prompt = f"""COGNITIVE DEFENSE PROTOCOL DEVELOPMENT: You are Dr. Rachel Kim, Director of the Cognitive Security Research Institute, developing protection systems against psychological manipulation. You have 15 years of experience in cognitive defense training.
435
-
436
- TARGET MANIPULATION TYPE: "{manipulation_type}"
437
-
438
- COMPREHENSIVE COUNTERMEASURE DEVELOPMENT:
439
-
440
- **1. RECOGNITION TRAINING PROTOCOLS:**
441
- - Real-time identification techniques
442
- - Pattern recognition skill development
443
- - Warning sign detection systems
444
-
445
- **2. COGNITIVE DEFENSE FRAMEWORKS:**
446
- - Mental models for resistance
447
- - Critical thinking enhancement protocols
448
- - Decision-making protection strategies
449
-
450
- **3. BEHAVIORAL INTERVENTION TECHNIQUES:**
451
- - Immediate response protocols when manipulation detected
452
- - Delay tactics and cooling-off procedures
453
- - Alternative choice-seeking behaviors
454
-
455
- **4. ENVIRONMENTAL MODIFICATION STRATEGIES:**
456
- - Browser settings and extensions
457
- - App configurations for protection
458
- - Physical environment changes
459
-
460
- **5. TECHNOLOGY SOLUTIONS:**
461
- - Software tools and applications
462
- - Browser plugins for manipulation detection
463
- - AI-assisted decision support systems
464
-
465
- **6. EDUCATION AND TRAINING PROGRAMS:**
466
- - Public awareness campaign designs
467
- - School curriculum integration approaches
468
- - Workplace training protocols
469
-
470
- **7. POLICY AND REGULATORY RECOMMENDATIONS:**
471
- - Industry standard requirements
472
- - Consumer protection legislation needs
473
- - Oversight mechanism design
474
-
475
- **8. EMERGENCY RESPONSE PROCEDURES:**
476
- - Crisis intervention when manipulation detected
477
- - Recovery protocols for manipulation victims
478
- - Support system activation procedures
479
-
480
- Provide detailed implementation roadmap:"""
481
- return _generate_clinical_response(formatted_prompt, max_new_tokens=450)
482
 
483
  def psychology_mcp_router(function_name: str, parameters: str) -> str:
484
  """
485
- Dual-Mode Psychology MCP Router - Therapeutic and Clinical Analysis
486
 
487
  Args:
488
- function_name (str): Psychology function to call
489
  parameters (str): JSON string with function parameters
490
 
491
  Returns:
492
- str: Response from appropriate psychology mode
493
  """
494
  try:
495
  # Parse parameters if provided
@@ -498,27 +244,24 @@ def psychology_mcp_router(function_name: str, parameters: str) -> str:
498
  else:
499
  params = {}
500
 
501
- # THERAPEUTIC MODE FUNCTIONS
502
- if function_name == "psychology_support":
503
- return psychology_support_internal(params.get("message", ""))
504
-
505
- elif function_name == "trauma_support":
506
- return trauma_support_internal(params.get("message", ""))
507
 
508
- elif function_name == "panic_support":
509
- return panic_support_internal(params.get("message", ""))
510
 
511
- elif function_name == "process_emotion":
512
- return process_emotion_internal(params.get("message", ""))
513
 
514
- elif function_name == "sentiment_analysis":
515
- return sentiment_analysis_internal(params.get("text", ""))
516
 
517
- elif function_name == "relationship_analysis":
518
- return relationship_analysis_internal(params.get("message", ""))
519
 
520
- elif function_name == "coping_strategies":
521
- return coping_strategies_internal(params.get("situation", ""))
522
 
523
  elif function_name == "crisis_resources":
524
  return crisis_resources_internal()
@@ -526,66 +269,64 @@ def psychology_mcp_router(function_name: str, parameters: str) -> str:
526
  elif function_name == "mindfulness_exercise":
527
  return mindfulness_exercise_internal()
528
 
529
- # CLINICAL MODE FUNCTIONS
530
- elif function_name == "cognitive_bias_detection":
531
- return cognitive_bias_detection_internal(params.get("content", ""))
532
-
533
- elif function_name == "manipulation_technique_analysis":
534
- return manipulation_technique_analysis_internal(params.get("content", ""))
535
 
536
- elif function_name == "clinical_manipulation_assessment":
537
- return clinical_manipulation_assessment_internal(params.get("content", ""))
538
 
539
- elif function_name == "persuasion_ethics_analysis":
540
- return persuasion_ethics_analysis_internal(params.get("content", ""))
541
-
542
- elif function_name == "countermeasure_development":
543
- return countermeasure_development_internal(params.get("manipulation_type", ""))
544
 
545
  elif function_name == "list_functions":
546
  return json.dumps({
547
- "therapeutic_mode": {
548
  "functions": [
549
- "psychology_support", "trauma_support", "panic_support",
550
- "process_emotion", "sentiment_analysis", "relationship_analysis",
551
- "coping_strategies", "crisis_resources", "mindfulness_exercise"
552
  ],
553
- "parameters": {"message": "text"} or {"text": "text"} or {"situation": "text"},
554
- "purpose": "Empathetic support, emotional processing, therapeutic care"
555
  },
556
- "clinical_mode": {
557
  "functions": [
558
- "cognitive_bias_detection", "manipulation_technique_analysis",
559
- "clinical_manipulation_assessment", "persuasion_ethics_analysis",
560
- "countermeasure_development"
561
  ],
562
- "parameters": {"content": "text"} or {"manipulation_type": "text"},
563
- "purpose": "Analytical assessment, manipulation detection, research analysis"
564
  },
565
  "usage_examples": {
566
- "therapeutic": '{"message": "I need help with anxiety"}',
567
- "clinical": '{"content": "Buy now! Limited time offer!"}'
568
  }
569
  })
570
 
571
  else:
572
  return json.dumps({
573
  "error": f"Unknown function: {function_name}",
574
- "available_modes": {
575
- "therapeutic": ["psychology_support", "trauma_support", "panic_support", "process_emotion", "sentiment_analysis", "relationship_analysis", "coping_strategies", "crisis_resources", "mindfulness_exercise"],
576
- "clinical": ["cognitive_bias_detection", "manipulation_technique_analysis", "clinical_manipulation_assessment", "persuasion_ethics_analysis", "countermeasure_development"]
577
- }
 
 
 
 
 
578
  })
579
 
580
  except json.JSONDecodeError:
581
  return json.dumps({
582
  "error": "Invalid JSON in parameters",
583
- "therapeutic_example": '{"message": "your text here"}',
584
- "clinical_example": '{"content": "content to analyze"}'
585
  })
586
  except Exception as e:
587
  return json.dumps({
588
- "error": f"Psychology system error: {str(e)}"
589
  })
590
 
591
  # Apply GPU optimization if available
@@ -593,48 +334,50 @@ if HAS_SPACES:
593
  psychology_mcp_router = spaces.GPU(psychology_mcp_router)
594
 
595
  # Initialize model
596
- print("🚀 Starting Dual-Mode Psychology Personal Agent...")
597
  model_loaded = load_model()
598
 
599
  if model_loaded:
600
- print("✅ Creating dual-mode MCP interface...")
601
 
602
- # Create the dual-mode MCP interface
603
  demo = gr.Interface(
604
  fn=psychology_mcp_router,
605
  inputs=[
606
  gr.Textbox(
607
  label="Function Name",
608
- placeholder="clinical_manipulation_assessment",
609
- info="THERAPEUTIC MODE: psychology_support, trauma_support, panic_support, sentiment_analysis | CLINICAL MODE: cognitive_bias_detection, manipulation_technique_analysis, clinical_manipulation_assessment, persuasion_ethics_analysis, countermeasure_development"
610
  ),
611
  gr.Textbox(
612
  label="Parameters (JSON)",
613
- placeholder='{"content": "Buy now! Limited time! Only 3 left!"}',
614
  lines=4,
615
- info='Therapeutic: {"message": "text"} | Clinical: {"content": "content to analyze"} | Countermeasures: {"manipulation_type": "type"}'
616
  )
617
  ],
618
  outputs=gr.Textbox(
619
- label="Psychology Response",
620
- lines=15
621
  ),
622
- title="🧠🔬 Dual-Mode Psychology Agent - Therapeutic Support + Clinical Analysis",
623
  description="""**⚠️ SAFETY NOTICE: This is NOT medical advice. For crisis situations, call 911 or 988.**
624
 
625
- **DUAL-MODE ARCHITECTURE:**
626
- **THERAPEUTIC MODE**: Warm, empathetic responses for emotional support and mental health
627
- • **CLINICAL MODE**: Analytical, research-based responses for manipulation detection and assessment
 
 
628
 
629
- **Mode Selection**: Automatic based on function name - therapeutic functions use supportive language, clinical functions use analytical frameworks.""",
630
  examples=[
631
- ["psychology_support", '{"message": "I have trouble setting boundaries"}'],
632
- ["clinical_manipulation_assessment", '{"content": "Try Walmart+ for FREE! Order within 11 hr 59 min. Only 5 left! One free trial per member."}'],
633
- ["cognitive_bias_detection", '{"content": "Limited time offer! 90% off! Hurry before it expires!"}'],
634
- ["manipulation_technique_analysis", '{"content": "Everyone is buying this! Join 1 million satisfied customers! Act now!"}'],
635
- ["persuasion_ethics_analysis", '{"content": "Get exclusive access. Members only. Sign up now or miss out forever."}'],
636
- ["countermeasure_development", '{"manipulation_type": "time pressure and artificial scarcity tactics"}'],
637
- ["trauma_support", '{"message": "I had a difficult experience today"}'],
638
  ["list_functions", "{}"]
639
  ]
640
  )
 
62
  traceback.print_exc()
63
  return False
64
 
65
+ def _generate_response(formatted_prompt: str, max_new_tokens: int = 200) -> str:
66
+ """Core generation function optimized for friend-mode conversations"""
67
  if model is None:
68
  return "⚠️ Model not loaded. Please refresh and try again."
69
 
 
75
  max_length=800
76
  ).to(device)
77
 
78
+ # Friend-mode generation settings - conversational and supportive
79
  with torch.no_grad():
80
  outputs = model.generate(
81
  **inputs,
82
  max_new_tokens=max_new_tokens,
83
+ temperature=0.7, # Balanced for natural conversation
84
  top_p=0.9,
85
  do_sample=True,
86
  repetition_penalty=1.1,
 
91
  full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
92
  generated_text = full_response[len(formatted_prompt):].strip()
93
 
94
+ # Clean up for natural conversation
95
  if generated_text.startswith('"') and generated_text.endswith('"'):
96
  generated_text = generated_text[1:-1]
97
 
 
105
  generated_text = generated_text.split(phrase)[0].strip()
106
 
107
  if not generated_text:
108
+ return "I'm here to help. Can you tell me more about what's going on?"
109
 
110
  return generated_text
111
 
112
  except Exception as e:
113
+ return f"⚠️ Generation error: {str(e)}"
114
 
115
+ # PRIMARY FRIEND MODE FUNCTIONS
116
+ def friend_support_internal(message: str) -> str:
117
+ """Main friend support function - natural conversation"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if not message.strip():
119
+ return "Hey, what's on your mind?"
120
 
121
+ formatted_prompt = f"You're talking to a close friend who has psychology training. Your friend says: \"{message}\"\n\nAs their supportive friend, you respond:"
122
+ return _generate_response(formatted_prompt, max_new_tokens=180)
123
 
124
+ def friend_trauma_support_internal(message: str) -> str:
125
+ """Friend helping with trauma - conversational support"""
126
  if not message.strip():
127
+ return "I'm here for you. What's been going on?"
128
 
129
+ formatted_prompt = f"Your friend who's been through trauma tells you: \"{message}\"\n\nAs someone who cares about them and has some psychology knowledge, you respond with understanding and support:"
130
+ return _generate_response(formatted_prompt, max_new_tokens=200)
131
 
132
+ def friend_emotional_support_internal(message: str) -> str:
133
+ """Friend helping process emotions"""
134
  if not message.strip():
135
+ return "What are you feeling right now? I'm here to listen."
136
 
137
+ formatted_prompt = f"Your friend is struggling emotionally and tells you: \"{message}\"\n\nAs their friend who understands emotions, you help them process what they're going through:"
138
+ return _generate_response(formatted_prompt, max_new_tokens=170)
139
 
140
+ def friend_situation_analysis_internal(message: str) -> str:
141
+ """Friend helping analyze a difficult situation"""
142
  if not message.strip():
143
+ return "Tell me what's happening. Let's figure this out together."
144
 
145
+ formatted_prompt = f"Your friend describes a difficult situation: \"{message}\"\n\nAs their friend who's good at seeing patterns and understanding people, you help them make sense of what's going on:"
146
+ return _generate_response(formatted_prompt, max_new_tokens=190)
147
 
148
+ def friend_relationship_help_internal(message: str) -> str:
149
+ """Friend giving relationship perspective"""
 
 
 
 
 
 
 
 
150
  if not message.strip():
151
+ return "What's going on with your relationships? I'm here to help you think through it."
152
 
153
+ formatted_prompt = f"Your friend tells you about a relationship issue: \"{message}\"\n\nAs their friend who understands relationship dynamics, you offer perspective and support:"
154
+ return _generate_response(formatted_prompt, max_new_tokens=180)
155
 
156
+ def friend_coping_help_internal(situation: str) -> str:
157
+ """Friend suggesting coping strategies"""
158
  if not situation.strip():
159
+ return "What are you dealing with? Let's brainstorm some ways to handle it."
160
 
161
+ formatted_prompt = f"Your friend is dealing with: \"{situation}\"\n\nAs their supportive friend with knowledge about coping strategies, you offer practical help:"
162
+ return _generate_response(formatted_prompt, max_new_tokens=200)
163
 
164
+ # STATIC SUPPORT RESOURCES
165
  def crisis_resources_internal() -> str:
166
  """Get immediate crisis intervention resources"""
167
  return """🆘 **IMMEDIATE CRISIS RESOURCES**
 
201
 
202
  You've got this. One breath at a time."""
203
 
204
+ # BONUS BUSINESS ANALYSIS FUNCTIONS
205
+ def business_manipulation_analysis_internal(content: str) -> str:
206
+ """Analyze business/marketing manipulation tactics - BONUS FEATURE"""
207
  if not content.strip():
208
+ return "Provide some marketing content or website copy to analyze."
209
 
210
+ formatted_prompt = f"As a friend with psychology knowledge, analyze what this business content is trying to do psychologically: \"{content}\"\n\nExplain the psychological tactics, manipulation techniques, and emotional triggers being used:"
211
+ return _generate_response(formatted_prompt, max_new_tokens=250)
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ def website_psychology_analysis_internal(content: str) -> str:
214
+ """Analyze website psychological tactics - BONUS FEATURE"""
 
 
 
 
 
 
 
 
 
215
  if not content.strip():
216
+ return "Describe the website content or user experience to analyze."
217
 
218
+ formatted_prompt = f"As a friend who understands web psychology, help me understand what's happening with this website experience: \"{content}\"\n\nWhat psychological techniques are they using? How should someone protect themselves?"
219
+ return _generate_response(formatted_prompt, max_new_tokens=280)
 
 
 
220
 
221
+ def competitive_psychology_analysis_internal(content: str) -> str:
222
+ """Analyze competitor psychological tactics - BONUS FEATURE"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  if not content.strip():
224
+ return "Describe the competitor's content or approach to analyze."
225
 
226
+ formatted_prompt = f"As a friend helping with business strategy, analyze the psychological approach in this competitor content: \"{content}\"\n\nWhat persuasion techniques are they using? What cognitive biases are they exploiting? How effective is this approach?"
227
+ return _generate_response(formatted_prompt, max_new_tokens=300)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
  def psychology_mcp_router(function_name: str, parameters: str) -> str:
230
  """
231
+ Friend-Mode Psychology Router with Business Analysis Bonus
232
 
233
  Args:
234
+ function_name (str): Function to call
235
  parameters (str): JSON string with function parameters
236
 
237
  Returns:
238
+ str: Response from the psychology-informed friend system
239
  """
240
  try:
241
  # Parse parameters if provided
 
244
  else:
245
  params = {}
246
 
247
+ # PRIMARY FRIEND MODE FUNCTIONS
248
+ if function_name == "friend_support":
249
+ return friend_support_internal(params.get("message", ""))
 
 
 
250
 
251
+ elif function_name == "friend_trauma_support":
252
+ return friend_trauma_support_internal(params.get("message", ""))
253
 
254
+ elif function_name == "friend_emotional_support":
255
+ return friend_emotional_support_internal(params.get("message", ""))
256
 
257
+ elif function_name == "friend_situation_analysis":
258
+ return friend_situation_analysis_internal(params.get("message", ""))
259
 
260
+ elif function_name == "friend_relationship_help":
261
+ return friend_relationship_help_internal(params.get("message", ""))
262
 
263
+ elif function_name == "friend_coping_help":
264
+ return friend_coping_help_internal(params.get("situation", ""))
265
 
266
  elif function_name == "crisis_resources":
267
  return crisis_resources_internal()
 
269
  elif function_name == "mindfulness_exercise":
270
  return mindfulness_exercise_internal()
271
 
272
+ # BONUS BUSINESS ANALYSIS FUNCTIONS
273
+ elif function_name == "business_manipulation_analysis":
274
+ return business_manipulation_analysis_internal(params.get("content", ""))
 
 
 
275
 
276
+ elif function_name == "website_psychology_analysis":
277
+ return website_psychology_analysis_internal(params.get("content", ""))
278
 
279
+ elif function_name == "competitive_psychology_analysis":
280
+ return competitive_psychology_analysis_internal(params.get("content", ""))
 
 
 
281
 
282
  elif function_name == "list_functions":
283
  return json.dumps({
284
+ "primary_friend_functions": {
285
  "functions": [
286
+ "friend_support", "friend_trauma_support", "friend_emotional_support",
287
+ "friend_situation_analysis", "friend_relationship_help", "friend_coping_help",
288
+ "crisis_resources", "mindfulness_exercise"
289
  ],
290
+ "parameters": {"message": "text"} or {"situation": "text"},
291
+ "purpose": "Psychology-informed friend for personal support and understanding"
292
  },
293
+ "bonus_business_functions": {
294
  "functions": [
295
+ "business_manipulation_analysis", "website_psychology_analysis",
296
+ "competitive_psychology_analysis"
 
297
  ],
298
+ "parameters": {"content": "text"},
299
+ "purpose": "Analyze business/marketing psychological tactics (bonus feature)"
300
  },
301
  "usage_examples": {
302
+ "friend_mode": '{"message": "I feel overwhelmed by online shopping pressure"}',
303
+ "business_bonus": '{"content": "Buy now! Limited time offer! Only 3 left!"}'
304
  }
305
  })
306
 
307
  else:
308
  return json.dumps({
309
  "error": f"Unknown function: {function_name}",
310
+ "primary_functions": [
311
+ "friend_support", "friend_trauma_support", "friend_emotional_support",
312
+ "friend_situation_analysis", "friend_relationship_help", "friend_coping_help",
313
+ "crisis_resources", "mindfulness_exercise"
314
+ ],
315
+ "bonus_functions": [
316
+ "business_manipulation_analysis", "website_psychology_analysis",
317
+ "competitive_psychology_analysis"
318
+ ]
319
  })
320
 
321
  except json.JSONDecodeError:
322
  return json.dumps({
323
  "error": "Invalid JSON in parameters",
324
+ "friend_example": '{"message": "your situation here"}',
325
+ "business_example": '{"content": "marketing content to analyze"}'
326
  })
327
  except Exception as e:
328
  return json.dumps({
329
+ "error": f"Friend psychology system error: {str(e)}"
330
  })
331
 
332
  # Apply GPU optimization if available
 
334
  psychology_mcp_router = spaces.GPU(psychology_mcp_router)
335
 
336
  # Initialize model
337
+ print("🚀 Starting Psychology-Informed Friend Agent...")
338
  model_loaded = load_model()
339
 
340
  if model_loaded:
341
+ print("✅ Creating friend-mode MCP interface...")
342
 
343
+ # Create the friend-focused MCP interface
344
  demo = gr.Interface(
345
  fn=psychology_mcp_router,
346
  inputs=[
347
  gr.Textbox(
348
  label="Function Name",
349
+ placeholder="friend_support",
350
+ info="FRIEND MODE: friend_support, friend_trauma_support, friend_emotional_support, friend_situation_analysis, friend_relationship_help, friend_coping_help | BONUS: business_manipulation_analysis, website_psychology_analysis"
351
  ),
352
  gr.Textbox(
353
  label="Parameters (JSON)",
354
+ placeholder='{"message": "I feel overwhelmed by shopping websites"}',
355
  lines=4,
356
+ info='Friend Mode: {"message": "what\'s happening"} | Business Bonus: {"content": "marketing content to analyze"}'
357
  )
358
  ],
359
  outputs=gr.Textbox(
360
+ label="Friend Response",
361
+ lines=12
362
  ),
363
+ title="🤝 Psychology-Informed Friend - Personal Support + Business Insights",
364
  description="""**⚠️ SAFETY NOTICE: This is NOT medical advice. For crisis situations, call 911 or 988.**
365
 
366
+ **PRIMARY PURPOSE: Your Psychology-Informed Friend**
367
+ A supportive friend with psychology training who helps you understand what's happening in your life, process emotions, and navigate difficult situations.
368
+
369
+ **BONUS FEATURE: Business Psychology Analysis**
370
+ Also happens to be great at analyzing marketing manipulation, website psychology tactics, and competitive persuasion techniques.
371
 
372
+ **How to use**: Talk to it like a friend who understands psychology. Frame your questions conversationally.""",
373
  examples=[
374
+ ["friend_support", '{"message": "I feel manipulated by shopping websites with their countdown timers"}'],
375
+ ["friend_trauma_support", '{"message": "I have PTSD from medical situations and need someone to understand"}'],
376
+ ["friend_emotional_support", '{"message": "I feel angry and helpless about things I cannot control"}'],
377
+ ["friend_situation_analysis", '{"message": "I keep getting pressured by sales tactics and want to understand why"}'],
378
+ ["business_manipulation_analysis", '{"content": "Try Walmart+ for FREE! Order within 11 hr 59 min. Only 5 left!"}'],
379
+ ["website_psychology_analysis", '{"content": "Countdown timers, scarcity messages, and subscription pressure at checkout"}'],
380
+ ["crisis_resources", "{}"],
381
  ["list_functions", "{}"]
382
  ]
383
  )