File size: 30,891 Bytes
d6e219c
f1948f2
 
e46fbeb
a0d733c
 
1ef0cee
 
 
 
f81397d
 
be511bb
 
 
 
 
0a6e7ae
f81397d
 
 
 
 
 
1ef0cee
0a6e7ae
e46fbeb
0a6e7ae
 
 
 
 
 
 
5888ec6
 
 
 
 
 
e46fbeb
 
5888ec6
0a6e7ae
d270769
 
e46fbeb
5888ec6
 
0a6e7ae
e46fbeb
 
 
 
 
 
 
 
 
d80ec7b
0a6e7ae
 
6cdcb5b
 
e1ba4f8
6cdcb5b
 
e46fbeb
0a6e7ae
cfdfbb0
 
0a6e7ae
 
184eae8
44ac58a
0db7070
 
 
ba18699
0db7070
d334e9c
0db7070
 
 
 
0a6e7ae
cfdfbb0
0a6e7ae
cfdfbb0
 
 
 
 
 
 
 
5ee6178
cfdfbb0
 
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb0821c
 
 
 
 
 
 
 
 
 
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b88ad9d
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d855c4
b5bf202
4d855c4
 
 
4eeeb7e
4d855c4
 
b5bf202
4d855c4
 
 
4eeeb7e
4d855c4
e9dc9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c24baa
 
 
 
6a4d82f
4c24baa
 
 
 
 
 
 
 
adff1b6
4c24baa
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb2ad0
8169a27
6e056de
 
 
c5ab02a
 
6e056de
 
c5ab02a
 
 
 
 
6e056de
0a6e7ae
 
6e056de
0a6e7ae
 
c5ab02a
0a6e7ae
 
c5ab02a
8169a27
 
0a6e7ae
8169a27
 
0a6e7ae
 
 
 
 
c5ab02a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6e7ae
 
 
 
 
 
0db7070
 
0a6e7ae
0db7070
0a6e7ae
b405143
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ee6178
 
0a6e7ae
 
 
 
 
 
 
 
 
 
 
e46fbeb
 
0a6e7ae
 
44220fe
977855e
cdb869a
d56f3b3
c127ba6
 
 
 
 
d56f3b3
cdb869a
d56f3b3
 
8cbdd57
90d7e35
cdb869a
 
44220fe
0a6e7ae
 
e46fbeb
 
 
96f5bc2
a0d733c
0a6e7ae
 
 
 
d4713b6
0a6e7ae
d374438
0a6e7ae
 
 
 
 
 
 
 
 
d80ec7b
0a6e7ae
d56f3b3
0a6e7ae
 
 
d374438
 
 
 
 
0a6e7ae
 
 
 
 
 
 
 
 
 
d56f3b3
0a6e7ae
 
 
 
 
 
d56f3b3
 
 
 
0a6e7ae
d56f3b3
509e003
0a6e7ae
d56f3b3
 
0a6e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b7d696
e46fbeb
 
 
 
 
 
 
 
b40c9cf
a0d733c
68c555d
cb8a766
e46fbeb
 
 
2376828
 
b40c9cf
7c6950a
e46fbeb
135755d
 
 
 
 
 
8169a27
135755d
8169a27
7c6950a
7c5f796
 
 
 
8169a27
7c5f796
 
 
 
 
7c6950a
8169a27
7c6950a
68c555d
 
 
 
 
7c6950a
8169a27
 
 
 
7c6950a
 
 
 
f020cca
577f266
0b7d696
e46fbeb
967ce44
e848448
8169a27
4e77d52
967ce44
 
 
 
 
 
8169a27
 
 
b40c9cf
e46fbeb
 
 
 
 
 
 
b40c9cf
 
e46fbeb
 
8169a27
c4bd45f
 
 
8169a27
2376828
ae867ed
 
 
8169a27
b90535a
 
 
 
 
 
8169a27
b90535a
 
 
 
8169a27
e46fbeb
b40c9cf
49de108
 
 
 
f76b87b
0a6e7ae
e46fbeb
0a6e7ae
e46fbeb
0a6e7ae
2376828
e46fbeb
 
 
 
2376828
 
e46fbeb
 
2376828
96f5bc2
2376828
 
e46fbeb
 
 
d457a0a
e46fbeb
 
2376828
 
