StructBERT 中文情感分类 WebUI 实现与多语言切换
基于百度 StructBERT 模型的中文情感分类 WebUI,支持中英文界面切换,让非技术用户也能轻松进行情感分析
1. 项目概述与环境准备
StructBERT 中文情感分类模型是百度基于 StructBERT 预训练模型微调后的经典模型,专门用于识别中文文本的情感倾向(正面/负面/中性)。这个模型在中文 NLP 领域有着很好的效果和效率平衡,特别适合实际业务应用。
介绍基于 StructBERT 模型构建的中文情感分类 WebUI 项目,支持单文本与批量分析,提供中英文界面切换。采用 Python、PyTorch、Gradio 及 Transformers 技术栈。内容包括环境配置、核心代码实现(模型加载、推理优化)、部署脚本及电商评论、社交媒体监控等应用场景。旨在为用户提供便捷的情感分析工具,支持 API 集成与批量处理,适用于个人及企业场景。
基于百度 StructBERT 模型的中文情感分类 WebUI,支持中英文界面切换,让非技术用户也能轻松进行情感分析
StructBERT 中文情感分类模型是百度基于 StructBERT 预训练模型微调后的经典模型,专门用于识别中文文本的情感倾向(正面/负面/中性)。这个模型在中文 NLP 领域有着很好的效果和效率平衡,特别适合实际业务应用。
本项目提供了一个完整的 WebUI 界面,支持单文本和批量情感分析,并且实现了中英文界面切换功能,让不同语言习惯的用户都能方便使用。
环境要求:
快速安装:
# 创建 conda 环境
conda create -n sentiment python=3.8
conda activate sentiment
# 安装核心依赖
pip install torch gradio flask transformers
单文本分析是最常用的功能,适合快速检查一段文字的情感倾向:
http://localhost:7860使用示例:
批量分析功能适合处理大量文本数据,比如用户评论分析:
批量处理优势:
实现多语言界面的关键在于使用 Gradio 的语言切换功能和动态界面更新:
import gradio as gr
from typing import Dict
LANGUAGE_TEXT = {
"zh": {
"title": "StructBERT 中文情感分析",
"single_title": "单文本情感分析",
"batch_title": "批量情感分析",
"input_placeholder": "请输入中文文本...",
"analyze_btn": "开始分析",
"positive": "积极",
"negative": "消极",
"neutral": "中性"
},
"en": {
"title": "StructBERT Sentiment Analysis",
"single_title": "Single Text Analysis",
"batch_title": "Batch Analysis",
"input_placeholder": "Enter Chinese text...",
"analyze_btn": "Analyze",
"positive": "Positive",
"negative": "Negative",
"neutral": "Neutral"
}
}
def create_interface(lang: str = "zh"):
"""创建多语言界面"""
texts = LANGUAGE_TEXT[lang]
with gr.Blocks(title=texts["title"]) as demo:
gr.Markdown(f"# {texts['title']}")
# 语言切换按钮
with gr.Row():
lang_btn = gr.Radio(
choices=["中文", "English"],
value="中文" if lang == "zh" else "English",
label="选择语言 / Language"
)
# 单文本分析区域
with gr.Tab(texts["single_title"]):
with gr.Row():
single_input = gr.Textbox(
label="输入文本",
placeholder=texts["input_placeholder"],
lines=3
)
with gr.Row():
analyze_btn = gr.Button(texts["analyze_btn"])
with gr.Row():
output = gr.Label(label="情感分析结果")
# 批量分析区域
with gr.Tab(texts["batch_title"]):
with gr.Row():
batch_input = gr.Textbox(
label="批量输入(每行一条)",
placeholder=texts["input_placeholder"],
lines=10
)
with gr.Row():
batch_btn = gr.Button("批量分析")
with gr.Row():
batch_output = gr.Dataframe(
headers=["文本", "情感", "置信度"],
label="批量分析结果"
)
# 语言切换逻辑
def update_language(selected_lang):
new_lang = "zh" if selected_lang == "中文" else "en"
return create_interface(new_lang)
lang_btn.change(update_language, inputs=lang_btn, outputs=demo)
return demo
Gradio 的 Blocks 组件支持动态界面更新,这是实现语言切换的关键:
# 启动多语言界面
demo = create_interface("zh")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)
实现原理:
from transformers import BertTokenizer, BertForSequenceClassification
import torch
from typing import List, Dict
class SentimentAnalyzer:
def __init__(self, model_path: str):
"""初始化情感分析模型"""
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.tokenizer = BertTokenizer.from_pretrained(model_path)
self.model = BertForSequenceClassification.from_pretrained(model_path)
self.model.to(self.device)
self.model.eval()
# 情感标签映射
self.label_map = {0: "negative", 1: "neutral", 2: "positive"}
def analyze_single(self, text: str):
"""分析单条文本"""
# 文本编码
inputs = self.tokenizer(
text, return_tensors="pt", truncation=True, max_length=512, padding=True
)
# 模型预测
with torch.no_grad():
inputs = {k: v.to(self.device) for k, v in inputs.items()}
outputs = self.model(**inputs)
probabilities = torch.softmax(outputs.logits, dim=-1)
# 结果解析
pred_label = torch.argmax(probabilities, dim=-1).item()
confidence = probabilities[0][pred_label].item()
return {
"text": text,
"sentiment": self.label_map[pred_label],
"confidence": round(confidence, 4),
"probabilities": probabilities.tolist()
}
对于批量文本分析,我们进行了性能优化:
def analyze_batch(self, texts: List[str], batch_size: int = 32):
"""批量分析文本,支持大批量处理"""
results = []
# 分批处理避免内存溢出
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
# 批量编码
inputs = self.tokenizer(
batch_texts, return_tensors="pt", truncation=True, max_length=512,
padding=True, add_special_tokens=True
)
# 批量预测
with torch.no_grad():
inputs = {k: v.to(self.device) for k, v in inputs.items()}
outputs = self.model(**inputs)
probabilities = torch.softmax(outputs.logits, dim=-1)
# 批量结果处理
batch_results = []
for j, probs in enumerate(probabilities):
pred_label = torch.argmax(probs).item()
confidence = probs[pred_label].item()
batch_results.append({
"text": batch_texts[j],
"sentiment": self.label_map[pred_label],
"confidence": round(confidence, 4)
})
results.extend(batch_results)
return results
创建启动脚本方便快速部署:
#!/bin/bash
# start_sentiment.sh
# 激活 conda 环境
conda activate sentiment
# 启动 WebUI 服务
cd /root/nlp_structbert_sentiment-classification_chinese-base
python app/webui.py &
# 启动 API 服务
python app/main.py &
echo "服务启动完成!"
echo "WebUI 地址:http://localhost:7860"
echo "API 地址:http://localhost:8080"
查看服务状态:
supervisorctl status
重启服务:
# 重启 WebUI
supervisorctl restart nlp_structbert_webui
# 重启 API
supervisorctl restart nlp_structbert_sentiment
查看日志:
# 实时查看 WebUI 日志
supervisorctl tail -f nlp_structbert_webui
# 查看 API 日志
supervisorctl tail -f nlp_structbert_sentiment
场景:分析商品评论情感倾向
# 示例评论数据
reviews = [
"产品质量很好,物超所值!",
"快递速度太慢了,等了好几天",
"包装很精美,适合送礼",
"功能没有描述的好,有点失望"
]
# 批量分析
analyzer = SentimentAnalyzer(MODEL_PATH)
results = analyzer.analyze_batch(reviews)
for result in results:
print(f"评论:{result['text']}")
print(f"情感:{result['sentiment']} (置信度:{result['confidence']})")
print("-" * 50)
场景:监控品牌相关讨论的情感倾向
def monitor_social_media(keywords: List[str], platform: str = "weibo"):
"""监控社交媒体情感"""
# 获取相关帖子
posts = fetch_posts(keywords, platform)
# 情感分析
sentiments = analyzer.analyze_batch(posts)
# 生成情感报告
positive_count = sum(1 for s in sentiments if s['sentiment'] == 'positive')
negative_count = sum(1 for s in sentiments if s['sentiment'] == 'negative')
return {
"total_posts": len(posts),
"positive_rate": positive_count / len(posts),
"negative_rate": negative_count / len(posts),
"details": sentiments
}
通过本教程,我们实现了一个功能完整的 StructBERT 中文情感分类 WebUI,支持中英文界面切换,让不同用户都能方便使用。
核心优势:
使用建议:
性能优化提示:
这个情感分析 WebUI 不仅提供了友好的用户界面,还通过多语言支持让更多用户能够受益于 AI 技术的情感分析能力。无论是个人使用还是企业应用,都是一个实用且强大的工具。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online