Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ 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(
|
|
@@ -16,21 +16,29 @@ emoji_model = AutoModelForCausalLM.from_pretrained(
|
|
| 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 |
if "history" not in st.session_state:
|
| 31 |
st.session_state.history = []
|
| 32 |
|
| 33 |
-
|
| 34 |
def classify_emoji_text(text: str):
|
| 35 |
prompt = f"输入:{text}\n输出:"
|
| 36 |
input_ids = emoji_tokenizer(prompt, return_tensors="pt").to(emoji_model.device)
|
|
@@ -42,82 +50,85 @@ def classify_emoji_text(text: str):
|
|
| 42 |
result = classifier(translated_text)[0]
|
| 43 |
label = result["label"]
|
| 44 |
score = result["score"]
|
| 45 |
-
reasoning =
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
st.session_state.history.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return translated_text, label, score, reasoning
|
| 49 |
|
| 50 |
-
# 页面布局
|
| 51 |
-
st.
|
| 52 |
-
|
| 53 |
-
selected_model_id = model_options[selected_model]
|
| 54 |
-
classifier = pipeline("text-classification", model=selected_model_id, device=0 if torch.cuda.is_available() else -1)
|
| 55 |
-
|
| 56 |
-
# 主页面:集成 Text Moderation 和 Text Analysis
|
| 57 |
-
st.title("🚨 Emoji Offensive Text Detector & Violation Analysis")
|
| 58 |
-
|
| 59 |
-
# 输入与分类
|
| 60 |
-
st.markdown("## ✍️ 输入或上传文本进行分类")
|
| 61 |
-
col1, col2 = st.columns([2,1])
|
| 62 |
-
with col1:
|
| 63 |
-
text = st.text_area("Enter sentence with emojis:", value="你是🐷", height=150)
|
| 64 |
-
if st.button("🚦 Analyze Text"):
|
| 65 |
-
with st.spinner("🔍 Processing..."):
|
| 66 |
-
try:
|
| 67 |
-
translated, label, score, reason = classify_emoji_text(text)
|
| 68 |
-
st.markdown("### 🔄 Translated sentence:")
|
| 69 |
-
st.code(translated, language="text")
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
st.error(f"❌ Error during processing: {e}")
|
| 77 |
|
| 78 |
-
|
| 79 |
-
st.markdown("### 🖼️ Or upload a screenshot:")
|
| 80 |
-
uploaded_file = st.file_uploader("Image (JPG/PNG)", type=["jpg","png","jpeg"])
|
| 81 |
if uploaded_file:
|
| 82 |
image = Image.open(uploaded_file)
|
| 83 |
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 84 |
-
with st.spinner("
|
| 85 |
ocr_text = pytesseract.image_to_string(image, lang="chi_sim+eng").strip()
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
|
|
|
| 96 |
st.markdown("---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
# 违规分析仪表盘
|
| 99 |
-
st.markdown("## 📊 Violation Analysis Dashboard")
|
| 100 |
-
if st.session_state.history:
|
| 101 |
df = pd.DataFrame(st.session_state.history)
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
for item in st.session_state.history:
|
| 104 |
-
st.markdown(f"-
|
| 105 |
-
st.markdown(f" -
|
| 106 |
-
st.markdown(f" -
|
|
|
|
| 107 |
|
|
|
|
| 108 |
radar_df = pd.DataFrame({
|
| 109 |
-
"Category": ["Insult","Abuse","Discrimination","Hate Speech","Vulgarity"],
|
| 110 |
-
"Score": [0.7,0.4,0.3,0.5,0.6]
|
| 111 |
})
|
| 112 |
-
# 优化雷达图,设置线条为黑色
|
| 113 |
radar_fig = px.line_polar(
|
| 114 |
radar_df,
|
| 115 |
r='Score',
|
| 116 |
theta='Category',
|
| 117 |
line_close=True,
|
| 118 |
-
title="⚠️ Risk Radar by Category"
|
| 119 |
-
color_discrete_sequence=['black']
|
| 120 |
)
|
|
|
|
| 121 |
st.plotly_chart(radar_fig)
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
| 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(
|
|
|
|
| 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("🧠 Settings")
|
| 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,
|
| 35 |
+
device=0 if torch.cuda.is_available() else -1)
|
| 36 |
+
|
| 37 |
+
# 初始化会话历史
|
| 38 |
if "history" not in st.session_state:
|
| 39 |
st.session_state.history = []
|
| 40 |
|
| 41 |
+
|
| 42 |
def classify_emoji_text(text: str):
|
| 43 |
prompt = f"输入:{text}\n输出:"
|
| 44 |
input_ids = emoji_tokenizer(prompt, return_tensors="pt").to(emoji_model.device)
|
|
|
|
| 50 |
result = classifier(translated_text)[0]
|
| 51 |
label = result["label"]
|
| 52 |
score = result["score"]
|
| 53 |
+
reasoning = (
|
| 54 |
+
f"The sentence was flagged as '{label}' due to potentially offensive phrases. "
|
| 55 |
+
"Consider replacing emotionally charged, ambiguous, or abusive terms."
|
| 56 |
+
)
|
| 57 |
|
| 58 |
+
st.session_state.history.append({
|
| 59 |
+
"text": text,
|
| 60 |
+
"translated": translated_text,
|
| 61 |
+
"label": label,
|
| 62 |
+
"score": score,
|
| 63 |
+
"reason": reasoning
|
| 64 |
+
})
|
| 65 |
return translated_text, label, score, reasoning
|
| 66 |
|
| 67 |
+
# 主页面布局
|
| 68 |
+
st.title("🚨 Emoji Offensive Text Detector & Analysis")
|
| 69 |
+
st.markdown("---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
# 输入与分析
|
| 72 |
+
st.header("✍️ Input & Moderation")
|
| 73 |
+
def text_moderation_section():
|
| 74 |
+
st.markdown("Enter text with emojis or upload an image with text.")
|
| 75 |
+
text = st.text_area("Sentence (or OCR text will appear here):", height=120)
|
|
|
|
| 76 |
|
| 77 |
+
uploaded_file = st.file_uploader("Or upload an image for OCR:", type=["jpg", "jpeg", "png"])
|
|
|
|
|
|
|
| 78 |
if uploaded_file:
|
| 79 |
image = Image.open(uploaded_file)
|
| 80 |
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 81 |
+
with st.spinner("Extracting text via OCR..."):
|
| 82 |
ocr_text = pytesseract.image_to_string(image, lang="chi_sim+eng").strip()
|
| 83 |
+
st.text_area("Extracted Text:", value=ocr_text, height=120)
|
| 84 |
+
text = ocr_text
|
| 85 |
+
|
| 86 |
+
if st.button("🚦 Analyze Text") and text:
|
| 87 |
+
with st.spinner("Processing..."):
|
| 88 |
+
try:
|
| 89 |
+
translated, label, score, reason = classify_emoji_text(text)
|
| 90 |
+
st.subheader("🔄 Translated Text")
|
| 91 |
+
st.code(translated)
|
| 92 |
+
st.subheader(f"🎯 Prediction: {label}")
|
| 93 |
+
st.write(f"Confidence: {score:.2%}")
|
| 94 |
+
st.subheader("🧠 Explanation")
|
| 95 |
+
st.info(reason)
|
| 96 |
+
except Exception as e:
|
| 97 |
+
st.error(f"Error during processing: {e}")
|
| 98 |
|
| 99 |
+
# 分析仪表板
|
| 100 |
st.markdown("---")
|
| 101 |
+
st.header("📊 Violation Analysis")
|
| 102 |
+
def analysis_dashboard():
|
| 103 |
+
if not st.session_state.history:
|
| 104 |
+
st.info("No data to display. Please analyze some text first.")
|
| 105 |
+
return
|
| 106 |
|
|
|
|
|
|
|
|
|
|
| 107 |
df = pd.DataFrame(st.session_state.history)
|
| 108 |
+
|
| 109 |
+
# 建议列表
|
| 110 |
+
st.subheader("📝 Offensive Terms & Suggestions")
|
| 111 |
for item in st.session_state.history:
|
| 112 |
+
st.markdown(f"- **Input:** {item['text']}")
|
| 113 |
+
st.markdown(f" - Translated: {item['translated']}")
|
| 114 |
+
st.markdown(f" - Label: {item['label']} ({item['score']:.2%})")
|
| 115 |
+
st.markdown(f" - Suggestion: {item['reason']}")
|
| 116 |
|
| 117 |
+
# 雷达图
|
| 118 |
radar_df = pd.DataFrame({
|
| 119 |
+
"Category": ["Insult", "Abuse", "Discrimination", "Hate Speech", "Vulgarity"],
|
| 120 |
+
"Score": [0.7, 0.4, 0.3, 0.5, 0.6]
|
| 121 |
})
|
|
|
|
| 122 |
radar_fig = px.line_polar(
|
| 123 |
radar_df,
|
| 124 |
r='Score',
|
| 125 |
theta='Category',
|
| 126 |
line_close=True,
|
| 127 |
+
title="⚠️ Risk Radar by Category"
|
|
|
|
| 128 |
)
|
| 129 |
+
radar_fig.update_traces(line_color='black')
|
| 130 |
st.plotly_chart(radar_fig)
|
| 131 |
+
|
| 132 |
+
# 渲染各部分
|
| 133 |
+
text_moderation_section()
|
| 134 |
+
analysis_dashboard()
|