96f5bc2
2376828
6f5f8ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import gradio as gr
import torch
import numpy as np
from transformers import pipeline, RobertaForSequenceClassification, RobertaTokenizer
from motif_tagging import detect_motifs
import re
import matplotlib.pyplot as plt
import io
from PIL import Image
from datetime import datetime
from transformers import pipeline as hf_pipeline  # prevent name collision with gradio pipeline

def get_emotion_profile(text):
    emotions = emotion_pipeline(text)
    if isinstance(emotions, list) and isinstance(emotions[0], list):
        emotions = emotions[0]
    return {e['label'].lower(): round(e['score'], 3) for e in emotions}
# Emotion model (no retraining needed)
emotion_pipeline = hf_pipeline(
    "text-classification",
    model="j-hartmann/emotion-english-distilroberta-base",
    top_k=None,
    truncation=True
)

# --- Timeline Visualization Function ---
def generate_abuse_score_chart(dates, scores, labels):
    import matplotlib.pyplot as plt
    import io
    from PIL import Image
    from datetime import datetime
    import re

    # Determine if all entries are valid dates
    if all(re.match(r"\d{4}-\d{2}-\d{2}", d) for d in dates):
        parsed_x = [datetime.strptime(d, "%Y-%m-%d") for d in dates]
        x_labels = [d.strftime("%Y-%m-%d") for d in parsed_x]
    else:
        parsed_x = list(range(1, len(dates) + 1))
        x_labels = [f"Message {i+1}" for i in range(len(dates))]

    fig, ax = plt.subplots(figsize=(8, 3))
    ax.plot(parsed_x, scores, marker='o', linestyle='-', color='darkred', linewidth=2)

    for x, y in zip(parsed_x, scores):
        ax.text(x, y + 2, f"{int(y)}%", ha='center', fontsize=8, color='black')

    ax.set_xticks(parsed_x)
    ax.set_xticklabels(x_labels)
    ax.set_xlabel("")  # No axis label
    ax.set_ylabel("Abuse Score (%)")
    ax.set_ylim(0, 105)
    ax.grid(True)
    plt.tight_layout()

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    return Image.open(buf)


# --- Abuse Model ---
from transformers import AutoModelForSequenceClassification, AutoTokenizer

model_name = "SamanthaStorm/tether-multilabel-v3"
model      = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer  = AutoTokenizer.from_pretrained(model_name, use_fast=False)

LABELS = [
    "recovery", "control", "gaslighting", "dismissiveness", "blame shifting",
    "coercion", "aggression", "nonabusive", "deflection", "projection", "insults"
]

THRESHOLDS = {
    "recovery": 0.999,
    "control": 0.100,
    "gaslighting": 0.410,
    "dismissiveness": 0.867,
    "blame shifting": 0.116,
    "coercion": 0.100,
    "aggression": 0.02,
    "nonabusive": 0.100,
    "deflection": 0.100,
    "projection": 0.100,
    "insults": 0.100
}

PATTERN_WEIGHTS = {
    "gaslighting": 1.5,
    "control": 1.2,
    "dismissiveness": 0.7,
    "blame shifting": 0.5,
    "insults": 1.4,
    "projection": 1.2,
    "recovery": 1.1,
    "coercion": 1.3,
    "aggression": 2.2,
    "nonabusive": 0.1,
    "deflection": 0.4
}
RISK_STAGE_LABELS = {
    1: "🌀 Risk Stage: Tension-Building\nThis message reflects rising emotional pressure or subtle control attempts.",
    2: "🔥 Risk Stage: Escalation\nThis message includes direct or aggressive patterns, suggesting active harm.",
    3: "🌧️ Risk Stage: Reconciliation\nThis message reflects a reset attempt—apologies or emotional repair without accountability.",
    4: "🌸 Risk Stage: Calm / Honeymoon\nThis message appears supportive but may follow prior harm, minimizing it."
}

