WJL110 commited on
Commit
9cbc5d1
·
verified ·
1 Parent(s): 0050bb6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -60
app.py CHANGED
@@ -1,70 +1,193 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
 
4
+ # 创建分类器
5
+ classifier = pipeline("text-classification", model="WJL110/emotion-classifier")
6
 
7
+ # 标签映射
8
+ label_map = {
9
+ "LABEL_0": "快乐",
10
+ "LABEL_1": "愤怒",
11
+ "LABEL_2": "悲伤"
12
+ }
13
+
14
+ def analyze_emotion(text):
 
15
  """
16
+ 对输入文本进行情感分析
17
  """
18
+ if not text.strip():
19
+ return "请输入要分析的文本", None, None
20
+
21
+ result = classifier(text)[0] # 获取第一个(也是唯一的)结果
22
+ emotion = label_map[result['label']]
23
+ confidence = result['score']
24
+
25
+ # 根据情感类型返回不同的颜色
26
+ if emotion == "快乐":
27
+ color = "#4CAF50" # 绿色
28
+ elif emotion == "愤怒":
29
+ color = "#F44336" # 红色
30
+ else: # 悲伤
31
+ color = "#2196F3" # 蓝色
32
+
33
+ return f"预测情感: {emotion}", f"置信度: {confidence:.2%}", color
 
 
 
 
 
34
 
