aeresd commited on
Commit
826a9bc
·
verified ·
1 Parent(s): 857cce7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -156
app.py CHANGED
@@ -1,168 +1,124 @@
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
- # ✅ Step 1: Emoji 翻译模型(你自己训练的模型)
10
- emoji_model_id = "JenniferHJF/qwen1.5-emoji-finetuned"
11
- emoji_tokenizer = AutoTokenizer.from_pretrained(emoji_model_id, trust_remote_code=True)
12
- emoji_model = AutoModelForCausalLM.from_pretrained(
13
- emoji_model_id,
14
- trust_remote_code=True,
15
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
16
- ).to("cuda" if torch.cuda.is_available() else "cpu")
17
- emoji_model.eval()
18
-
19
- # ✅ Step 2: 可选择的冒犯性文本识别模型
20
- model_options = {
21
- "Toxic-BERT": "unitary/toxic-bert",
22
- "Roberta Offensive": "cardiffnlp/twitter-roberta-base-offensive",
23
- "BERT Emotion": "bhadresh-savani/bert-base-go-emotion"
24
  }
25
 
26
- # ✅ 页面配置
27
- st.set_page_config(page_title="Emoji Offensive Text Detector", page_icon="🚨", layout="wide")
28
-
29
- # 侧边栏:模型选择
30
- with st.sidebar:
31
- st.header("🧠 Configuration")
32
- selected_model = st.selectbox("Choose classification model", list(model_options.keys()))
33
- selected_model_id = model_options[selected_model]
34
- classifier = pipeline("text-classification", model=selected_model_id, device=0 if torch.cuda.is_available() else -1)
35
-
36
- # 初始化历史记录
37
- if "history" not in st.session_state:
38
- st.session_state.history = []
39
-
40
- # 分类函数
41
- def classify_emoji_text(text: str):
42
- prompt = f"输入:{text}\n输出:"
43
- input_ids = emoji_tokenizer(prompt, return_tensors="pt").to(emoji_model.device)
44
- with torch.no_grad():
45
- output_ids = emoji_model.generate(**input_ids, max_new_tokens=64, do_sample=False)
46
- decoded = emoji_tokenizer.decode(output_ids[0], skip_special_tokens=True)
47
- translated_text = decoded.split("输出:")[-1].strip() if "输出:" in decoded else decoded.strip()
48
-
49
- result = classifier(translated_text)[0]
50
- label = result["label"]
51
- score = result["score"]
52
- reasoning = (
53
- f"The sentence was flagged as '{label}' due to potentially offensive phrases. "
54
- "Consider replacing emotionally charged, ambiguous, or abusive terms."
55
- )
56
-
57
- st.session_state.history.append({
58
- "text": text,
59
- "translated": translated_text,
60
- "label": label,
61
- "score": score,
62
- "reason": reasoning
63
- })
64
- return translated_text, label, score, reasoning
65
-
66
- # 主页面:输入与分析共存
67
- st.title("🚨 Emoji Offensive Text Detector & Analysis Dashboard")
68
 
69
- # 文本输入
70
- st.subheader("1. 输入与分类")
71
- default_text = "你是🐷"
72
- text = st.text_area("Enter sentence with emojis:", value=default_text, height=150)
 
 
73
 
 
74
  if st.button("🚦 Analyze Text"):
75
  with st.spinner("🔍 Processing..."):
76
  try:
77
- translated, label, score, reason = classify_emoji_text(text)
78
- st.markdown("**Translated sentence:**")
79
- st.code(translated, language="text")
80
- st.markdown(f"**Prediction:** {label}")
81
- st.markdown(f"**Confidence Score:** {score:.2%}")
82
- st.markdown("**Model Explanation:**")
83
- st.info(reason)
84
- except Exception as e:
85
- st.error(f" An error occurred:\n{e}")
86
-
87
- # 图片上传与 OCR
88
- st.markdown("---")
89
- st.subheader("2. 图片 OCR & 分类")
90
- uploaded_file = st.file_uploader("Upload an image (JPG/PNG)", type=["jpg","jpeg","png"])
91
- if uploaded_file:
92
- image = Image.open(uploaded_file)
93
- st.image(image, caption="Uploaded Screenshot", use_column_width=True)
94
- with st.spinner("🧠 Extracting text via OCR..."):
95
- ocr_text = pytesseract.image_to_string(image, lang="chi_sim+eng").strip()
96
- if ocr_text:
97
- st.markdown("**Extracted Text:**")
98
- st.code(ocr_text)
99
- translated, label, score, reason = classify_emoji_text(ocr_text)
100
- st.markdown("**Translated sentence:**")
101
- st.code(translated, language="text")
102
- st.markdown(f"**Prediction:** {label}")
103
- st.markdown(f"**Confidence Score:** {score:.2%}")
104
- st.markdown("**Model Explanation:**")
105
- st.info(reason)
106
- else:
107
- st.info("⚠️ No text detected in the image.")
108
-
109
- # 分析仪表盘
110
- st.markdown("---")
111
- st.subheader("3. Violation Analysis Dashboard")
112
- if st.session_state.history:
113
- # 展示历史记录
114
- df = pd.DataFrame(st.session_state.history)
115
- st.markdown("### 🧾 Offensive Terms & Suggestions")
116
- for item in st.session_state.history:
117
- st.markdown(f"- 🔹 **Input:** {item['text']}")
118
- st.markdown(f" - ✨ **Translated:** {item['translated']}")
119
- st.markdown(f" - ❗ **Label:** {item['label']} with **{item['score']:.2%}** confidence")
120
- st.markdown(f" - 🔧 **Suggestion:** {item['reason']}")
121
-
122
- # 雷达图
123
- radar_df = pd.DataFrame({
124
- "Category": ["Insult","Abuse","Discrimination","Hate Speech","Vulgarity"],
125
- "Score": [0.7,0.4,0.3,0.5,0.6]
126
- })
127
- radar_fig = px.line_polar(radar_df, r='Score', theta='Category', line_close=True, title="⚠️ Risk Radar by Category")
128
- radar_fig.update_traces(line_color='black')
129
- st.plotly_chart(radar_fig)
130
-
131
- # —— 新增:单词级冒犯性相关性分析 —— #
132
- st.markdown("### 🧬 Word-level Offensive Correlation")
133
-
134
- # 取最近一次翻译文本,按空格拆分单词
135
- last_translated_text = st.session_state.history[-1]["translated"]
136
- words = last_translated_text.split()
137
-
138
- # 对每个单词进行分类并收集分数
139
- word_scores = []
140
- for word in words:
141
- try:
142
- res = classifier(word)[0]
143
- word_scores.append({
144
- "Word": word,
145
- "Label": res["label"],
146
- "Score": res["score"]
147
  })