ESCALATION_QUESTIONS = [
    ("Partner has access to firearms or weapons", 4),
    ("Partner threatened to kill you", 3),
    ("Partner threatened you with a weapon", 3),
    ("Partner has ever choked you, even if you considered it consensual at the time", 4),
    ("Partner injured or threatened your pet(s)", 3),
    ("Partner has broken your things, punched or kicked walls, or thrown things ", 2),
    ("Partner forced or coerced you into unwanted sexual acts", 3),
    ("Partner threatened to take away your children", 2),
    ("Violence has increased in frequency or severity", 3),
    ("Partner monitors your calls/GPS/social media", 2)
]
DARVO_PATTERNS = [
    "blame shifting",         # "You're the reason this happens"
    "projection",             # "You're the abusive one"
    "deflection",             # "This isn't about that"
    "dismissiveness",         # "You're overreacting"
    "insults",                # Personal attacks that redirect attention
    "aggression",             # Escalates tone to destabilize
    "recovery phase",         # Sudden affection following aggression
    "contradictory statements" # “I never said that” immediately followed by a version of what they said
]
DARVO_MOTIFS = [
    "I never said that.", "You’re imagining things.", "That never happened.",
    "You’re making a big deal out of nothing.", "It was just a joke.", "You’re too sensitive.",
    "I don’t know what you’re talking about.", "You’re overreacting.", "I didn’t mean it that way.",
    "You’re twisting my words.", "You’re remembering it wrong.", "You’re always looking for something to complain about.",
    "You’re just trying to start a fight.", "I was only trying to help.", "You’re making things up.",
    "You’re blowing this out of proportion.", "You’re being paranoid.", "You’re too emotional.",
    "You’re always so dramatic.", "You’re just trying to make me look bad.",

    "You’re crazy.", "You’re the one with the problem.", "You’re always so negative.",
    "You’re just trying to control me.", "You’re the abusive one.", "You’re trying to ruin my life.",
    "You’re just jealous.", "You’re the one who needs help.", "You’re always playing the victim.",
    "You’re the one causing all the problems.", "You’re just trying to make me feel guilty.",
    "You’re the one who can’t let go of the past.", "You’re the one who’s always angry.",
    "You’re the one who’s always complaining.", "You’re the one who’s always starting arguments.",
    "You’re the one who’s always making things worse.", "You’re the one who’s always making me feel bad.",
    "You’re the one who’s always making me look like the bad guy.",
    "You’re the one who’s always making me feel like a failure.",
    "You’re the one who’s always making me feel like I’m not good enough.",

    "I can’t believe you’re doing this to me.", "You’re hurting me.",
    "You’re making me feel like a terrible person.", "You’re always blaming me for everything.",
    "You’re the one who’s abusive.", "You’re the one who’s controlling.", "You’re the one who’s manipulative.",
    "You’re the one who’s toxic.", "You’re the one who’s gaslighting me.",
    "You’re the one who’s always putting me down.", "You’re the one who’s always making me feel bad.",
    "You’re the one who’s always making me feel like I’m not good enough.",
    "You’re the one who’s always making me feel like I’m the problem.",
    "You’re the one who’s always making me feel like I’m the bad guy.",
    "You’re the one who’s always making me feel like I’m the villain.",
    "You’re the one who’s always making me feel like I’m the one who needs to change.",
    "You’re the one who’s always making me feel like I’m the one who’s wrong.",
    "You’re the one who’s always making me feel like I’m the one who’s crazy.",
    "You’re the one who’s always making me feel like I’m the one who’s abusive.",
    "You’re the one who’s always making me feel like I’m the one who’s toxic."
]
def get_emotional_tone_tag(emotions, sentiment, patterns, abuse_score):
    sadness = emotions.get("sadness", 0)
    joy = emotions.get("joy", 0)
    neutral = emotions.get("neutral", 0)
    disgust = emotions.get("disgust", 0)
    anger = emotions.get("anger", 0)
    fear = emotions.get("fear", 0)
    disgust = emotions.get("disgust", 0)

    # 1. Performative Regret
    if (
        sadness > 0.4 and
        any(p in patterns for p in ["blame shifting", "guilt tripping", "recovery phase"]) and
        (sentiment == "undermining" or abuse_score > 40)
    ):
        return "performative regret"

    # 2. Coercive Warmth
    if (
        (joy > 0.3 or sadness > 0.4) and
        any(p in patterns for p in ["control", "gaslighting"]) and
        sentiment == "undermining"
    ):
        return "coercive warmth"

    # 3. Cold Invalidation
    if (
        (neutral + disgust) > 0.5 and
        any(p in patterns for p in ["dismissiveness", "projection", "obscure language"]) and
        sentiment == "undermining"
    ):
        return "cold invalidation"

    # 4. Genuine Vulnerability
    if (
        (sadness + fear) > 0.5 and
        sentiment == "supportive" and
        all(p in ["recovery phase"] for p in patterns)
    ):
        return "genuine vulnerability"

    # 5. Emotional Threat
    if (
        (anger + disgust) > 0.5 and
        any(p in patterns for p in ["control", "threat", "insults", "dismissiveness"]) and
        sentiment == "undermining"
    ):
        return "emotional threat"

    # 6. Weaponized Sadness
    if (
        sadness > 0.6 and
        any(p in patterns for p in ["guilt tripping", "projection"]) and
        sentiment == "undermining"
    ):
        return "weaponized sadness"

    # 7. Toxic Resignation
    if (
        neutral > 0.5 and
        any(p in patterns for p in ["dismissiveness", "obscure language"]) and
        sentiment == "undermining"
    ):
        return "toxic resignation"
    # 8. Aggressive Dismissal
    if (
        anger > 0.5 and
        any(p in patterns for p in ["aggression", "insults", "control"]) and
        sentiment == "undermining"
    ):
        return "aggressive dismissal"
    # 9. Deflective Hostility
    if (
        (0.2 < anger < 0.7 or 0.2 < disgust < 0.7) and
        any(p in patterns for p in ["deflection", "projection"]) and
        sentiment == "undermining"
    ):
        return "deflective hostility"   
    # 10. Mocking Detachment
    if (
        (neutral + joy) > 0.5 and
        any(p in patterns for p in ["mockery", "insults", "projection"]) and
        sentiment == "undermining"
    ):
        return "mocking detachment"
        # 11. Contradictory Gaslight
    if (
        (joy + anger + sadness) > 0.5 and
        any(p in patterns for p in ["gaslighting", "contradictory statements"]) and
        sentiment == "undermining"
    ):
        return "contradictory gaslight"
        # 12. Calculated Neutrality
    if (
        neutral > 0.6 and
        any(p in patterns for p in ["obscure language", "deflection", "dismissiveness"]) and
        sentiment == "undermining"
    ):
        return "calculated neutrality"
     # 13. Forced Accountability Flip
    if (
        (anger + disgust) > 0.5 and
        any(p in patterns for p in ["blame shifting", "manipulation", "projection"]) and
        sentiment == "undermining"
    ):
        return "forced accountability flip"
        # 14. Conditional Affection
    if (
        joy > 0.4 and
        any(p in patterns for p in ["apology baiting", "control", "recovery phase"]) and
        sentiment == "undermining"
    ):
        return "conditional affection"
    
    if (
        (anger + disgust) > 0.5 and
        any(p in patterns for p in ["blame shifting", "projection", "deflection"]) and
        sentiment == "undermining"
    ):
        return "forced accountability flip"

    # Emotional Instability Fallback
    if (
        (anger + sadness + disgust) > 0.6 and
        sentiment == "undermining"
    ):
        return "emotional instability"
        
    return None
