Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
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",
|
21 |
-
"extreme_control"
|
22 |
]
|
23 |
|
24 |
-
# Custom thresholds for each label
|
25 |
THRESHOLDS = {
|
26 |
-
"gaslighting": 0.25,
|
27 |
-
"
|
28 |
-
"
|
29 |
-
"
|
30 |
-
"
|
31 |
-
"
|
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:
|
48 |
|
49 |
EXPLANATIONS = {
|
50 |
-
"gaslighting": "Gaslighting involves making someone question their own reality or perceptions
|
51 |
-
"blame_shifting": "Blame-shifting is when one person redirects
|
52 |
-
"projection": "Projection
|
53 |
-
"dismissiveness": "Dismissiveness
|
54 |
-
"mockery": "Mockery involves
|
55 |
-
"recovery_phase": "Recovery phase
|
56 |
-
"insults": "Insults are derogatory remarks
|
57 |
-
"apology_baiting": "Apology-baiting
|
58 |
-
"deflection": "Deflection
|
59 |
-
"control": "Control
|
60 |
-
"extreme_control": "Extreme control
|
61 |
-
"physical_threat": "Physical threats
|
62 |
-
"suicidal_threat": "Suicidal threats
|
63 |
-
"guilt_tripping": "Guilt-tripping
|
64 |
-
"
|
65 |
-
"
|
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,
|
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:
|
108 |
|
109 |
-
#
|
110 |
-
|
111 |
-
|
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 = "
|
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"
|
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 |
-
"
|
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(
|
152 |
-
"
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
],
|
162 |
-
|
|
|
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 person’s 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()
|