Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -62,8 +62,8 @@ def load_model():
|
|
| 62 |
traceback.print_exc()
|
| 63 |
return False
|
| 64 |
|
| 65 |
-
def
|
| 66 |
-
"""
|
| 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 |
-
#
|
| 79 |
with torch.no_grad():
|
| 80 |
outputs = model.generate(
|
| 81 |
**inputs,
|
| 82 |
max_new_tokens=max_new_tokens,
|
| 83 |
-
temperature=0.
|
| 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 |
-
#
|
| 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
|
| 109 |
|
| 110 |
return generated_text
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
-
return f"⚠️
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 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 "
|
| 172 |
|
| 173 |
-
formatted_prompt = f"
|
| 174 |
-
return
|
| 175 |
|
| 176 |
-
def
|
| 177 |
-
"""
|
| 178 |
if not message.strip():
|
| 179 |
-
return "I'm here
|
| 180 |
|
| 181 |
-
formatted_prompt = f"
|
| 182 |
-
return
|
| 183 |
|
| 184 |
-
def
|
| 185 |
-
"""
|
| 186 |
if not message.strip():
|
| 187 |
-
return "
|
| 188 |
|
| 189 |
-
formatted_prompt = f"
|
| 190 |
-
return
|
| 191 |
|
| 192 |
-
def
|
| 193 |
-
"""
|
| 194 |
if not message.strip():
|
| 195 |
-
return "
|
| 196 |
|
| 197 |
-
formatted_prompt = f"
|
| 198 |
-
return
|
| 199 |
|
| 200 |
-
def
|
| 201 |
-
"""
|
| 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 "
|
| 212 |
|
| 213 |
-
formatted_prompt = f"
|
| 214 |
-
return
|
| 215 |
|
| 216 |
-
def
|
| 217 |
-
"""
|
| 218 |
if not situation.strip():
|
| 219 |
-
return "
|
| 220 |
|
| 221 |
-
formatted_prompt = f"
|
| 222 |
-
return
|
| 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 |
-
#
|
| 264 |
-
def
|
| 265 |
-
"""
|
| 266 |
if not content.strip():
|
| 267 |
-
return "
|
| 268 |
|
| 269 |
-
formatted_prompt = f"
|
| 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 |
-
|
| 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 "
|
| 297 |
|
| 298 |
-
formatted_prompt = f"
|
| 299 |
-
|
| 300 |
-
CONTENT UNDER ANALYSIS: "{content}"
|
| 301 |
-
|
| 302 |
-
Provide systematic classification of manipulation vectors:
|
| 303 |
|
| 304 |
-
|
| 305 |
-
|
| 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 "
|
| 335 |
|
| 336 |
-
formatted_prompt = f"
|
| 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 |
-
|
| 486 |
|
| 487 |
Args:
|
| 488 |
-
function_name (str):
|
| 489 |
parameters (str): JSON string with function parameters
|
| 490 |
|
| 491 |
Returns:
|
| 492 |
-
str: Response from
|
| 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 |
-
#
|
| 502 |
-
if function_name == "
|
| 503 |
-
return
|
| 504 |
-
|
| 505 |
-
elif function_name == "trauma_support":
|
| 506 |
-
return trauma_support_internal(params.get("message", ""))
|
| 507 |
|
| 508 |
-
elif function_name == "
|
| 509 |
-
return
|
| 510 |
|
| 511 |
-
elif function_name == "
|
| 512 |
-
return
|
| 513 |
|
| 514 |
-
elif function_name == "
|
| 515 |
-
return
|
| 516 |
|
| 517 |
-
elif function_name == "
|
| 518 |
-
return
|
| 519 |
|
| 520 |
-
elif function_name == "
|
| 521 |
-
return
|
| 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 |
-
#
|
| 530 |
-
elif function_name == "
|
| 531 |
-
return
|
| 532 |
-
|
| 533 |
-
elif function_name == "manipulation_technique_analysis":
|
| 534 |
-
return manipulation_technique_analysis_internal(params.get("content", ""))
|
| 535 |
|
| 536 |
-
elif function_name == "
|
| 537 |
-
return
|
| 538 |
|
| 539 |
-
elif function_name == "
|
| 540 |
-
return
|
| 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 |
-
"
|
| 548 |
"functions": [
|
| 549 |
-
"
|
| 550 |
-
"
|
| 551 |
-
"
|
| 552 |
],
|
| 553 |
-
"parameters": {"message": "text"} or {"
|
| 554 |
-
"purpose": "
|
| 555 |
},
|
| 556 |
-
"
|
| 557 |
"functions": [
|
| 558 |
-
"
|
| 559 |
-
"
|
| 560 |
-
"countermeasure_development"
|
| 561 |
],
|
| 562 |
-
"parameters": {"content": "text"}
|
| 563 |
-
"purpose": "
|
| 564 |
},
|
| 565 |
"usage_examples": {
|
| 566 |
-
"
|
| 567 |
-
"
|
| 568 |
}
|
| 569 |
})
|
| 570 |
|
| 571 |
else:
|
| 572 |
return json.dumps({
|
| 573 |
"error": f"Unknown function: {function_name}",
|
| 574 |
-
"
|
| 575 |
-
"
|
| 576 |
-
"
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
})
|
| 579 |
|
| 580 |
except json.JSONDecodeError:
|
| 581 |
return json.dumps({
|
| 582 |
"error": "Invalid JSON in parameters",
|
| 583 |
-
"
|
| 584 |
-
"
|
| 585 |
})
|
| 586 |
except Exception as e:
|
| 587 |
return json.dumps({
|
| 588 |
-
"error": f"
|
| 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
|
| 597 |
model_loaded = load_model()
|
| 598 |
|
| 599 |
if model_loaded:
|
| 600 |
-
print("✅ Creating
|
| 601 |
|
| 602 |
-
# Create the
|
| 603 |
demo = gr.Interface(
|
| 604 |
fn=psychology_mcp_router,
|
| 605 |
inputs=[
|
| 606 |
gr.Textbox(
|
| 607 |
label="Function Name",
|
| 608 |
-
placeholder="
|
| 609 |
-
info="
|
| 610 |
),
|
| 611 |
gr.Textbox(
|
| 612 |
label="Parameters (JSON)",
|
| 613 |
-
placeholder='{"
|
| 614 |
lines=4,
|
| 615 |
-
info='
|
| 616 |
)
|
| 617 |
],
|
| 618 |
outputs=gr.Textbox(
|
| 619 |
-
label="
|
| 620 |
-
lines=
|
| 621 |
),
|
| 622 |
-
title="
|
| 623 |
description="""**⚠️ SAFETY NOTICE: This is NOT medical advice. For crisis situations, call 911 or 988.**
|
| 624 |
|
| 625 |
-
**
|
| 626 |
-
|
| 627 |
-
|
|
|
|
|
|
|
| 628 |
|
| 629 |
-
**
|
| 630 |
examples=[
|
| 631 |
-
["
|
| 632 |
-
["
|
| 633 |
-
["
|
| 634 |
-
["
|
| 635 |
-
["
|
| 636 |
-
["
|
| 637 |
-
["
|
| 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 |
)
|