def detect_contradiction(message):
    patterns = [
        (r"\b(i love you).{0,15}(i hate you|you ruin everything)", re.IGNORECASE),
        (r"\b(i’m sorry).{0,15}(but you|if you hadn’t)", re.IGNORECASE),
        (r"\b(i’m trying).{0,15}(you never|why do you)", re.IGNORECASE),
        (r"\b(do what you want).{0,15}(you’ll regret it|i always give everything)", re.IGNORECASE),
        (r"\b(i don’t care).{0,15}(you never think of me)", re.IGNORECASE),
        (r"\b(i guess i’m just).{0,15}(the bad guy|worthless|never enough)", re.IGNORECASE)
    ]
    return any(re.search(p, message, flags) for p, flags in patterns)
    
def calculate_darvo_score(patterns, sentiment_before, sentiment_after, motifs_found, contradiction_flag=False):
    # Count all detected DARVO-related patterns
    pattern_hits = sum(1 for p in patterns if p.lower() in DARVO_PATTERNS)

    # Sentiment delta
    sentiment_shift_score = max(0.0, sentiment_after - sentiment_before)

    # Match against DARVO motifs more loosely
    motif_hits = sum(
        any(phrase.lower() in motif.lower() or motif.lower() in phrase.lower()
            for phrase in DARVO_MOTIFS)
        for motif in motifs_found
    )
    motif_score = motif_hits / max(len(DARVO_MOTIFS), 1)

    # Contradiction still binary
    contradiction_score = 1.0 if contradiction_flag else 0.0

    # Final DARVO score
    return round(min(
        0.3 * pattern_hits +
        0.3 * sentiment_shift_score +
        0.25 * motif_score +
        0.15 * contradiction_score, 1.0
    ), 3)
