import gradio as gr from transformers import pipeline # --- 全局变量和模型加载 --- # 在应用启动时,我们只加载一次模型,这对于性能至关重要。 # 这样可以避免每次用户查询时都重新加载模型。 # 1. 使用 pipeline 加载你的情感分类模型 # 注意:模型名称需要是 Hugging Face Hub 上的准确名称 classifier = pipeline("text-classification", model="WJL110/emotion-classifier") # 2. 定义标签映射,将模型输出的 LABEL_0 等转换为更友好的中文标签 label_map = { "LABEL_0": "快乐", "LABEL_1": "愤怒", "LABEL_2": "悲伤" } # --- 核心推理函数 --- # 这个函数将被 Gradio 调用。它接收用户输入,并返回模型预测结果。 def classify_emotion(text): """ 对输入的文本进行情感分析。 """ if not text.strip(): # 处理空输入 return "请输入一些文本进行分析。" # 使用模型进行预测 # pipeline 返回一个列表,其中包含一个字典,例如:[{'label': 'LABEL_0', 'score': 0.99}] result = classifier(text)[0] # 从结果中提取标签和置信度,并进行格式化 predicted_label = result['label'] confidence = result['score'] # 将技术标签转换为中文情感名称 emotion = label_map[predicted_label] # 返回一个格式化的字符串作为结果 return f"预测情感: **{emotion}**\n置信度: **{confidence:.4f}**" # --- Gradio 界面定义 --- # 使用 gr.Interface 创建一个简单的 Web 界面 # fn: 指定要调用的函数 (我们的 classify_emotion) # inputs: 指定输入组件 (一个文本框) # outputs: 指定输出组件 (一个文本框,我们设置它能渲染 Markdown) # title, description: 设置界面的标题和描述 demo = gr.Interface( fn=classify_emotion, inputs=gr.Textbox( label="输入文本", placeholder="在这里输入你想分析情感的句子,例如:今天天气真好!" ), outputs=gr.Textbox( label="分析结果", lines=3, # 设置输出框的高度 interactive=False # 用户不能编辑输出框 ), title="情感分析器 (Emotion Classifier)", description="这个应用使用 `WJL110/emotion-classifier` 模型来分析文本中的情感倾向,可识别快乐、愤怒和悲伤三种情绪。" ) # --- 启动应用 --- # 当这个脚本被直接运行时,启动 Gradio 服务 if __name__ == "__main__": # 在 Hugging Face Spaces 上,需要将 share 设置为 False # server_name="0.0.0.0" 是让应用在容器的所有网络接口上监听,这是 Spaces 所必需的 demo.launch(server_name="0.0.0.0", share=False)