WJL110 commited on
Commit
92a5737
·
verified ·
1 Parent(s): c82bc9e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # 1. 加载模型
5
+ # 第一次启动时会下载模型,可能需要几秒钟
6
+ classifier = pipeline("text-classification", model="WJL110/emotion-classifier")
7
+
8
+ # 2. 定义标签映射
9
+ label_map = {
10
+ "LABEL_0": "快乐",
11
+ "LABEL_1": "愤怒",
12
+ "LABEL_2": "悲伤"
13
+ }
14
+
15
+ def respond(message, history):
16
+ """
17
+ message: 用户输入的当前文本
18
+ history: 之前的对话历史 (分类模型通常不需要上下文,所以这里我们只处理当前message)
19
+ """
20
+ if not message:
21
+ return "请输入内容"
22
+
23
+ try:
24
+ # 进行推理
25
+ result = classifier(message)[0]
26
+
27
+ # 获取结果
28
+ raw_label = result['label']
29
+ score = result['score']
30
+
31
+ # 映射标签
32
+ emotion = label_map.get(raw_label, raw_label) # 如果找不到key,就显示原始label
33
+
34
+ # 格式化回复内容
35
+ response_text = (
36
+ f"🤖 分析结果:\n"
37
+ f"------------------\n"
38
+ f"预测情感:**{emotion}**\n"
39
+ f"置信度:{score:.2%}"
40
+ )
41
+ return response_text
42
+
43
+ except Exception as e:
44
+ return f"发生错误: {str(e)}"
45
+
46
+ # 3. 创建聊天界面
47
+ # 虽然这是分类任务,但使用 ChatInterface 可以给用户一种交互的感觉
48
+ demo = gr.ChatInterface(
49
+ fn=respond,
50
+ title="情感分析机器人 (Emotion Classifier)",
51
+ description="输入一段文字,我会分析其中包含的情感(快乐、愤怒、悲伤)。",
52
+ examples=["今天真是太开心了!", "这件事让我很生气。", "听到这个消息很难过。"],
53
+ retry_btn=None,
54
+ undo_btn=None,
55
+ clear_btn="清除",
56
+ )
57
+
58
+ if __name__ == "__main__":
59
+ demo.launch()