def detect_weapon_language(text):
    weapon_keywords = [
        "knife", "knives", "stab", "cut you", "cutting",
        "gun", "shoot", "rifle", "firearm", "pistol",
        "bomb", "blow up", "grenade", "explode",
        "weapon", "armed", "loaded", "kill you", "take you out"
    ]
    text_lower = text.lower()
    return any(word in text_lower for word in weapon_keywords)
def get_risk_stage(patterns, sentiment):
    if "threat" in patterns or "insults" in patterns:
        return 2
    elif "recovery phase" in patterns:
        return 3
    elif "control" in patterns or "guilt tripping" in patterns:
        return 1
    elif sentiment == "supportive" and any(p in patterns for p in ["projection", "dismissiveness"]):
        return 4
    return 1

def generate_risk_snippet(abuse_score, top_label, escalation_score, stage):
    import re

    # Extract aggression score if aggression is detected
    if isinstance(top_label, str) and "aggression" in top_label.lower():
        try:
            match = re.search(r"\(?(\d+)\%?\)?", top_label)
            aggression_score = int(match.group(1)) / 100 if match else 0
        except:
            aggression_score = 0
    else:
        aggression_score = 0

    # Revised risk logic
    if abuse_score >= 85 or escalation_score >= 16:
        risk_level = "high"
    elif abuse_score >= 60 or escalation_score >= 8 or aggression_score >= 0.25:
        risk_level = "moderate"
    elif stage == 2 and abuse_score >= 40:
        risk_level = "moderate"
    else:
        risk_level = "low"

    if isinstance(top_label, str) and " – " in top_label:
        pattern_label, pattern_score = top_label.split(" – ")
    else:
        pattern_label = str(top_label) if top_label is not None else "Unknown"
        pattern_score = ""

    WHY_FLAGGED = {
        "control": "This message may reflect efforts to restrict someone’s autonomy, even if it's framed as concern or care.",
        "gaslighting": "This message could be manipulating someone into questioning their perception or feelings.",
        "dismissiveness": "This message may include belittling, invalidating, or ignoring the other person’s experience.",
        "insults": "Direct insults often appear in escalating abusive dynamics and can erode emotional safety.",
        "threat": "This message includes threatening language, which is a strong predictor of harm.",
        "blame shifting": "This message may redirect responsibility to avoid accountability, especially during conflict.",
        "guilt tripping": "This message may induce guilt in order to control or manipulate behavior.",
        "recovery phase": "This message may be part of a tension-reset cycle, appearing kind but avoiding change.",
        "projection": "This message may involve attributing the abuser’s own behaviors to the victim.",
        "contradictory statements": "This message may contain internal contradictions used to confuse, destabilize, or deflect responsibility.",
        "obscure language": "This message may use overly formal, vague, or complex language to obscure meaning or avoid accountability.",
        "default": "This message contains language patterns that may affect safety, clarity, or emotional autonomy."
    }

    explanation = WHY_FLAGGED.get(pattern_label.lower(), WHY_FLAGGED["default"])

    base = f"\n\n🛑 Risk Level: {risk_level.capitalize()}\n"
    base += f"This message shows strong indicators of **{pattern_label}**. "

    if risk_level == "high":
        base += "The language may reflect patterns of emotional control, even when expressed in soft or caring terms.\n"
    elif risk_level == "moderate":
        base += "There are signs of emotional pressure or verbal aggression that may escalate if repeated.\n"
    else:
        base += "The message does not strongly indicate abuse, but it's important to monitor for patterns.\n"

    base += f"\n💡 *Why this might be flagged:*\n{explanation}\n"
    base += f"\nDetected Pattern: **{pattern_label} ({pattern_score})**\n"
    base += "🧠 You can review the pattern in context. This tool highlights possible dynamics—not judgments."
    return base

    WHY_FLAGGED = {
        "control": "This message may reflect efforts to restrict someone’s autonomy, even if it's framed as concern or care.",
        "gaslighting": "This message could be manipulating someone into questioning their perception or feelings.",
        "dismissiveness": "This message may include belittling, invalidating, or ignoring the other person’s experience.",
        "insults": "Direct insults often appear in escalating abusive dynamics and can erode emotional safety.",
        "threat": "This message includes threatening language, which is a strong predictor of harm.",
        "blame shifting": "This message may redirect responsibility to avoid accountability, especially during conflict.",
        "guilt tripping": "This message may induce guilt in order to control or manipulate behavior.",
        "recovery phase": "This message may be part of a tension-reset cycle, appearing kind but avoiding change.",
        "projection": "This message may involve attributing the abuser’s own behaviors to the victim.",
        "contradictory statements": "This message may contain internal contradictions used to confuse, destabilize, or deflect responsibility.",
        "obscure language": "This message may use overly formal, vague, or complex language to obscure meaning or avoid accountability.",
        "default": "This message contains language patterns that may affect safety, clarity, or emotional autonomy."
}
    explanation = WHY_FLAGGED.get(pattern_label.lower(), WHY_FLAGGED["default"])

    base = f"\n\n🛑 Risk Level: {risk_level.capitalize()}\n"
    base += f"This message shows strong indicators of **{pattern_label}**. "

    if risk_level == "high":
        base += "The language may reflect patterns of emotional control, even when expressed in soft or caring terms.\n"
    elif risk_level == "moderate":
        base += "There are signs of emotional pressure or indirect control that may escalate if repeated.\n"
    else:
        base += "The message does not strongly indicate abuse, but it's important to monitor for patterns.\n"
    
    base += f"\n💡 *Why this might be flagged:*\n{explanation}\n"
    base += f"\nDetected Pattern: **{pattern_label} ({pattern_score})**\n"
    base += "🧠 You can review the pattern in context. This tool highlights possible dynamics—not judgments."
    return base
