phxdev commited on
Commit
88eac55
·
verified ·
1 Parent(s): 9940952

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +391 -0
app.py CHANGED
@@ -274,11 +274,402 @@ def mindfulness_exercise() -> str:
274
 
275
  You are safe. You are here. This moment will pass."""
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  # Apply GPU optimization if available
278
  if HAS_SPACES:
279
  psychology_support = spaces.GPU(psychology_support)
280
  trauma_support = spaces.GPU(trauma_support)
281
  panic_support = spaces.GPU(panic_support)
 
 
 
 
 
 
 
 
 
282
 
283
  # Initialize model
284
  print("🚀 Starting Psychology Personal Agent...")
 
274
 
275
  You are safe. You are here. This moment will pass."""
276
 
277
+ def process_emotion(message: str) -> str:
278
+ """
279
+ Core emotion processing engine - labels, validates, and routes emotions.
280
+ """
281
+
282
+ if model is None:
283
+ return "⚠️ Psychology model is loading. Please try again in a moment."
284
+
285
+ formatted_prompt = f"""Someone is experiencing an emotion and said: "{message}"
286
+
287
+ You're an emotion processing system. Use their exact words and energy.
288
+
289
+ Process their emotion systematically:
290
+ - Label the emotion accurately (not just "sad" - is it grief, disappointment, loneliness?)
291
+ - Validate that this emotion makes sense given their situation
292
+ - Identify what the emotion is telling them (anger = boundary violation, anxiety = perceived threat, etc.)
293
+ - Give them 2-3 specific things to do with this emotion right now
294
+ - Don't try to make the emotion go away - process it
295
+
296
+ "You're feeling [specific emotion]. That makes complete sense because [validation]. This emotion is telling you [information]. Here's what to do: [specific actions]."
297
+
298
+ Sound like an emotion expert who knows feelings have jobs to do:"""
299
+
300
+ try:
301
+ inputs = tokenizer(
302
+ formatted_prompt,
303
+ return_tensors="pt",
304
+ truncation=True,
305
+ max_length=512
306
+ ).to(device)
307
+
308
+ with torch.no_grad():
309
+ outputs = model.generate(
310
+ **inputs,
311
+ max_length=len(inputs.input_ids[0]) + 300,
312
+ temperature=0.8,
313
+ top_p=0.9,
314
+ do_sample=True,
315
+ repetition_penalty=1.1,
316
+ pad_token_id=tokenizer.eos_token_id,
317
+ eos_token_id=tokenizer.eos_token_id,
318
+ )
319
+
320
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
321
+ generated_text = response[len(formatted_prompt):].strip()
322
+
323
+ if generated_text.startswith('"') and generated_text.endswith('"'):
324
+ generated_text = generated_text[1:-1]
325
+
326
+ return generated_text
327
+
328
+ except Exception as e:
329
+ return f"⚠️ Error generating response: {str(e)}"
330
+
331
+ def set_boundary(message: str) -> str:
332
+ """
333
+ Boundary setting system - analyzes situation and provides enforcement strategy.
334
+ """
335
+
336
+ if model is None:
337
+ return "⚠️ Psychology model is loading. Please try again in a moment."
338
+
339
+ formatted_prompt = f"""Someone needs to set a boundary and said: "{message}"
340
+
341
+ You're a boundary implementation system. Use their words and energy.
342
+
343
+ Design their boundary strategy:
344
+ - Identify what boundary they need (time, emotional, physical, professional)
345
+ - Give them the exact script to communicate it clearly
346
+ - Predict how the other person will respond and prep counter-responses
347
+ - Set up enforcement consequences if the boundary gets crossed
348
+ - Make it non-negotiable but not mean
349
+
350
+ "You need a [type] boundary. Say this exactly: '[script]'. When they push back with '[predicted response]', say '[counter-script]'. If they violate it, do this: '[consequence]'."
351
+
352
+ Sound like someone who knows boundaries are about self-protection, not punishment:"""
353
+
354
+ try:
355
+ inputs = tokenizer(
356
+ formatted_prompt,
357
+ return_tensors="pt",
358
+ truncation=True,
359
+ max_length=512
360
+ ).to(device)
361
+
362
+ with torch.no_grad():
363
+ outputs = model.generate(
364
+ **inputs,
365
+ max_length=len(inputs.input_ids[0]) + 300,
366
+ temperature=0.8,
367
+ top_p=0.9,
368
+ do_sample=True,
369
+ repetition_penalty=1.1,
370
+ pad_token_id=tokenizer.eos_token_id,
371
+ eos_token_id=tokenizer.eos_token_id,
372
+ )
373
+
374
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
375
+ generated_text = response[len(formatted_prompt):].strip()
376
+
377
+ if generated_text.startswith('"') and generated_text.endswith('"'):
378
+ generated_text = generated_text[1:-1]
379
+
380
+ return generated_text
381
+
382
+ except Exception as e:
383
+ return f"⚠️ Error generating response: {str(e)}"
384
+
385
+ def handle_conflict(message: str) -> str:
386
+ """
387
+ Conflict response router - analyzes conflict type and selects optimal approach.
388
+ """
389
+
390
+ if model is None:
391
+ return "⚠️ Psychology model is loading. Please try again in a moment."
392
+
393
+ formatted_prompt = f"""Someone is in conflict and said: "{message}"
394
+
395
+ You're a conflict response system. Use their words and match their energy.
396
+
397
+ Route their conflict strategy:
398
+ - Assess conflict type (values clash, resource competition, communication breakdown, power struggle)
399
+ - Analyze the other person's likely motivations and triggers
400
+ - Calculate optimal approach: engage directly, de-escalate, get mediator, or strategic withdrawal
401
+ - Give them specific tactics for their chosen approach
402
+ - Predict likely outcomes and backup plans
403
+
404
+ "This is a [conflict type]. The other person wants [motivation]. Your best approach is [strategy]. Use these tactics: [specific actions]. If that fails, do this: [backup plan]."
405
+
406
+ Sound like someone who knows conflict is chess, not war:"""
407
+
408
+ try:
409
+ inputs = tokenizer(
410
+ formatted_prompt,
411
+ return_tensors="pt",
412
+ truncation=True,
413
+ max_length=512
414
+ ).to(device)
415
+
416
+ with torch.no_grad():
417
+ outputs = model.generate(
418
+ **inputs,
419
+ max_length=len(inputs.input_ids[0]) + 300,
420
+ temperature=0.8,
421
+ top_p=0.9,
422
+ do_sample=True,
423
+ repetition_penalty=1.1,
424
+ pad_token_id=tokenizer.eos_token_id,
425
+ eos_token_id=tokenizer.eos_token_id,
426
+ )
427
+
428
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
429
+ generated_text = response[len(formatted_prompt):].strip()
430
+
431
+ if generated_text.startswith('"') and generated_text.endswith('"'):
432
+ generated_text = generated_text[1:-1]
433
+
434
+ return generated_text
435
+
436
+ except Exception as e:
437
+ return f"⚠️ Error generating response: {str(e)}"
438
+
439
+ def modify_habit(message: str) -> str:
440
+ """
441
+ Habit modification system - builds new habits or breaks old ones.
442
+ """
443
+
444
+ if model is None:
445
+ return "⚠️ Psychology model is loading. Please try again in a moment."
446
+
447
+ formatted_prompt = f"""Someone wants to change a habit and said: "{message}"
448
+
449
+ You're a habit modification system. Use their exact words and energy.
450
+
451
+ Engineer their habit change:
452
+ - Identify the current habit loop (cue, routine, reward)
453
+ - Design replacement routine that gives same reward
454
+ - Make it stupidly easy to start (2-minute rule)
455
+ - Build in accountability and tracking system
456
+ - Predict failure points and create recovery protocols
457
+
458
+ "Current loop: [cue] → [routine] → [reward]. New loop: [same cue] → [new routine] → [same reward]. Start with this tiny version: [2-minute version]. Track using [method]. When you screw up (you will), do this: [recovery plan]."
459
+
460
+ Sound like someone who knows habits are engineering, not willpower:"""
461
+
462
+ try:
463
+ inputs = tokenizer(
464
+ formatted_prompt,
465
+ return_tensors="pt",
466
+ truncation=True,
467
+ max_length=512
468
+ ).to(device)
469
+
470
+ with torch.no_grad():
471
+ outputs = model.generate(
472
+ **inputs,
473
+ max_length=len(inputs.input_ids[0]) + 300,
474
+ temperature=0.8,
475
+ top_p=0.9,
476
+ do_sample=True,
477
+ repetition_penalty=1.1,
478
+ pad_token_id=tokenizer.eos_token_id,
479
+ eos_token_id=tokenizer.eos_token_id,
480
+ )
481
+
482
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
483
+ generated_text = response[len(formatted_prompt):].strip()
484
+
485
+ if generated_text.startswith('"') and generated_text.endswith('"'):
486
+ generated_text = generated_text[1:-1]
487
+
488
+ return generated_text
489
+
490
+ except Exception as e:
491
+ return f"⚠️ Error generating response: {str(e)}"
492
+
493
+ def process_feedback(message: str) -> str:
494
+ """
495
+ Feedback processing system - filters valid criticism from noise.
496
+ """
497
+
498
+ if model is None:
499
+ return "⚠️ Psychology model is loading. Please try again in a moment."
500
+
501
+ formatted_prompt = f"""Someone received feedback and said: "{message}"
502
+
503
+ You're a feedback processing system. Use their words and energy.
504
+
505
+ Process their feedback systematically:
506
+ - Separate the valid information from the emotional delivery
507
+ - Assess the source's credibility and motivation
508
+ - Identify what's actionable vs what's projection/opinion
509
+ - Give them specific steps to implement valid feedback
510
+ - Help them dismiss invalid criticism without guilt
511
+
512
+ "Valid feedback: [specific items]. Source credibility: [assessment]. Actionable items: [specific steps]. Ignore this part: [invalid elements] because [reason]. Your response should be: [specific response]."
513
+
514
+ Sound like someone who knows feedback is data, not judgment:"""
515
+
516
+ try:
517
+ inputs = tokenizer(
518
+ formatted_prompt,
519
+ return_tensors="pt",
520
+ truncation=True,
521
+ max_length=512
522
+ ).to(device)
523
+
524
+ with torch.no_grad():
525
+ outputs = model.generate(
526
+ **inputs,
527
+ max_length=len(inputs.input_ids[0]) + 300,
528
+ temperature=0.8,
529
+ top_p=0.9,
530
+ do_sample=True,
531
+ repetition_penalty=1.1,
532
+ pad_token_id=tokenizer.eos_token_id,
533
+ eos_token_id=tokenizer.eos_token_id,
534
+ )
535
+
536
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
537
+ generated_text = response[len(formatted_prompt):].strip()
538
+
539
+ if generated_text.startswith('"') and generated_text.endswith('"'):
540
+ generated_text = generated_text[1:-1]
541
+
542
+ return generated_text
543
+
544
+ except Exception as e:
545
+ return f"⚠️ Error generating response: {str(e)}"
546
+
547
+ def psychological_sentiment_analysis(message: str) -> str:
548
+ """
549
+ Advanced psychological sentiment analysis - beyond positive/negative.
550
+ """
551
+
552
+ if model is None:
553
+ return "⚠️ Psychology model is loading. Please try again in a moment."
554
+
555
+ formatted_prompt = f"""Someone said: "{message}"
556
+
557
+ You're a psychological sentiment analyzer. Extract precise emotional and mental state markers.
558
+
559
+ Analyze psychological sentiment systematically:
560
+ - Primary emotional state (specific emotion, not just "sad" - grief, disappointment, overwhelm, etc.)
561
+ - Stress level (1-10 scale with indicators)
562
+ - Cognitive state (clear thinking, ruminating, dissociating, hyperfocused)
563
+ - Energy level (depleted, normal, manic, scattered)
564
+ - Social connection (isolated, supported, conflicted, avoidant)
565
+ - Self-worth markers (confident, insecure, grandiose, worthless)
566
+ - Coping capacity (resilient, struggling, crisis mode, overwhelmed)
567
+
568
+ Output format: "Sentiment Analysis: [Primary emotion], Stress: [level/10], Cognitive: [state], Energy: [level], Social: [connection], Self-worth: [markers], Coping: [capacity]"
569
+
570
+ Be precise and clinical in your assessment:"""
571
+
572
+ try:
573
+ inputs = tokenizer(
574
+ formatted_prompt,
575
+ return_tensors="pt",
576
+ truncation=True,
577
+ max_length=512
578
+ ).to(device)
579
+
580
+ with torch.no_grad():
581
+ outputs = model.generate(
582
+ **inputs,
583
+ max_length=len(inputs.input_ids[0]) + 300,
584
+ temperature=0.8,
585
+ top_p=0.9,
586
+ do_sample=True,
587
+ repetition_penalty=1.1,
588
+ pad_token_id=tokenizer.eos_token_id,
589
+ eos_token_id=tokenizer.eos_token_id,
590
+ )
591
+
592
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
593
+ generated_text = response[len(formatted_prompt):].strip()
594
+
595
+ if generated_text.startswith('"') and generated_text.endswith('"'):
596
+ generated_text = generated_text[1:-1]
597
+
598
+ return generated_text
599
+
600
+ except Exception as e:
601
+ return f"⚠️ Error generating response: {str(e)}"
602
+
603
+ def psychological_concept_tagger(message: str) -> str:
604
+ """
605
+ Tag psychological frameworks and concepts present in the message.
606
+ """
607
+
608
+ if model is None:
609
+ return "⚠️ Psychology model is loading. Please try again in a moment."
610
+
611
+ formatted_prompt = f"""Someone said: "{message}"
612
+
613
+ You're a psychological concept identification system. Tag all relevant psychological frameworks at play.
614
+
615
+ Identify active psychological concepts:
616
+ - Personality patterns (Big Five traits, attachment styles, cognitive styles)
617
+ - Defense mechanisms (projection, denial, rationalization, splitting, etc.)
618
+ - Cognitive biases (catastrophizing, all-or-nothing, confirmation bias, etc.)
619
+ - Relationship dynamics (codependency, triangulation, power struggles, etc.)
620
+ - Developmental issues (trauma responses, family-of-origin patterns, etc.)
621
+ - Mental health indicators (depression markers, anxiety patterns, PTSD symptoms, etc.)
622
+ - Coping mechanisms (healthy vs unhealthy, adaptive vs maladaptive)
623
+
624
+ Output format: "Concepts: [Personality: X], [Defense: Y], [Cognitive: Z], [Relationship: A], [Developmental: B], [Mental Health: C], [Coping: D]"
625
+
626
+ Be comprehensive and precise - tag everything you detect:"""
627
+
628
+ try:
629
+ inputs = tokenizer(
630
+ formatted_prompt,
631
+ return_tensors="pt",
632
+ truncation=True,
633
+ max_length=512
634
+ ).to(device)
635
+
636
+ with torch.no_grad():
637
+ outputs = model.generate(
638
+ **inputs,
639
+ max_length=len(inputs.input_ids[0]) + 300,
640
+ temperature=0.8,
641
+ top_p=0.9,
642
+ do_sample=True,
643
+ repetition_penalty=1.1,
644
+ pad_token_id=tokenizer.eos_token_id,
645
+ eos_token_id=tokenizer.eos_token_id,
646
+ )
647
+
648
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
649
+ generated_text = response[len(formatted_prompt):].strip()
650
+
651
+ if generated_text.startswith('"') and generated_text.endswith('"'):
652
+ generated_text = generated_text[1:-1]
653
+
654
+ return generated_text
655
+
656
+ except Exception as e:
657
+ return f"⚠️ Error generating response: {str(e)}"
658
+
659
  # Apply GPU optimization if available
660
  if HAS_SPACES:
661
  psychology_support = spaces.GPU(psychology_support)
662
  trauma_support = spaces.GPU(trauma_support)
663
  panic_support = spaces.GPU(panic_support)
664
+ personality_decision_support = spaces.GPU(personality_decision_support)
665
+ values_based_choice = spaces.GPU(values_based_choice)
666
+ process_emotion = spaces.GPU(process_emotion)
667
+ set_boundary = spaces.GPU(set_boundary)
668
+ handle_conflict = spaces.GPU(handle_conflict)
669
+ modify_habit = spaces.GPU(modify_habit)
670
+ process_feedback = spaces.GPU(process_feedback)
671
+ psychological_sentiment_analysis = spaces.GPU(psychological_sentiment_analysis)
672
+ psychological_concept_tagger = spaces.GPU(psychological_concept_tagger)
673
 
674
  # Initialize model
675
  print("🚀 Starting Psychology Personal Agent...")