Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,62 +1,70 @@
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
-
from transformers import RobertaForSequenceClassification, RobertaTokenizer
|
4 |
import numpy as np
|
5 |
-
from transformers import pipeline
|
6 |
|
7 |
-
# Load sentiment
|
8 |
sentiment_analyzer = pipeline("sentiment-analysis")
|
9 |
|
10 |
-
# Load
|
11 |
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 |
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,
|
25 |
-
"
|
26 |
-
"
|
27 |
-
"
|
28 |
-
"
|
29 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
}
|
31 |
|
32 |
-
|
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
|
39 |
-
"dismissiveness": "Dismissiveness
|
40 |
-
"mockery": "Mockery involves
|
41 |
-
"recovery_phase": "Recovery phase
|
42 |
-
"insults": "Insults are derogatory remarks
|
43 |
-
"apology_baiting": "Apology-baiting manipulates
|
44 |
-
"deflection": "Deflection
|
45 |
-
"control": "Control
|
46 |
-
"extreme_control": "Extreme control
|
47 |
-
"physical_threat": "Physical threats
|
48 |
-
"suicidal_threat": "Suicidal threats
|
49 |
-
"guilt_tripping": "Guilt-tripping
|
50 |
-
"manipulation": "Manipulation
|
51 |
-
"non_abusive": "Non-abusive language is respectful,
|
52 |
}
|
53 |
|
54 |
-
|
55 |
-
triggered_scores = [score for label, score in zip(LABELS, scores) if score > thresholds[label]]
|
56 |
-
if not triggered_scores:
|
57 |
-
return 0.0
|
58 |
-
return round(np.mean(triggered_scores) * 100, 2)
|
59 |
-
|
60 |
def interpret_abuse_level(score):
|
61 |
if score > 80:
|
62 |
return "Extreme / High Risk"
|
@@ -69,6 +77,7 @@ def interpret_abuse_level(score):
|
|
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:
|
@@ -79,78 +88,75 @@ def analyze_messages(input_text, context_flags):
|
|
79 |
sentiment_label = sentiment['label']
|
80 |
sentiment_score = sentiment['score']
|
81 |
|
82 |
-
#
|
83 |
adjusted_thresholds = THRESHOLDS.copy()
|
84 |
-
if sentiment_label == "NEGATIVE":
|
85 |
-
adjusted_thresholds = {
|
86 |
|
87 |
-
#
|
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
|
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
|
98 |
if context_flags and len(context_flags) >= 2:
|
99 |
danger_flag_count += 1
|
100 |
|
101 |
-
#
|
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
|
107 |
-
|
|
|
108 |
abuse_description = interpret_abuse_level(abuse_level)
|
109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
# Resources
|
111 |
if danger_flag_count >= 2:
|
112 |
-
resources = "
|
113 |
else:
|
114 |
resources = "For more information on abuse patterns, consider reaching out to support groups or professional counselors."
|
115 |
|
116 |
-
#
|
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 |
-
|
124 |
result = (
|
125 |
f"Abuse Risk Score: {abuse_level}% – {abuse_description}\n\n"
|
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
|
130 |
-
|
|
|
131 |
f"Sentiment: {sentiment_label} (Confidence: {sentiment_score*100:.2f}%)"
|
132 |
)
|
133 |
-
|
134 |
return result
|
135 |
|
136 |
-
#
|
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 |
-
|
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__":
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
+
from transformers import RobertaForSequenceClassification, RobertaTokenizer, pipeline
|
4 |
import numpy as np
|
|
|
5 |
|
6 |
+
# Load sentiment model
|
7 |
sentiment_analyzer = pipeline("sentiment-analysis")
|
8 |
|
9 |
+
# Load abuse pattern model
|
10 |
model_name = "SamanthaStorm/abuse-pattern-detector-v2"
|
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 |
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 |
+
PATTERN_LABELS = LABELS[:15]
|
23 |
+
DANGER_LABELS = LABELS[15:]
|
24 |
|
25 |
+
# Thresholds
|
26 |
THRESHOLDS = {
|
27 |
+
"gaslighting": 0.25,
|
28 |
+
"mockery": 0.15,
|
29 |
+
"dismissiveness": 0.30,
|
30 |
+
"control": 0.43,
|
31 |
+
"guilt_tripping": 0.19,
|
32 |
+
"apology_baiting": 0.45,
|
33 |
+
"blame_shifting": 0.23,
|
34 |
+
"projection": 0.50,
|
35 |
+
"contradictory_statements": 0.25,
|
36 |
+
"manipulation": 0.25,
|
37 |
+
"deflection": 0.30,
|
38 |
+
"insults": 0.34,
|
39 |
+
"obscure_formal": 0.25,
|
40 |
+
"recovery_phase": 0.25,
|
41 |
+
"non_abusive": 0.70,
|
42 |
+
"suicidal_threat": 0.45,
|
43 |
+
"physical_threat": 0.20,
|
44 |
+
"extreme_control": 0.36
|
45 |
}
|
46 |
|
47 |
+
# Explanations
|
|
|
|
|
48 |
EXPLANATIONS = {
|
49 |
+
"gaslighting": "Gaslighting involves making someone question their own reality or perceptions, often causing them to feel confused or insecure.",
|
50 |
+
"blame_shifting": "Blame-shifting is when one person redirects the responsibility for an issue onto someone else, avoiding accountability.",
|
51 |
+
"projection": "Projection involves accusing the victim of behaviors or characteristics that the abuser themselves exhibit.",
|
52 |
+
"dismissiveness": "Dismissiveness is the act of belittling or disregarding another person's thoughts, feelings, or experiences.",
|
53 |
+
"mockery": "Mockery involves ridiculing or making fun of someone in a hurtful way, often with the intent to humiliate them.",
|
54 |
+
"recovery_phase": "Recovery phase refers to dismissing or invalidating someone’s process of emotional healing, or ignoring their need for support.",
|
55 |
+
"insults": "Insults are derogatory remarks aimed at degrading or humiliating someone, often targeting their personal traits or character.",
|
56 |
+
"apology_baiting": "Apology-baiting is when the abuser manipulates the victim into apologizing for something the abuser caused or did wrong.",
|
57 |
+
"deflection": "Deflection is the act of avoiding responsibility or shifting focus away from one's own actions, often to avoid accountability.",
|
58 |
+
"control": "Control tactics are behaviors that restrict or limit someone's autonomy, often involving domination, manipulation, or coercion.",
|
59 |
+
"extreme_control": "Extreme control involves excessive manipulation or domination over someone’s actions, decisions, or behaviors.",
|
60 |
+
"physical_threat": "Physical threats involve any indication or direct mention of harm to someone’s physical well-being, often used to intimidate or control.",
|
61 |
+
"suicidal_threat": "Suicidal threats are statements made to manipulate or control someone by making them feel responsible for the abuser’s well-being.",
|
62 |
+
"guilt_tripping": "Guilt-tripping involves making someone feel guilty or responsible for things they didn’t do, often to manipulate their behavior.",
|
63 |
+
"manipulation": "Manipulation refers to using deceptive tactics to control or influence someone’s emotions, decisions, or behavior to serve the manipulator’s own interests.",
|
64 |
+
"non_abusive": "Non-abusive language is communication that is respectful, empathetic, and free of harmful behaviors or manipulation."
|
65 |
}
|
66 |
|
67 |
+
# Abuse level interpretation
|
|
|
|
|
|
|
|
|
|
|
68 |
def interpret_abuse_level(score):
|
69 |
if score > 80:
|
70 |
return "Extreme / High Risk"
|
|
|
77 |
else:
|
78 |
return "Very Low / Likely Safe"
|
79 |
|
80 |
+
# Main analysis
|
81 |
def analyze_messages(input_text, context_flags):
|
82 |
input_text = input_text.strip()
|
83 |
if not input_text:
|
|
|
88 |
sentiment_label = sentiment['label']
|
89 |
sentiment_score = sentiment['score']
|
90 |
|
91 |
+
# Adjust thresholds if negative tone
|
92 |
adjusted_thresholds = THRESHOLDS.copy()
|
93 |
+
if sentiment_label.upper() == "NEGATIVE":
|
94 |
+
adjusted_thresholds = {k: v * 0.8 for k, v in THRESHOLDS.items()}
|
95 |
|
96 |
+
# Run model
|
97 |
inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
|
98 |
with torch.no_grad():
|
99 |
outputs = model(**inputs)
|
100 |
scores = torch.sigmoid(outputs.logits.squeeze(0)).numpy()
|
101 |
|
102 |
+
# Pattern & danger from model
|
103 |
pattern_count = sum(score > adjusted_thresholds[label] for label, score in zip(PATTERN_LABELS, scores[:15]))
|
104 |
danger_flag_count = sum(score > adjusted_thresholds[label] for label, score in zip(DANGER_LABELS, scores[15:]))
|
105 |
|
106 |
+
# Add checkbox context flags
|
107 |
if context_flags and len(context_flags) >= 2:
|
108 |
danger_flag_count += 1
|
109 |
|
110 |
+
# Override if non-abusive
|
111 |
non_abusive_score = scores[LABELS.index('non_abusive')]
|
112 |
if non_abusive_score > adjusted_thresholds['non_abusive']:
|
113 |
return "This message is classified as non-abusive."
|
114 |
|
115 |
+
# Abuse score
|
116 |
+
triggered_scores = [score for label, score in zip(LABELS, scores) if score > adjusted_thresholds[label]]
|
117 |
+
abuse_level = round(np.mean(triggered_scores) * 100, 2) if triggered_scores else 0.0
|
118 |
abuse_description = interpret_abuse_level(abuse_level)
|
119 |
|
120 |
+
# Top patterns
|
121 |
+
scored_patterns = [(label, score) for label, score in zip(PATTERN_LABELS, scores[:15])]
|
122 |
+
top_patterns = sorted(scored_patterns, key=lambda x: x[1], reverse=True)[:2]
|
123 |
+
top_pattern_explanations = "\n".join(
|
124 |
+
[f"• {label.replace('_', ' ').title()}: {EXPLANATIONS.get(label, 'No explanation available.')}" for label, _ in top_patterns]
|
125 |
+
)
|
126 |
+
|
127 |
# Resources
|
128 |
if danger_flag_count >= 2:
|
129 |
+
resources = "Immediate assistance recommended. Please seek professional help or contact emergency services."
|
130 |
else:
|
131 |
resources = "For more information on abuse patterns, consider reaching out to support groups or professional counselors."
|
132 |
|
133 |
+
# Result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
result = (
|
135 |
f"Abuse Risk Score: {abuse_level}% – {abuse_description}\n\n"
|
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 |
return result
|
145 |
|
146 |
+
# Interface
|
147 |
iface = gr.Interface(
|
148 |
fn=analyze_messages,
|
149 |
inputs=[
|
150 |
+
gr.Textbox(lines=10, placeholder="Enter message here...", label="input_text"),
|
151 |
gr.CheckboxGroup(
|
152 |
+
["They've threatened harm", "They isolate me", "I've changed my behavior out of fear",
|
153 |
+
"They monitor/follow me", "I feel unsafe when alone with them"],
|
154 |
label="Do any of these apply to your situation?",
|
155 |
+
type="value"
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
)
|
157 |
],
|
158 |
outputs=gr.Textbox(label="Analysis Result"),
|
159 |
+
title="Abuse Pattern Detector"
|
160 |
)
|
161 |
|
162 |
if __name__ == "__main__":
|