148
- except Exception:
149
- continue
 
 
 
 
 
 
 
 
 
 
 
150
 
151
- if word_scores:
152
- word_df = pd.DataFrame(word_scores)
153
- word_df = word_df.sort_values(by="Score", ascending=False).reset_index(drop=True)
154
 
155
- max_display = 5
156
- # Streamlit 1.22+ 支持 st.toggle,若版本不支持可改用 checkbox
157
- show_more = st.toggle("Show more words", value=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
- display_df = word_df if show_more else word_df.head(max_display)
160
- # 隐藏边框并渲染 HTML 表格
161
- st.markdown(
162
- display_df.to_html(index=False, border=0),
163
- unsafe_allow_html=True
164
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  else:
166
- st.info("No word-level analysis available.")
167
- else:
168
- st.info("⚠️ No classification data available yet.")
 
1
+ # 新增:预定义冒犯性类别映射(根据雷达图需求)
2
+ OFFENSE_CATEGORIES = {
3
+ "Insult": ["侮辱", "贬低", "讽刺"],
4
+ "Abuse": ["辱骂", "攻击性语言", "脏话"],
5
+ "Discrimination": ["歧视性言论", "种族歧视", "性别歧视"],
6
+ "Hate Speech": ["仇恨言论", "暴力煽动"],
7
+ "Vulgarity": ["低俗用语", "色情暗示"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  }
9
 
10
+ # 修改分类函数以支持多维度分析
11
+ def classify_text_with_categories(text: str):
12
+ results = classifier(text)
13
+ category_scores = {category: 0 for category in OFFENSE_CATEGORIES}
14
+
15
+ # 多维度评分
16
+ for res in results:
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
+ word_analysis.append({
29
+ "word": word,
30
+ "main_label": res["label"],
31
+ "main_score": res["score"],
32
+ "offense_category": next(
33
+ (cat for cat, keywords in OFFENSE_CATEGORIES.items()
34
+ if any(kw in res["label"].lower() for kw in keywords)),
35
+ "Other"
36
+ )
37
+ })
38
+ except:
39
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ return {
42
+ "translations": text,
43
+ "overall": results[0],
44
+ "categories": category_scores,
45
+ "word_analysis": word_analysis
46
+ }
47
 
48
+ # 优化后的分类处理
49
  if st.button("🚦 Analyze Text"):
50
  with st.spinner("🔍 Processing..."):
51
  try:
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
+ avg_scores = {cat: sum(scores)/len(scores) if scores else 0
91
+ for cat, scores in radar_data.items()}
92
+
93
+ # 构建雷达图
94
+ fig = px.line_polar(
95
+ pd.DataFrame(avg_scores, index=OFFENSE_CATEGORIES).reset_index(),
96
+ r='index', theta='OFFENSE_CATEGORIES',
97
+ line_close=True, title="📉 Offense Risk Radar Chart"
98
+ )
99
+ fig.update_traces(line_color='#FF4B4B')
100
+ st.plotly_chart(fig)
101
 
102
+ # 优化后的单词级分析
103
+ if st.session_state.history:
104
+ # 聚合单词级数据
105
+ all_words = []
106
+ for entry in st.session_state.history:
107
+ all_words.extend(entry["word_analysis"])
108
+
109
+ # 生成词云数据
110
+ word_counts = pd.DataFrame(all_words).groupby('word').agg({
111
+ 'main_score': 'mean',
112
+ 'offense_category': lambda x: x.mode()[0]
113
+ }).reset_index().sort_values('main_score', ascending=False)
114
+
115
+ # 交互式词云展示
116
+ st.markdown("### 🧩 Offensive Word Analysis")
117
+ if not word_counts.empty:
118
+ top_words = word_counts.head(10)
119
+ fig = px.bar(top_words, x="word", y="main_score",
120
+ color="offense_category",
121
+ title="Top Offensive Words by Score")
122
+ st.plotly_chart(fig)
123
  else:
124
+ st.info("No offensive words detected")