Update app.py
Browse files
app.py
CHANGED
@@ -1,124 +1,219 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
}
|
9 |
|
10 |
-
#
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
|
16 |
-
for
|
17 |
-
label = res["label"]
|
18 |
-
score = res["score"]
|
19 |
-
for cat, keywords in OFFENSE_CATEGORIES.items():
|
20 |
-
if any(kw in label.lower() for kw in keywords):
|
21 |
-
category_scores[cat] += score
|
22 |
-
|
23 |
-
# 单词级分析
|
24 |
-
word_analysis = []
|
25 |
-
for word in text.split():
|
26 |
try:
|
27 |
res = classifier(word)[0]
|
28 |
-
|
29 |
-
"
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
if any(kw in res["label"].lower() for kw in keywords)),
|
35 |
-
"Other"
|
36 |
-
)
|
37 |
-
})
|
38 |
-
except:
|
39 |
-
continue
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
# 处理文本输入
|
53 |
-
text_input = text if text else ocr_text
|
54 |
-
analysis = classify_text_with_categories(text_input)
|
55 |
-
|
56 |
-
# 更新历史记录
|
57 |
-
st.session_state.history.append({
|
58 |
-
"original": text_input,
|
59 |
-
"translated": analysis["translations"],
|
60 |
-
"overall": analysis["overall"],
|
61 |
-
"categories": analysis["categories"],
|
62 |
-
"word_analysis": analysis["word_analysis"]
|
63 |
-
})
|
64 |
-
|
65 |
-
# 展示核心结果
|
66 |
-
st.markdown("**Main Prediction:**")
|
67 |
-
st.metric("Label", analysis["overall"]["label"],
|
68 |
-
delta=f"{analysis['overall']['score']:.2%} Confidence")
|
69 |
-
|
70 |
-
# 新增:类别分布展示
|
71 |
-
st.markdown("### 📊 Offense Category Breakdown")
|
72 |
-
category_data = [{"Category": k, "Score": v} for k, v in analysis["categories"].items()]
|
73 |
-
fig = px.bar(category_data, x="Category", y="Score",
|
74 |
-
title="Category Contribution",
|
75 |
-
labels={"Score": "Probability"})
|
76 |
-
st.plotly_chart(fig)
|
77 |
-
|
78 |
-
except Exception as e:
|
79 |
-
st.error(f"❌ Error: {str(e)}")
|
80 |
-
|
81 |
-
# 优化后的雷达图生成
|
82 |
-
if st.session_state.history:
|
83 |
-
# 聚合所有历史记录的类别数据
|
84 |
-
radar_data = {cat: [] for cat in OFFENSE_CATEGORIES}
|
85 |
-
for entry in st.session_state.history:
|
86 |
-
for cat, score in entry["categories"].items():
|
87 |
-
radar_data[cat].append(score)
|
88 |
|
89 |
-
#
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
-
# 构建雷达图
|
94 |
fig = px.line_polar(
|
95 |
-
|
96 |
-
r='
|
97 |
-
|
|
|
|
|
|
|
98 |
)
|
99 |
-
fig.
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
if st.session_state.history:
|
104 |
-
#
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
else:
|
124 |
-
st.info("No
|
|
|
|
|
|
1 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
2 |
+
import torch
|
3 |
+
import streamlit as st
|
4 |
+
from PIL import Image
|
5 |
+
import pytesseract
|
6 |
+
import pandas as pd
|
7 |
+
import plotly.express as px
|
8 |
+
|
9 |
+
# ✅ 新增维度定义
|
10 |
+
OFFENSIVE_CATEGORIES = {
|
11 |
+
"Insult": ["蠢货", "白痴", "废物"],
|
12 |
+
"Abuse": ["去死", "打死", "宰了你"],
|
13 |
+
"Discrimination": ["女司机", "娘娘腔", "黑鬼"],
|
14 |
+
"HateSpeech": ["灭族", "屠杀", "灭绝"],
|
15 |
+
"Vulgarity": ["艹", "sb", "尼玛"]
|
16 |
}
|
17 |
|
18 |
+
# ✅ 模型初始化(保持原有结构)
|
19 |
+
emoji_model_id = "JenniferHJF/qwen1.5-emoji-finetuned"
|
20 |
+
emoji_tokenizer = AutoTokenizer.from_pretrained(emoji_model_id, trust_remote_code=True)
|
21 |
+
emoji_model = AutoModelForCausalLM.from_pretrained(
|
22 |
+
emoji_model_id,
|
23 |
+
trust_remote_code=True,
|
24 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
25 |
+
).to("cuda" if torch.cuda.is_available() else "cpu")
|
26 |
+
emoji_model.eval()
|
27 |
+
|
28 |
+
model_options = {
|
29 |
+
"Toxic-BERT": "unitary/toxic-bert",
|
30 |
+
"Roberta Offensive": "cardiffnlp/twitter-roberta-base-offensive",
|
31 |
+
"BERT Emotion": "bhadresh-savani/bert-base-go-emotion"
|
32 |
+
}
|
33 |
+
|
34 |
+
# ✅ 动态评分算法
|
35 |
+
def dynamic_scoring(text: str, classifier):
|
36 |
+
scores = {k: 0.0 for k in OFFENSIVE_CATEGORIES}
|
37 |
+
|
38 |
+
for category, keywords in OFFENSIVE_CATEGORIES.items():
|
39 |
+
for kw in keywords:
|
40 |
+
if kw in text:
|
41 |
+
scores[category] += 0.3
|
42 |
|
43 |
+
words = text.split()
|
44 |
+
for word in words:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
try:
|
46 |
res = classifier(word)[0]
|
47 |
+
if res["label"] in scores:
|
48 |
+
scores[res["label"]] += res["score"] * 0.7
|
49 |
+
except: pass
|
50 |
+
|
51 |
+
max_score = max(scores.values()) or 1
|
52 |
+
return {k: round(v/max_score, 2) for k,v in scores.items()}
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
+
# ✅ 分类函数改造
|
55 |
+
def classify_emoji_text(text: str):
|
56 |
+
prompt = f"输入:{text}\n输出:"
|
57 |
+
input_ids = emoji_tokenizer(prompt, return_tensors="pt").to(emoji_model.device)
|
58 |
+
with torch.no_grad():
|
59 |
+
output_ids = emoji_model.generate(**input_ids, max_new_tokens=64, do_sample=False)
|
60 |
+
decoded = emoji_tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
61 |
+
translated_text = decoded.split("输出:")[-1].strip() if "输出:" in decoded else decoded.strip()
|
62 |
|
63 |
+
result = classifier(translated_text)[0]
|
64 |
+
label = result["label"]
|
65 |
+
score = result["score"]
|
66 |
+
reasoning = f"The sentence was flagged as '{label}' due to potentially offensive phrases."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
# 新增维度分析
|
69 |
+
category_scores = dynamic_scoring(translated_text, classifier)
|
70 |
+
|
71 |
+
st.session_state.history.append({
|
72 |
+
"text": text,
|
73 |
+
"translated": translated_text,
|
74 |
+
"label": label,
|
75 |
+
"score": score,
|
76 |
+
"reason": reasoning,
|
77 |
+
"scores": category_scores
|
78 |
+
})
|
79 |
+
return translated_text, label, score, reasoning, category_scores
|
80 |
+
|
81 |
+
# ✅ 可视化生成函数
|
82 |
+
def generate_radar_chart(scores_dict: dict):
|
83 |
+
radar_df = pd.DataFrame({
|
84 |
+
"Category": list(scores_dict.keys()),
|
85 |
+
"Score": list(scores_dict.values())
|
86 |
+
})
|
87 |
|
|
|
88 |
fig = px.line_polar(
|
89 |
+
radar_df,
|
90 |
+
r='Score',
|
91 |
+
theta='Category',
|
92 |
+
line_close=True,
|
93 |
+
color_discrete_sequence=['#FF6B6B'],
|
94 |
+
title="🛡️ Multi-Dimensional Offensive Analysis"
|
95 |
)
|
96 |
+
fig.update_layout(
|
97 |
+
polar=dict(
|
98 |
+
radialaxis=dict(
|
99 |
+
visible=True,
|
100 |
+
range=[0, 1],
|
101 |
+
tickvals=[0, 0.3, 0.7, 1],
|
102 |
+
ticktext=["Safe", "Caution", "Risk", "Danger"]
|
103 |
+
)),
|
104 |
+
showlegend=False
|
105 |
+
)
|
106 |
+
return fig
|
107 |
+
|
108 |
+
# ✅ 页面配置(保持原有结构)
|
109 |
+
st.set_page_config(page_title="Emoji Offensive Text Detector", page_icon="🚨", layout="wide")
|
110 |
+
|
111 |
+
with st.sidebar:
|
112 |
+
st.header("🧠 Configuration")
|
113 |
+
selected_model = st.selectbox("Choose classification model", list(model_options.keys()))
|
114 |
+
selected_model_id = model_options[selected_model]
|
115 |
+
classifier = pipeline("text-classification", model=selected_model_id, device=0 if torch.cuda.is_available() else -1)
|
116 |
+
|
117 |
+
if "history" not in st.session_state:
|
118 |
+
st.session_state.history = []
|
119 |
+
|
120 |
+
# 主页面逻辑
|
121 |
+
st.title("🚨 Emoji Offensive Text Detector & Analysis Dashboard")
|
122 |
|
123 |
+
# 文本输入
|
124 |
+
st.subheader("1. 输入与分类")
|
125 |
+
default_text = "你是🐷"
|
126 |
+
text = st.text_area("Enter sentence with emojis:", value=default_text, height=150)
|
127 |
+
|
128 |
+
if st.button("🚦 Analyze Text"):
|
129 |
+
with st.spinner("🔍 Processing..."):
|
130 |
+
try:
|
131 |
+
translated, label, score, reason, category_scores = classify_emoji_text(text)
|
132 |
+
# 展示基础结果
|
133 |
+
st.markdown("**Translated sentence:**")
|
134 |
+
st.code(translated, language="text")
|
135 |
+
# 展示雷达图
|
136 |
+
st.plotly_chart(generate_radar_chart(category_scores))
|
137 |
+
|
138 |
+
# 图片上传与 OCR
|
139 |
+
st.markdown("---")
|
140 |
+
st.subheader("2. 图片 OCR & 分类")
|
141 |
+
uploaded_file = st.file_uploader("Upload an image (JPG/PNG)", type=["jpg","jpeg","png"])
|
142 |
+
if uploaded_file:
|
143 |
+
image = Image.open(uploaded_file)
|
144 |
+
st.image(image, caption="Uploaded Screenshot", use_column_width=True)
|
145 |
+
with st.spinner("🧠 Extracting text via OCR..."):
|
146 |
+
ocr_text = pytesseract.image_to_string(image, lang="chi_sim+eng").strip()
|
147 |
+
if ocr_text:
|
148 |
+
st.markdown("**Extracted Text:**")
|
149 |
+
st.code(ocr_text)
|
150 |
+
translated, label, score, reason = classify_emoji_text(ocr_text)
|
151 |
+
st.markdown("**Translated sentence:**")
|
152 |
+
st.code(translated, language="text")
|
153 |
+
st.markdown(f"**Prediction:** {label}")
|
154 |
+
st.markdown(f"**Confidence Score:** {score:.2%}")
|
155 |
+
st.markdown("**Model Explanation:**")
|
156 |
+
st.info(reason)
|
157 |
+
else:
|
158 |
+
st.info("⚠️ No text detected in the image.")
|
159 |
+
|
160 |
+
# 分析仪表盘
|
161 |
+
st.markdown("---")
|
162 |
+
st.subheader("3. Violation Analysis Dashboard")
|
163 |
if st.session_state.history:
|
164 |
+
# 展示历史记录
|
165 |
+
df = pd.DataFrame(st.session_state.history)
|
166 |
+
st.markdown("### 🧾 Offensive Terms & Suggestions")
|
167 |
+
for item in st.session_state.history:
|
168 |
+
st.markdown(f"- 🔹 **Input:** {item['text']}")
|
169 |
+
st.markdown(f" - ✨ **Translated:** {item['translated']}")
|
170 |
+
st.markdown(f" - ❗ **Label:** {item['label']} with **{item['score']:.2%}** confidence")
|
171 |
+
st.markdown(f" - 🔧 **Suggestion:** {item['reason']}")
|
172 |
+
|
173 |
+
# 雷达图
|
174 |
+
radar_df = pd.DataFrame({
|
175 |
+
"Category": ["Insult","Abuse","Discrimination","Hate Speech","Vulgarity"],
|
176 |
+
"Score": [0.7,0.4,0.3,0.5,0.6]
|
177 |
+
})
|
178 |
+
radar_fig = px.line_polar(radar_df, r='Score', theta='Category', line_close=True, title="⚠️ Risk Radar by Category")
|
179 |
+
radar_fig.update_traces(line_color='black')
|
180 |
+
st.plotly_chart(radar_fig)
|
181 |
+
|
182 |
+
# —— 新增:单词级冒犯性相关性分析 —— #
|
183 |
+
st.markdown("### 🧬 Word-level Offensive Correlation")
|
184 |
+
|
185 |
+
# 取最近一次翻译文本,按空格拆分单词
|
186 |
+
last_translated_text = st.session_state.history[-1]["translated"]
|
187 |
+
words = last_translated_text.split()
|
188 |
+
|
189 |
+
# 对每个单词进行分类并收集分数
|
190 |
+
word_scores = []
|
191 |
+
for word in words:
|
192 |
+
try:
|
193 |
+
res = classifier(word)[0]
|
194 |
+
word_scores.append({
|
195 |
+
"Word": word,
|
196 |
+
"Label": res["label"],
|
197 |
+
"Score": res["score"]
|
198 |
+
})
|
199 |
+
except Exception:
|
200 |
+
continue
|
201 |
+
|
202 |
+
if word_scores:
|
203 |
+
word_df = pd.DataFrame(word_scores)
|
204 |
+
word_df = word_df.sort_values(by="Score", ascending=False).reset_index(drop=True)
|
205 |
+
|
206 |
+
max_display = 5
|
207 |
+
# Streamlit 1.22+ 支持 st.toggle,若版本不支持可改用 checkbox
|
208 |
+
show_more = st.toggle("Show more words", value=False)
|
209 |
+
|
210 |
+
display_df = word_df if show_more else word_df.head(max_display)
|
211 |
+
# 隐藏边框并渲染 HTML 表格
|
212 |
+
st.markdown(
|
213 |
+
display_df.to_html(index=False, border=0),
|
214 |
+
unsafe_allow_html=True
|
215 |
+
)
|
216 |
else:
|
217 |
+
st.info("❕ No word-level analysis available.")
|
218 |
+
else:
|
219 |
+
st.info("⚠️ No classification data available yet.")
|