SamanthaStorm commited on
Commit
5bb1f05
·
verified ·
1 Parent(s): 947c124

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -65
app.py CHANGED
@@ -12,59 +12,43 @@ model_name = "SamanthaStorm/abuse-pattern-detector-v2"
12
  model = RobertaForSequenceClassification.from_pretrained(model_name, trust_remote_code=True)
13
  tokenizer = RobertaTokenizer.from_pretrained(model_name, trust_remote_code=True)
14
 
15
- # Define labels (18 total)
16
  LABELS = [
17
  "gaslighting", "mockery", "dismissiveness", "control",
18
  "guilt_tripping", "apology_baiting", "blame_shifting", "projection",
19
  "contradictory_statements", "manipulation", "deflection", "insults",
20
- "obscure_formal", "recovery_phase", "non_abusive", "suicidal_threat", "physical_threat",
21
- "extreme_control"
22
  ]
23
 
24
- # Custom thresholds for each label
25
  THRESHOLDS = {
26
- "gaslighting": 0.25,
27
- "mockery": 0.15,
28
- "dismissiveness": 0.30,
29
- "control": 0.43,
30
- "guilt_tripping": 0.19,
31
- "apology_baiting": 0.45,
32
- "blame_shifting": 0.23,
33
- "projection": 0.50,
34
- "contradictory_statements": 0.25,
35
- "manipulation": 0.25,
36
- "deflection": 0.30,
37
- "insults": 0.34,
38
- "obscure_formal": 0.25,
39
- "recovery_phase": 0.25,
40
- "non_abusive": 0.99,
41
- "suicidal_threat": 0.45,
42
- "physical_threat": 0.20,
43
- "extreme_control": 0.36
44
  }
45
 
46
  PATTERN_LABELS = LABELS[:15]
47
- DANGER_LABELS = LABELS[15:18]
48
 
49
  EXPLANATIONS = {
50
- "gaslighting": "Gaslighting involves making someone question their own reality or perceptions, often causing them to feel confused or insecure.",
51
- "blame_shifting": "Blame-shifting is when one person redirects the responsibility for an issue onto someone else, avoiding accountability.",
52
- "projection": "Projection involves accusing the victim of behaviors or characteristics that the abuser themselves exhibit.",
53
- "dismissiveness": "Dismissiveness is the act of belittling or disregarding another person's thoughts, feelings, or experiences.",
54
- "mockery": "Mockery involves ridiculing or making fun of someone in a hurtful way, often with the intent to humiliate them.",
55
- "recovery_phase": "Recovery phase refers to dismissing or invalidating someone’s process of emotional healing, or ignoring their need for support.",
56
- "insults": "Insults are derogatory remarks aimed at degrading or humiliating someone, often targeting their personal traits or character.",
57
- "apology_baiting": "Apology-baiting is when the abuser manipulates the victim into apologizing for something the abuser caused or did wrong.",
58
- "deflection": "Deflection is the act of avoiding responsibility or shifting focus away from one's own actions, often to avoid accountability.",
59
- "control": "Control tactics are behaviors that restrict or limit someone's autonomy, often involving domination, manipulation, or coercion.",
60
- "extreme_control": "Extreme control involves excessive manipulation or domination over someone’s actions, decisions, or behaviors.",
61
- "physical_threat": "Physical threats involve any indication or direct mention of harm to someone’s physical well-being, often used to intimidate or control.",
62
- "suicidal_threat": "Suicidal threats are statements made to manipulate or control someone by making them feel responsible for the abuser’s well-being.",
63
- "guilt_tripping": "Guilt-tripping involves making someone feel guilty or responsible for things they didn’t do, often to manipulate their behavior.",
64
- "emotional_manipulation": "Emotional manipulation is using guilt, fear, or emotional dependency to control another person’s thoughts, feelings, or actions.",
65
- "manipulation": "Manipulation refers to using deceptive tactics to control or influence someone’s emotions, decisions, or behavior to serve the manipulator’s own interests.",
66
- "non_abusive": "Non-abusive language is communication that is respectful, empathetic, and free of harmful behaviors or manipulation.",
67
- "obscure_formal": "Obscure or overly formal language used manipulatively to create confusion, avoid responsibility, or assert superiority."
68
  }
69
 
70
  def calculate_abuse_level(scores, thresholds):
@@ -85,49 +69,55 @@ def interpret_abuse_level(score):
85
  else:
86
  return "Very Low / Likely Safe"
87
 
88
- def analyze_messages(input_text, risk_flags):
89
  input_text = input_text.strip()
90
  if not input_text:
91
  return "Please enter a message for analysis."
92
 
 
93
  sentiment = sentiment_analyzer(input_text)[0]
94
  sentiment_label = sentiment['label']
95
  sentiment_score = sentiment['score']
96
 
 
97
  adjusted_thresholds = THRESHOLDS.copy()
98
  if sentiment_label == "NEGATIVE":
99
  adjusted_thresholds = {key: val * 0.8 for key, val in THRESHOLDS.items()}
100
 
 
101
  inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
