SamanthaStorm commited on
Commit
e185e86
·
verified ·
1 Parent(s): a6c0cf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -34
app.py CHANGED
@@ -1,23 +1,65 @@
1
  import gradio as gr
2
  import torch
3
  import numpy as np
4
- from transformers import AutoModelForSequenceClassification, AutoTokenizer, RobertaForSequenceClassification, RobertaTokenizer
 
5
  from motif_tagging import detect_motifs
 
6
 
7
- # Load models
8
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("SamanthaStorm/tether-sentiment")
9
  sentiment_tokenizer = AutoTokenizer.from_pretrained("SamanthaStorm/tether-sentiment")
 
 
10
  model_name = "SamanthaStorm/autotrain-c1un8-p8vzo"
11
  model = RobertaForSequenceClassification.from_pretrained(model_name, trust_remote_code=True)
12
  tokenizer = RobertaTokenizer.from_pretrained(model_name, trust_remote_code=True)
13
 
14
- LABELS = [...]
15
- THRESHOLDS = {...}
 
 
 
 
 
 
 
 
 
 
 
16
  PATTERN_LABELS = LABELS[:15]
17
  DANGER_LABELS = LABELS[15:18]
18
- EXPLANATIONS = {...}
19
- PATTERN_WEIGHTS = {...}
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def custom_sentiment(text):
23
  inputs = sentiment_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
@@ -30,7 +72,6 @@ def custom_sentiment(text):
30
  score = probs[0][label_idx].item()
31
  return {"label": label, "score": score}
32
 
33
-
34
  def calculate_abuse_level(scores, thresholds, motif_hits=None):
35
  weighted_scores = []
36
  for label, score in zip(LABELS, scores):
@@ -39,11 +80,10 @@ def calculate_abuse_level(scores, thresholds, motif_hits=None):
39
  weighted_scores.append(score * weight)
40
  base_score = round(np.mean(weighted_scores) * 100, 2) if weighted_scores else 0.0
41
  motif_hits = motif_hits or []
42
- if any(label in motif_hits for label in DANGER_LABELS):
43
  base_score = max(base_score, 75.0)
44
  return base_score
45
 
46
-
47
  def interpret_abuse_level(score):
48
  if score > 80:
49
  return "Extreme / High Risk"
@@ -55,50 +95,59 @@ def interpret_abuse_level(score):
55
  return "Mild Concern"
56
  return "Very Low / Likely Safe"
57
 
58
-
59
- def analyze_single_message(text):
60
- if not text.strip():
61
- return "No input provided."
62
- sentiment = custom_sentiment(text)
63
- thresholds = {k: v * 0.8 for k, v in THRESHOLDS.items()} if sentiment['label'] == "undermining" else THRESHOLDS.copy()
64
  motif_flags, matched_phrases = detect_motifs(text)
 
 
 
 
 
65
  inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
66
  with torch.no_grad():
67
  outputs = model(**inputs)
68
  scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()
69
- abuse_score = calculate_abuse_level(scores, thresholds, [label for label, _ in matched_phrases])
70
- summary = interpret_abuse_level(abuse_score)
71
- return f"Abuse Risk Score: {abuse_score}% — {summary}\nSentiment: {sentiment['label']} ({sentiment['score']*100:.2f}%)"
72
-
73
-
74
- def analyze_composite(msg1, msg2, msg3):
75
- results = [analyze_single_message(t) for t in [msg1, msg2, msg3]]
76
- composite_score = np.mean([
77
- float(line.split('%')[0].split()[-1]) if 'Abuse Risk Score:' in line else 0
78
- for line in results
79
- ])
80
- final_summary = interpret_abuse_level(composite_score)
81
- composite_result = f"\n\nComposite Abuse Risk Score: {composite_score:.2f}% — {final_summary}"
82
- return results[0], results[1], results[2], composite_result
83
 
 
 
 
 
 
 
84
 