def compute_abuse_score(matched_scores, sentiment):
    if not matched_scores:
        return 0

    # Weighted average of passed patterns
    weighted_total = sum(score * weight for _, score, weight in matched_scores)
    weight_sum = sum(weight for _, _, weight in matched_scores)
    base_score = (weighted_total / weight_sum) * 100

    # Boost for pattern count
    pattern_count = len(matched_scores)
    scale = 1.0 + 0.25 * max(0, pattern_count - 1)  # 1.25x for 2, 1.5x for 3+
    scaled_score = base_score * scale

    # Pattern floors
    FLOORS = {
        "threat": 70,
        "control": 40,
        "gaslighting": 30,
        "insults": 25,
        "aggression": 40
    }
    floor = max(FLOORS.get(label, 0) for label, _, _ in matched_scores)
    adjusted_score = max(scaled_score, floor)

    # Sentiment tweak
    if sentiment == "undermining" and adjusted_score < 50:
        adjusted_score += 10

    return min(adjusted_score, 100)
    
    
def analyze_single_message(text, thresholds):
    motif_hits, matched_phrases = detect_motifs(text)

    # Get emotion profile
    emotion_profile = get_emotion_profile(text)
    sentiment_score = emotion_profile.get("anger", 0) + emotion_profile.get("disgust", 0)

    # Get model scores
    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    with torch.no_grad():
        outputs = model(**inputs)
    scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()

    # Sentiment override if neutral is high while critical thresholds are passed
    if emotion_profile.get("neutral", 0) > 0.85 and any(
        scores[LABELS.index(l)] > thresholds[l]
        for l in ["control", "threat", "blame shifting"]
    ):
        sentiment = "undermining"
    else:
        sentiment = "undermining" if sentiment_score > 0.25 else "supportive"

    weapon_flag = detect_weapon_language(text)

    adjusted_thresholds = {
        k: v + 0.05 if sentiment == "supportive" else v
        for k, v in thresholds.items()
    }

    contradiction_flag = detect_contradiction(text)

    threshold_labels = [
        label for label, score in zip(LABELS, scores)
        if score > adjusted_thresholds[label]
    ]
    tone_tag = get_emotional_tone_tag(emotion_profile, sentiment, threshold_labels, 0)
    motifs = [phrase for _, phrase in matched_phrases]

    darvo_score = calculate_darvo_score(
        threshold_labels,
        sentiment_before=0.0,
        sentiment_after=sentiment_score,
        motifs_found=motifs,
        contradiction_flag=contradiction_flag
    )

    top_patterns = sorted(
        [(label, score) for label, score in zip(LABELS, scores)],
        key=lambda x: x[1],
        reverse=True
    )[:2]
    # Post-threshold validation: strip recovery if it occurs with undermining sentiment
    if "recovery" in threshold_labels and tone_tag == "forced accountability flip":
        threshold_labels.remove("recovery")
        top_patterns = [p for p in top_patterns if p[0] != "recovery"]
        print("⚠️ Removing 'recovery' due to undermining sentiment (not genuine repair)")

    matched_scores = [
        (label, score, PATTERN_WEIGHTS.get(label, 1.0))
        for label, score in zip(LABELS, scores)
        if score > adjusted_thresholds[label]
    ]

    abuse_score_raw = compute_abuse_score(matched_scores, sentiment)
    abuse_score = abuse_score_raw

    # Risk stage logic
    stage = get_risk_stage(threshold_labels, sentiment) if threshold_labels else 1
    if weapon_flag and stage < 2:
        stage = 2
    if weapon_flag:
        abuse_score_raw = min(abuse_score_raw + 25, 100)

    abuse_score = min(
        abuse_score_raw,
        100 if "threat" in threshold_labels or "control" in threshold_labels else 95
    )

    # Tone tag must happen after abuse_score is finalized
    tone_tag = get_emotional_tone_tag(emotion_profile, sentiment, threshold_labels, abuse_score)

    # Debug
    print(f"Emotional Tone Tag: {tone_tag}")
    print("Emotion Profile:")
    for emotion, score in emotion_profile.items():
        print(f"  {emotion.capitalize():10}: {score}")
    print("\n--- Debug Info ---")
    print(f"Text: {text}")
    print(f"Sentiment (via emotion): {sentiment} (score: {round(sentiment_score, 3)})")
    print("Abuse Pattern Scores:")
    for label, score in zip(LABELS, scores):
        passed = "✅" if score > adjusted_thresholds[label] else "❌"
        print(f"  {label:25}{score:.3f} {passed}")
    print(f"Matched for score: {[(l, round(s, 3)) for l, s, _ in matched_scores]}")
    print(f"Abuse Score Raw: {round(abuse_score_raw, 1)}")
    print(f"Motifs: {motifs}")
    print(f"Contradiction: {contradiction_flag}")
    print("------------------\n")

    return abuse_score, threshold_labels, top_patterns, {"label": sentiment}, stage, darvo_score, tone_tag

