jenniferhk008 commited on
Commit
5eec73a
·
verified ·
1 Parent(s): 9dc1a75

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +39 -36
agent.py CHANGED
@@ -1,36 +1,39 @@
1
- import streamlit as st
2
- from agent import classify_emoji_text
3
-
4
- # ✅ 页面配置
5
- st.set_page_config(page_title="Emoji Offensive Text Detector", page_icon="🚨", layout="wide")
6
-
7
- # 页面标题
8
- st.title("🧠 Emoji-based Offensive Language Classifier")
9
-
10
- st.markdown("""
11
- This application translates emojis in a sentence and classifies whether the final sentence is offensive or not using two AI models.
12
- - The **first model** translates emoji or symbolic phrases into standard Chinese text.
13
- - The **second model** performs offensive language detection.
14
- """)
15
-
16
- # ✅ 输入区域
17
- default_text = "你是🐷"
18
- text = st.text_area("✍️ Input your sentence here:", value=default_text, height=150)
19
-
20
- # 触发按钮
21
- if st.button("🚦 Analyze"):
22
- with st.spinner("🔍 Processing..."):
23
- try:
24
- translated, label, score = classify_emoji_text(text)
25
-
26
- # 输出结果显示(修复多行字符串语法)
27
- st.markdown("### 🔄 Translated sentence:")
28
- st.code(translated, language="text")
29
-
30
- st.markdown(f"### 🎯 Prediction: `{label}`")
31
- st.markdown(f"### 📊 Confidence Score: `{score:.2%}`")
32
-
33
- except Exception as e:
34
- st.error(f"❌ An error occurred during processing:\n\n{e}")
35
- else:
36
- st.info("👈 Please input text and click the button to classify.")
 
 
 
 
1
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
2
+ import torch
3
+
4
+ # ✅ Step 1: Emoji 翻译模型(你自己训练的模型)
5
+ emoji_model_id = "JenniferHJF/qwen1.5-emoji-finetuned"
6
+ emoji_tokenizer = AutoTokenizer.from_pretrained(emoji_model_id, trust_remote_code=True)
7
+ emoji_model = AutoModelForCausalLM.from_pretrained(
8
+ emoji_model_id,
9
+ trust_remote_code=True,
10
+ torch_dtype=torch.float16
11
+ ).to("cuda" if torch.cuda.is_available() else "cpu")
12
+ emoji_model.eval()
13
+
14
+ # ✅ Step 2: 冒犯性文本识别模型
15
+ classifier = pipeline("text-classification", model="unitary/toxic-bert", device=0 if torch.cuda.is_available() else -1)
16
+
17
+ def classify_emoji_text(text: str):
18
+ """
19
+ Step 1: 翻译文本中的 emoji
20
+ Step 2: 使用分类器判断是否冒犯
21
+ """
22
+ prompt = f"""请判断下面的文本是否具有冒犯性。
23
+ 这里的“冒犯性”主要指包含人身攻击、侮辱、歧视、仇恨言论或极端粗俗的内容。
24
+ 如果文本具有冒犯性,请仅回复冒犯;如果不具有冒犯性,请仅回复不冒犯。
25
+ 文本如下:
26
+ {text}
27
+ """
28
+
29
+ input_ids = emoji_tokenizer(prompt, return_tensors="pt").to(emoji_model.device)
30
+ with torch.no_grad():
31
+ output_ids = emoji_model.generate(**input_ids, max_new_tokens=50, do_sample=False)
32
+ decoded = emoji_tokenizer.decode(output_ids[0], skip_special_tokens=True)
33
+ translated_text = decoded.strip().split("文本如下:")[-1].strip()
34
+
35
+ result = classifier(translated_text)[0]
36
+ label = result["label"]
37
+ score = result["score"]
38
+
39
+ return translated_text, label, score