Create agent.py
Browse files
agent.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|