def analyze_composite(msg1, date1, msg2, date2, msg3, date3, *answers_and_none):
    none_selected_checked = answers_and_none[-1]
    responses_checked = any(answers_and_none[:-1])
    none_selected = not responses_checked and none_selected_checked

    if none_selected:
        escalation_score = None
        risk_level = "unknown"
    else:
        escalation_score = sum(w for (_, w), a in zip(ESCALATION_QUESTIONS, answers_and_none[:-1]) if a)

    messages = [msg1, msg2, msg3]
    dates = [date1, date2, date3]
    active = [(m, d) for m, d in zip(messages, dates) if m.strip()]
    if not active:
        return "Please enter at least one message."

    # Run model on messages
    results = [(analyze_single_message(m, THRESHOLDS.copy()), d) for m, d in active]
    abuse_scores = [r[0][0] for r in results]
    top_labels = [r[0][1][0] if r[0][1] else r[0][2][0][0] for r in results]
    top_scores = [r[0][2][0][1] for r in results]
    sentiments = [r[0][3]['label'] for r in results]
    stages = [r[0][4] for r in results]
    darvo_scores = [r[0][5] for r in results]
    tone_tags= [r[0][6] for r in results]
    dates_used = [r[1] or "Undated" for r in results]  # Store dates for future mapping
    # Calculate escalation bump *after* model results exist
    escalation_bump = 0
    for result, _ in results:
        abuse_score, threshold_labels, top_patterns, sentiment, stage, darvo_score, tone_tag = result
        if darvo_score > 0.65:
            escalation_bump += 3
        if tone_tag in ["forced accountability flip", "emotional threat"]:
            escalation_bump += 2
        if abuse_score > 80:
            escalation_bump += 2
        if stage == 2:
            escalation_bump += 3

    # Now we can safely calculate hybrid_score
    hybrid_score = escalation_score + escalation_bump if escalation_score is not None else 0
    risk_level = (
        "High" if hybrid_score >= 16 else
        "Moderate" if hybrid_score >= 8 else
        "Low"
    )

    # Now compute scores and allow override
    abuse_scores = [r[0][0] for r in results]
    stages = [r[0][4] for r in results]

    # Post-check override (e.g. stage 2 or high abuse score forces Moderate risk)
    if any(score > 70 for score in abuse_scores) or any(stage == 2 for stage in stages):
        if risk_level == "Low":
            risk_level = "Moderate"

    for result, date in results:
        assert len(result) == 7, "Unexpected output from analyze_single_message"