85
  iface = gr.Interface(
86
  fn=analyze_composite,
87
  inputs=[
88
  gr.Textbox(label="Message 1"),
89
  gr.Textbox(label="Message 2"),
90
- gr.Textbox(label="Message 3")
 
 
 
 
91
  ],
92
  outputs=[
93
  gr.Textbox(label="Message 1 Result"),
94
  gr.Textbox(label="Message 2 Result"),
95
  gr.Textbox(label="Message 3 Result"),
96
- gr.Textbox(label="Composite Score Summary")
97
  ],
98
  title="Abuse Pattern Detector (Multi-Message)",
99
- live=False,
100
- allow_flagging="manual"
101
  )
102
 
103
  if __name__ == "__main__":
104
- iface.launch()
 
1
  import gradio as gr
2
  import torch
3
  import numpy as np
4
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
5
+ from transformers import RobertaForSequenceClassification, RobertaTokenizer
6
  from motif_tagging import detect_motifs
7
+ from abuse_type_mapping import determine_abuse_type
8
 
9
+ # custom fine-tuned sentiment model
10
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("SamanthaStorm/tether-sentiment")
11
  sentiment_tokenizer = AutoTokenizer.from_pretrained("SamanthaStorm/tether-sentiment")
12
+
13
+ # Load abuse pattern model
14
  model_name = "SamanthaStorm/autotrain-c1un8-p8vzo"
15
  model = RobertaForSequenceClassification.from_pretrained(model_name, trust_remote_code=True)
16
  tokenizer = RobertaTokenizer.from_pretrained(model_name, trust_remote_code=True)
17
 
18
+ LABELS = [
19
+ "gaslighting", "mockery", "dismissiveness", "control", "guilt_tripping", "apology_baiting", "blame_shifting", "projection",
20
+ "contradictory_statements", "manipulation", "deflection", "insults", "obscure_formal", "recovery_phase", "non_abusive",
21
+ "suicidal_threat", "physical_threat", "extreme_control"
22
+ ]
23
+
24
+ THRESHOLDS = {
25
+ "gaslighting": 0.25, "mockery": 0.15, "dismissiveness": 0.45, "control": 0.43, "guilt_tripping": 0.15,
26
+ "apology_baiting": 0.2, "blame_shifting": 0.23, "projection": 0.50, "contradictory_statements": 0.25,
27
+ "manipulation": 0.25, "deflection": 0.30, "insults": 0.34, "obscure_formal": 0.25, "recovery_phase": 0.25,
28
+ "non_abusive": 2.0, "suicidal_threat": 0.45, "physical_threat": 0.02, "extreme_control": 0.30
29
+ }
30
+
31
  PATTERN_LABELS = LABELS[:15]
32
  DANGER_LABELS = LABELS[15:18]
 
 
33
 
34
+ EXPLANATIONS = {
35
+ "gaslighting": "Gaslighting involves making someone question their own reality or perceptions...",
36
+ "blame_shifting": "Blame-shifting is when one person redirects the responsibility...",
37
+ "projection": "Projection involves accusing the victim of behaviors the abuser exhibits.",
38
+ "dismissiveness": "Dismissiveness is belittling or disregarding another person’s feelings.",
39
+ "mockery": "Mockery ridicules someone in a hurtful, humiliating way.",
40
+ "recovery_phase": "Recovery phase dismisses someone's emotional healing process.",
41
+ "insults": "Insults are derogatory remarks aimed at degrading someone.",
42
+ "apology_baiting": "Apology-baiting manipulates victims into apologizing for abuser's behavior.",
43
+ "deflection": "Deflection avoids accountability by redirecting blame.",
44
+ "control": "Control restricts autonomy through manipulation or coercion.",
45
+ "extreme_control": "Extreme control dominates decisions and behaviors entirely.",
46
+ "physical_threat": "Physical threats signal risk of bodily harm.",
47
+ "suicidal_threat": "Suicidal threats manipulate others using self-harm threats.",
48
+ "guilt_tripping": "Guilt-tripping uses guilt to manipulate someone’s actions.",
49
+ "manipulation": "Manipulation deceives to influence or control outcomes.",
50
+ "non_abusive": "Non-abusive language is respectful and free of coercion.",
51
+ "obscure_formal": "Obscure/formal language manipulates through confusion or superiority."
52
+ }
53
+
54
+ PATTERN_WEIGHTS = {
55
+ "physical_threat": 1.5,
56
+ "suicidal_threat": 1.4,
57
+ "extreme_control": 1.5,
58
+ "gaslighting": 1.3,
59
+ "control": 1.2,
60
+ "dismissiveness": 0.8,
61
+ "non_abusive": 0.0
62
+ }
63
 