35
+ def analyze_emotion_with_history(text, history):
36
+ """
37
+ 带有历史记录的情感分析函数
38
+ """
39
+ result_text, confidence_text, color = analyze_emotion(text)
40
+
41
+ # 更新历史记录
42
+ history.append((text, f"{result_text}\n{confidence_text}"))
43
+
44
+ return history, history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # 创建Gradio界面
47
+ with gr.Blocks(title="情感分析应用", theme=gr.themes.Soft()) as demo:
48
+ gr.Markdown("# 🎭 情感分析应用")
49
+ gr.Markdown("输入文本,AI将分析其情感倾向(快乐、愤怒或悲伤)")
50
+
51
+ with gr.Row():
52
+ with gr.Column(scale=2):
53
+ # 输入区域
54
+ text_input = gr.Textbox(
55
+ label="输入要分析的文本",
56
+ placeholder="请输入您想要分析情感的文本...",
57
+ lines=4,
58
+ max_lines=10
59
+ )
60
+
61
+ # 按钮
62
+ with gr.Row():
63
+ analyze_btn = gr.Button("🔍 分析情感", variant="primary")
64
+ clear_btn = gr.Button("🗑️ 清空", variant="secondary")
65
+
66
+ with gr.Column(scale=2):
67
+ # 输出区域
68
+ result_text = gr.Textbox(
69
+ label="分析结果",
70
+ lines=2,
71
+ interactive=False
72
+ )
73
+
74
+ # 情感标签显示
75
+ sentiment_label = gr.Label(
76
+ label="情感分类",
77
+ value=[{"label": "请输入文本并点击分析按钮", "confidence": 0}]
78
+ )
79
+
80
+ # 历史记录
81
+ gr.Markdown("### 📜 历史记录")
82
+ chatbot = gr.Chatbot(
83
+ label="分析历史",
84
+ height=300
85
+ )
86
+
87
+ # 示例文本
88
+ gr.Markdown("### 📝 示例文本")
89
+
90
+ # 创建示例分类标签页
91
+ with gr.Tabs():
92
+ # 基础示例
93
+ with gr.TabItem("基础示例"):
94
+ basic_examples = gr.Examples(
95
+ examples=(
96
+ "今天真是太开心了!",
97
+ "这件事让我很生气。",
98
+ "听到这个消息很难过。",
99
+ "我收到了一份意外的礼物,感到非常惊喜和快乐!",
100
+ "排队排了这么久,服务还这么差,真是令人愤怒!",
101
+ "我的宠物离开了我���我感到非常悲伤和孤独。"
102
+ ),
103
+ inputs=text_input,
104
+ cache_examples=False
105
+ )
106
+
107
+ # 复杂示例 - 快乐
108
+ with gr.TabItem("复杂示例 - 快乐"):
109
+ happy_examples = gr.Examples(
110
+ examples=(
111
+ "当我看到女儿在毕业典礼上作为优秀毕业生代表发言时,她的声音虽然有些颤抖但坚定有力,我的眼眶不由自主地湿润了。十八年的养育,从蹒跚学步到如今亭亭玉立,所有的辛苦在这一刻都化作了无法言喻的欣慰与自豪。",
112
+ "当我收到大学录取通知书时,激动得跳了起来,但随即又感到一丝不安。我知道这意味着我将离开家人,独自面对陌生的环境和挑战。这种既期待又恐惧的心情让我彻夜难眠。",
113
+ "刚开始看到他忘记了我们的纪念日,我感到有些失落。但当他晚上给我一个惊喜的烛光晚餐,并拿出准备已久的礼物时,那份失落感瞬间被巨大的幸福感所取代,我甚至感动得流下了眼泪。",
114
+ "经过三年的努力,我们终于还清了所有债务。今天,当我把最后一张支票寄出去时,看着窗外明媚的阳光,我深深地吸了一口气,感觉肩上的重担终于卸了下来。"
115
+ ),
116
+ inputs=text_input,
117
+ cache_examples=False
118
+ )
119
+
120
+ # 复杂示例 - 愤怒
121
+ with gr.TabItem("复杂示例 - 愤怒"):
122
+ angry_examples = gr.Examples(
123
+ examples=(
124
+ "当我发现自己精心准备了三个月的项目方案被同事占为己有,并且在领导面前装作是他自己的创意时,一股难以遏制的怒火从心底喷涌而出。这种背叛比项目失败本身更让我感到愤怒和失望。",
125
+ "公司宣布裁员名单时,我既感到愤怒又有些庆幸。愤怒的是公司如此无情地对待为其效力多年的员工,庆幸的是自己不在裁员名单中。这种矛盾的心情让我感到既内疚又不安。",
126
+ "会议开始时,我还能保持冷静地听取不同意见。但当有人开始质疑我的专业能力,并歪曲我的观点时,我感到血液逐渐涌上头顶,从最初的不悦逐渐升级为无法控制的愤怒。",
127
+ "真是太好了!我的笔记本电脑在我准备提交重要项目的前一天突然崩溃了,所有的数据都没有备份。看来我这个月的努力又要白费了,这真是太棒了!"
128
+ ),
129
+ inputs=text_input,
130
+ cache_examples=False
131
+ )
132
+
133
+ # 复杂示例 - 悲伤
134
+ with gr.TabItem("复杂示例 - 悲伤"):
135
+ sad_examples = gr.Examples(
136
+ examples=(
137
+ "整理母亲遗物时,我发现了一本她的日记,里面记录着她对我们子女的牵挂和担忧,即使在她病重的最后日子里,字里行间依然充满了对生活的热爱。看着那些熟悉的字迹,我仿佛又听到了她温柔的叮嘱,泪水无声地滑落。",
138
+ "得知多年未见的好友突然去世的消息,我愣住了。我们曾经一起度过了人生中最美好的青春岁月,那些欢声笑语仿佛还在耳边回响。虽然知道人终有一死,但当这一刻真的来临时,心中还是充满了无法言说的悲伤和遗憾。",
139
+ "接到医院电话时,我只是有些担心。但当医生告诉我检查结果,说情况比预想的要严重得多时,我的心一下子沉了下去,从担忧变成了深深的恐惧和绝望。",
140
+ "今天路过那家我们曾经经常光顾的咖啡馆,看到熟悉的靠窗座位空着,我不由自主地停下了脚步。物是人非,那些曾经的美好时光如今只剩下回忆,心中涌起一股难以言喻的酸楚。"
141
+ ),
142
+ inputs=text_input,
143
+ cache_examples=False
144
+ )
145
+
146
+ # 极高复杂度示例
147
+ with gr.TabItem("极高复杂度示例"):
148
+ extreme_examples = gr.Examples(
149
+ examples=(
150
+ "在父亲的葬礼上,我看到他生前最爱的向日葵开得正盛,那是他亲手种下的。阳光透过教堂的彩色玻璃窗洒进来,照亮了他微笑的遗像。我感到一阵难以言喻的悲伤,却又在这悲伤中感受到一丝温暖和力量。",
151
+ "当我得知自己获得了梦寐以求的职位时,激动得几乎要哭出来。但想到要离开现在的团队和熟悉的环境,心中又涌起一股莫名的伤感。这种既兴奋又不舍的心情让我百感交集。",
152
+ "看到他对我撒谎的证据,我感到一阵眩晕。愤怒、失望、背叛感、还有一丝难以置信,这些情绪在我心中交织,让我几乎无法呼吸。我想大声质问他,却又感到一种深深的无力感。",
153
+ "她只是淡淡地说了一句'祝你幸福',然后转身离开。我看着她渐行渐远的背影,心里空落落的,好像失去了什么重要的东西,却又说不清楚具体是什么。"
154
+ ),
155
+ inputs=text_input,
156
+ cache_examples=False
157
+ )
158
+
159
+ # 绑定事件
160
+ analyze_btn.click(
161
+ fn=analyze_emotion,
162
+ inputs=text_input,
163
+ outputs=[result_text, sentiment_label]
164
+ )
165
+
166
+ # 清空按钮事件
167
+ clear_btn.click(
168
+ fn=lambda: ("", [{"label": "请输入文本并点击分析按钮", "confidence": 0}], []),
169
+ outputs=[text_input, sentiment_label, chatbot]
170
+ )
171
+
172
+ # 回车键触发分析
173
+ text_input.submit(
174
+ fn=analyze_emotion,
175
+ inputs=text_input,
176
+ outputs=[result_text, sentiment_label]
177
+ )
178
+
179
+ # 历史记录更新
180
+ analyze_btn.click(
181
+ fn=analyze_emotion_with_history,
182
+ inputs=[text_input, chatbot],
183
+ outputs=[chatbot, chatbot]
184
+ )
185
+
186
+ text_input.submit(
187
+ fn=analyze_emotion_with_history,
188
+ inputs=[text_input, chatbot],
189
+ outputs=[chatbot, chatbot]
190
+ )
191
 
192
  if __name__ == "__main__":
193
  demo.launch()