102
  with torch.no_grad():
103
  outputs = model(**inputs)
104
  scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()
105
 
 
106
  pattern_count = sum(score > adjusted_thresholds[label] for label, score in zip(PATTERN_LABELS, scores[:15]))
107
- danger_flag_count = sum(score > adjusted_thresholds[label] for label, score in zip(DANGER_LABELS, scores[15:18]))
108
 
109
- # Incorporate risk flag count
110
- user_risk_count = len(risk_flags)
111
- if user_risk_count >= 2:
112
- danger_flag_count += 1 # elevate risk signal
113
 
 
114
  non_abusive_score = scores[LABELS.index('non_abusive')]
115
  if non_abusive_score > adjusted_thresholds['non_abusive']:
116
  return "This message is classified as non-abusive."
117
 
 
118
  abuse_level = calculate_abuse_level(scores, THRESHOLDS)
119
  abuse_description = interpret_abuse_level(abuse_level)
120
 
 
121
  if danger_flag_count >= 2:
122
- resources = "Immediate assistance recommended. Please seek professional help or contact emergency services."
123
  else:
124
  resources = "For more information on abuse patterns, consider reaching out to support groups or professional counselors."
125
 
 
126
  scored_patterns = [(label, score) for label, score in zip(PATTERN_LABELS, scores[:15])]
127
  top_patterns = sorted(scored_patterns, key=lambda x: x[1], reverse=True)[:2]
128
-
129
  top_pattern_explanations = "\n".join([
130
- f"\u2022 {label.replace('_', ' ').title()}: {EXPLANATIONS.get(label, 'No explanation available.')}"
131
  for label, _ in top_patterns
132
  ])
133
 
@@ -136,31 +126,32 @@ def analyze_messages(input_text, risk_flags):
136
  f"Most Likely Patterns:\n{top_pattern_explanations}\n\n"
137
  f"⚠️ Critical Danger Flags Detected: {danger_flag_count} of 3\n"
138
  "The Danger Assessment is a validated tool that helps identify serious risk in intimate partner violence. "
139
- "It flags communication patterns associated with increased risk of severe harm. "
140
- "For more info, consider reaching out to support groups or professionals.\n\n"
141
- f"Resources: {resources} \n\n"
142
  f"Sentiment: {sentiment_label} (Confidence: {sentiment_score*100:.2f}%)"
143
  )
144
 
145
  return result
146
 
 
147
  iface = gr.Interface(
148
  fn=analyze_messages,
149
  inputs=[
150
  gr.Textbox(lines=10, placeholder="Enter message here..."),
151
- gr.CheckboxGroup(label="Do any of these apply to your situation?", choices=[
152
- "They've threatened harm",
153
- "They isolate me",
154
- "I’ve changed my behavior out of fear",
155
- "They monitor/follow me",
156
- "I feel unsafe when alone with them"
157
- ])
158
- ],
159
- outputs=[
160
- gr.Textbox(label="Analysis Result"),
161
  ],
162
- title="Abuse Pattern Detector"
 
163
  )
164
 
165
  if __name__ == "__main__":
166
- iface.launch()
 
12
  model = RobertaForSequenceClassification.from_pretrained(model_name, trust_remote_code=True)
13
  tokenizer = RobertaTokenizer.from_pretrained(model_name, trust_remote_code=True)
14
 
 
15
  LABELS = [
16
  "gaslighting", "mockery", "dismissiveness", "control",
17
  "guilt_tripping", "apology_baiting", "blame_shifting", "projection",
18
  "contradictory_statements", "manipulation", "deflection", "insults",
19
+ "obscure_formal", "recovery_phase", "non_abusive",
20
+ "suicidal_threat", "physical_threat", "extreme_control"
21
  ]