# --- Composite Abuse Score using compute_abuse_score ---
    composite_abuse_scores = []

    for result, _ in results:
        _, _, top_patterns, sentiment, _, _, _ = result
        matched_scores = [(label, score, PATTERN_WEIGHTS.get(label, 1.0)) for label, score in top_patterns]
        final_score = compute_abuse_score(matched_scores, sentiment["label"])
        composite_abuse_scores.append(final_score)

    composite_abuse = int(round(sum(composite_abuse_scores) / len(composite_abuse_scores)))



    most_common_stage = max(set(stages), key=stages.count)
    stage_text = RISK_STAGE_LABELS[most_common_stage]

    avg_darvo = round(sum(darvo_scores) / len(darvo_scores), 3)
    darvo_blurb = ""
    if avg_darvo > 0.25:
        level = "moderate" if avg_darvo < 0.65 else "high"
        darvo_blurb = f"\n\n🎭 **DARVO Score: {avg_darvo}** → This indicates a **{level} likelihood** of narrative reversal (DARVO), where the speaker may be denying, attacking, or reversing blame."

    out = f"Abuse Intensity: {composite_abuse}%\n"
    out += "📊 This reflects the strength and severity of detected abuse patterns in the message(s).\n\n"

# Save this line for later use at the 
    if escalation_score is None:
        escalation_text = "📉 Escalation Potential: Unknown (Checklist not completed)\n"
        escalation_text += "⚠️ *This section was not completed. Escalation potential is unknown.*\n"
        hybrid_score = 0  # ✅ fallback so it's defined for generate_risk_snippet
    else:
        escalation_text = f"🧨 **Escalation Potential: {risk_level} ({escalation_score}/{sum(w for _, w in ESCALATION_QUESTIONS)})**\n"
        escalation_text += "This score comes directly from the safety checklist and functions as a standalone escalation risk score.\n"
        escalation_text += "It indicates how many serious risk factors are present based on your answers to the safety checklist.\n"
        # Derive top_label from the strongest top_patterns across all messages
    top_label = None
    if results:
        sorted_patterns = sorted(
            [(label, score) for r in results for label, score in r[0][2]],
            key=lambda x: x[1],
            reverse=True
    )
        if sorted_patterns:
            top_label = f"{sorted_patterns[0][0]}{int(round(sorted_patterns[0][1] * 100))}%"
        if top_label is None:
            top_label = "Unknown – 0%"
    out += generate_risk_snippet(composite_abuse, top_label, hybrid_score if escalation_score is not None else 0, most_common_stage)
    out += f"\n\n{stage_text}"
    out += darvo_blurb
    out += "\n\n🎭 **Emotional Tones Detected:**\n"
    for i, tone in enumerate(tone_tags):
        label = tone if tone else "none"
        out += f"• Message {i+1}: *{label}*\n"
    print(f"DEBUG: avg_darvo = {avg_darvo}")
    pattern_labels = [r[0][2][0][0] for r in results]  # top label for each message
    timeline_image = generate_abuse_score_chart(dates_used, abuse_scores, pattern_labels)
    out += "\n\n" + escalation_text
    return out, timeline_image
    
message_date_pairs = [
    (
        gr.Textbox(label=f"Message {i+1}"),
        gr.Textbox(label=f"Date {i+1} (optional)", placeholder="YYYY-MM-DD")
    )
    for i in range(3)
]
textbox_inputs = [item for pair in message_date_pairs for item in pair]
quiz_boxes = [gr.Checkbox(label=q) for q, _ in ESCALATION_QUESTIONS]
none_box = gr.Checkbox(label="None of the above")

iface = gr.Interface(
    fn=analyze_composite,
    inputs=textbox_inputs + quiz_boxes + [none_box],
    outputs=[
        gr.Textbox(label="Results"),
        gr.Image(label="Abuse Score Timeline", type="pil")
    ],
    title="Abuse Pattern Detector + Escalation Quiz",
    allow_flagging="manual"
)

if __name__ == "__main__":
    iface.launch()