64
  def custom_sentiment(text):
65
  inputs = sentiment_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
 
72
  score = probs[0][label_idx].item()
73
  return {"label": label, "score": score}
74
 
 
75
  def calculate_abuse_level(scores, thresholds, motif_hits=None):
76
  weighted_scores = []
77
  for label, score in zip(LABELS, scores):
 
80
  weighted_scores.append(score * weight)
81
  base_score = round(np.mean(weighted_scores) * 100, 2) if weighted_scores else 0.0
82
  motif_hits = motif_hits or []
83
+ if any(label in motif_hits for label in {"physical_threat", "suicidal_threat", "extreme_control"}):
84
  base_score = max(base_score, 75.0)
85
  return base_score
86
 
 
87
  def interpret_abuse_level(score):
88
  if score > 80:
89
  return "Extreme / High Risk"
 
95
  return "Mild Concern"
96
  return "Very Low / Likely Safe"
97
 
98
+ def analyze_single_message(text, contextual_flags):
 
 
 
 
 
99
  motif_flags, matched_phrases = detect_motifs(text)
100
+ risk_flags = list(set(contextual_flags + motif_flags)) if contextual_flags else motif_flags
101
+ sentiment_result = custom_sentiment(text)
102
+ sentiment_label = sentiment_result["label"]
103
+ sentiment_score = sentiment_result["score"]
104
+ thresholds = {k: v * 0.8 for k, v in THRESHOLDS.items()} if sentiment_label == "undermining" else THRESHOLDS.copy()
105
  inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
106
  with torch.no_grad():
107
  outputs = model(**inputs)
108
  scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()
109
+ threshold_labels = [label for label, score in zip(PATTERN_LABELS, scores[:15]) if score > thresholds[label]]
110
+ phrase_labels = [label for label, _ in matched_phrases]
111
+ pattern_labels_used = list(set(threshold_labels + phrase_labels))
112
+ abuse_level = calculate_abuse_level(scores, thresholds, motif_hits=[label for label, _ in matched_phrases])
113
+ abuse_description = interpret_abuse_level(abuse_level)
114
+ return {
115
+ "text": text,
116
+ "score": abuse_level,
117
+ "summary": abuse_description,
118
+ "sentiment": f"{sentiment_label} ({sentiment_score*100:.2f}%)",
119
+ "top_labels": pattern_labels_used[:2],
120
+ "matched_phrases": matched_phrases,
121
+ "flags": contextual_flags
122
+ }
123
 
124
+ def analyze_composite(msg1, msg2, msg3, flags):
125
+ results = [analyze_single_message(t, flags) for t in [msg1, msg2, msg3] if t.strip()]
126
+ composite_score = round(np.mean([r['score'] for r in results]), 2) if results else 0.0
127
+ return [
128
+ f"Score: {r['score']}% – {r['summary']}\nSentiment: {r['sentiment']}\nFlags: {', '.join(r['flags']) if r['flags'] else 'None'}\nLabels: {', '.join(r['top_labels'])}" for r in results
129
+ ] + [f"Composite Abuse Score: {composite_score}%"]
130
 
131
  iface = gr.Interface(
132
  fn=analyze_composite,
133
  inputs=[
134
  gr.Textbox(label="Message 1"),
135
  gr.Textbox(label="Message 2"),
136
+ gr.Textbox(label="Message 3"),
137
+ gr.CheckboxGroup(label="Contextual Flags", choices=[
138
+ "They've threatened harm", "They isolate me", "I’ve changed my behavior out of fear",
139
+ "They monitor/follow me", "I feel unsafe when alone with them"
140
+ ])
141
  ],
142
  outputs=[
143
  gr.Textbox(label="Message 1 Result"),
144
  gr.Textbox(label="Message 2 Result"),
145
  gr.Textbox(label="Message 3 Result"),
146
+ gr.Textbox(label="Composite Score")
147
  ],
148
  title="Abuse Pattern Detector (Multi-Message)",
149
+ flagging_mode="manual"
 
150
  )
151
 
152
  if __name__ == "__main__":
153
+ iface.queue().launch()