22
 
 
23
  THRESHOLDS = {
24
+ "gaslighting": 0.25, "mockery": 0.15, "dismissiveness": 0.30,
25
+ "control": 0.43, "guilt_tripping": 0.19, "apology_baiting": 0.45,
26
+ "blame_shifting": 0.23, "projection": 0.50, "contradictory_statements": 0.25,
27
+ "manipulation": 0.25, "deflection": 0.30, "insults": 0.34,
28
+ "obscure_formal": 0.25, "recovery_phase": 0.25, "non_abusive": 0.70,
29
+ "suicidal_threat": 0.45, "physical_threat": 0.20, "extreme_control": 0.36
 
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
 
32
  PATTERN_LABELS = LABELS[:15]
33
+ DANGER_LABELS = LABELS[15:]
34
 
35
  EXPLANATIONS = {
36
+ "gaslighting": "Gaslighting involves making someone question their own reality or perceptions.",
37
+ "blame_shifting": "Blame-shifting is when one person redirects responsibility onto someone else.",
38
+ "projection": "Projection accuses the victim of behaviors the abuser exhibits themselves.",
39
+ "dismissiveness": "Dismissiveness belittles or ignores another persons thoughts or feelings.",
40
+ "mockery": "Mockery involves ridicule or sarcasm meant to humiliate.",
41
+ "recovery_phase": "Recovery phase invalidates someone’s healing process or needs.",
42
+ "insults": "Insults are derogatory remarks meant to degrade or attack.",
43
+ "apology_baiting": "Apology-baiting manipulates someone into apologizing for the abuser’s actions.",
44
+ "deflection": "Deflection shifts responsibility or changes the subject to avoid blame.",
45
+ "control": "Control includes behavior that limits another’s autonomy or freedom.",
46
+ "extreme_control": "Extreme control is highly manipulative dominance over another’s choices.",
47
+ "physical_threat": "Physical threats suggest or state a risk of bodily harm.",
48
+ "suicidal_threat": "Suicidal threats use self-harm as a way to manipulate others.",
49
+ "guilt_tripping": "Guilt-tripping makes someone feel guilty for things they didn’t cause.",
50
+ "manipulation": "Manipulation influences someone’s behavior through deceptive emotional tactics.",
51
+ "non_abusive": "Non-abusive language is respectful, supportive, and healthy."
 
 
52
  }
53
 
54
  def calculate_abuse_level(scores, thresholds):
 
69
  else:
70
  return "Very Low / Likely Safe"
71
 
72
+ def analyze_messages(input_text, context_flags):
73
  input_text = input_text.strip()
74
  if not input_text:
75
  return "Please enter a message for analysis."
76
 
77
+ # Sentiment
78
  sentiment = sentiment_analyzer(input_text)[0]
79
  sentiment_label = sentiment['label']
80
  sentiment_score = sentiment['score']
81
 
82
+ # Threshold adjustment for negative tone
83
  adjusted_thresholds = THRESHOLDS.copy()
84
  if sentiment_label == "NEGATIVE":
85
  adjusted_thresholds = {key: val * 0.8 for key, val in THRESHOLDS.items()}
86
 
87
+ # Tokenization and prediction
88
  inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
89
  with torch.no_grad():
90
  outputs = model(**inputs)
91
  scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()
92
 
93
+ # Pattern and danger flags from model
94
  pattern_count = sum(score > adjusted_thresholds[label] for label, score in zip(PATTERN_LABELS, scores[:15]))
95
+ danger_flag_count = sum(score > adjusted_thresholds[label] for label, score in zip(DANGER_LABELS, scores[15:]))
96
 
97
+ # Add contextual danger from checkboxes
98
+ if context_flags and len(context_flags) >= 2:
99
+ danger_flag_count += 1
 
100
 
101
+ # Non-abusive override
102
  non_abusive_score = scores[LABELS.index('non_abusive')]
103
  if non_abusive_score > adjusted_thresholds['non_abusive']:
104
  return "This message is classified as non-abusive."
105
 
106
+ # Abuse level
107
  abuse_level = calculate_abuse_level(scores, THRESHOLDS)
108
  abuse_description = interpret_abuse_level(abuse_level)
109
 
110
+ # Resources
111
  if danger_flag_count >= 2:
112
+ resources = "⚠️ Your responses indicate elevated danger. Please consider seeking support immediately through a domestic violence hotline or trusted professional."
113
  else:
114
  resources = "For more information on abuse patterns, consider reaching out to support groups or professional counselors."
115
 
116
+ # Top patterns with definitions
117
  scored_patterns = [(label, score) for label, score in zip(PATTERN_LABELS, scores[:15])]
118
  top_patterns = sorted(scored_patterns, key=lambda x: x[1], reverse=True)[:2]
 
119
  top_pattern_explanations = "\n".join([
120
+ f" {label.replace('_', ' ').title()}: {EXPLANATIONS.get(label, 'No explanation available.')}"
121
  for label, _ in top_patterns
122
  ])
123
 
 
126
  f"Most Likely Patterns:\n{top_pattern_explanations}\n\n"
127
  f"⚠️ Critical Danger Flags Detected: {danger_flag_count} of 3\n"
128
  "The Danger Assessment is a validated tool that helps identify serious risk in intimate partner violence. "
129
+ "It flags communication patterns associated with increased risk of severe harm.\n\n"
130
+ f"Resources: {resources}\n\n"
 
131
  f"Sentiment: {sentiment_label} (Confidence: {sentiment_score*100:.2f}%)"
132
  )
133
 
134
  return result
135
 
136
+ # Launch interface
137
  iface = gr.Interface(
138
  fn=analyze_messages,
139
  inputs=[
140
  gr.Textbox(lines=10, placeholder="Enter message here..."),
141
+ gr.CheckboxGroup(
142
+ label="Do any of these apply to your situation?",
143
+ choices=[
144
+ "They’ve threatened harm",
145
+ "They isolate me",
146
+ "I’ve changed my behavior out of fear",
147
+ "They monitor/follow me",
148
+ "I feel unsafe when alone with them"
149
+ ]
150
+ )
151
  ],
152
+ outputs=gr.Textbox(label="Analysis Result"),
153
+ title="Abuse Pattern Detector",
154
  )
155
 
156
  if __name__ == "__main__":
157
+ iface.launch()