使用modelscope部署StructBERT情感分类-中文-通用-base
模型,并提供api接口
本地部署modelscope环境
为了简化部署,直接使用官方提供的docker镜像部署环境
拉取镜像
使用cpu镜像
bash
docker pull modelscope-registry.cn-beijing.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-py311-torch2.3.1-1.28.0

启动容器
挂载容器内的/home
目录到本地,作为开发目录
arduino
docker run -it --rm -p 8080:8080 --name modelscopelocal -v <本地目录>:/home <镜像> bash
本地目录和镜像替换为实际的内容 启动后,会直接进入容器中
bash
docker run -it --rm -p 8080:8080 --name modelscopelocal -v D:\workspace\modelscope:/home 6e724d5e15e8 bash
root@470b3a2a6460:/#
使用模型进行预测
在开发目录下创建一个python文件main.py
,使用模型对输入文本进行情感分析
python
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
semantic_cls = pipeline(Tasks.text_classification, 'iic/nlp_structbert_sentiment-classification_chinese-base')
result = semantic_cls(input=['哪次能看到你挖石油不漏','今晚什么游戏啊 主播可以说一声吗'])
print(result)
在命令行运行python main.py
输出结果如下:
json
[{'scores': [0.8981053829193115, 0.10189458727836609], 'labels': ['正面', '负面']}, {'scores': [0.8091937899589539, 0.19080623984336853], 'labels': ['正面', '负面']}, {'scores': [0.896651029586792, 0.10334893316030502], 'labels': ['负面', '正面']}]
启动一个fastapi服务提供api接口
开发目录下创建一个app.py文件
python
## 腾讯元宝自动生成
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
app = FastAPI(title="情感分析API", description="提供文本情感分析的REST接口", version="1.0.0")
# 加载模型(保持不变)
try:
sentiment_pipeline = pipeline(
task=Tasks.text_classification,
model='iic/nlp_structbert_sentiment-classification_chinese-base'
)
except Exception as e:
raise RuntimeError(f"模型加载失败: {str(e)}")
# 请求数据结构(保持不变)
class TextListRequest(BaseModel):
texts: List[str]
# 响应数据结构(新增 text 字段)
class AnalysisResult(BaseModel):
text: str # 原始输入文本(新增)
labels: List[str] # 情感标签(如 ["正面", "负面"])
scores: List[float] # 对应标签的概率分数(如 [0.89, 0.11])
class AnalysisResponse(BaseModel):
results: List[AnalysisResult] # 每个文本的完整结果
# /analysis 接口(核心修改点)
@app.post("/analysis", response_model=AnalysisResponse)
async def analyze_text(request: TextListRequest):
try:
raw_results = sentiment_pipeline(input=request.texts)
# 新增:将原始文本与预测结果绑定(按顺序一一对应)
formatted_results = [
AnalysisResult(
text=request.texts[i], # 原始文本
labels=result["labels"], # 标签
scores=result["scores"] # 分数
)
for i, result in enumerate(raw_results) # 按索引匹配原始文本
]
return {"results": formatted_results}
except Exception as e:
raise HTTPException(status_code=500, detail=f"预测失败: {str(e)}")
# 其他代码(健康检查、启动命令等)保持不变
# 可选:添加健康检查接口
@app.get("/health", description="服务健康检查")
async def health_check():
return {"status": "ok", "message": "服务运行正常"}
# 启动命令(运行时执行)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
app="app:app", # 模块名:应用实例名
host="0.0.0.0", # 允许外部访问
port=8080, # 端口号
reload=True # 开发模式自动重载(生产环境建议设为False)
)
启动服务python app.py
访问分析接口
在容器外访问接口
css
curl --location --request POST 'http://localhost:8080/analysis' \
--header 'Content-Type: application/json' \
--data-raw '{"texts": ["南征北战"]}'
返回结果如下
json
{
"results": [
{
"text": "南征北战",
"labels": [
"正面",
"负面"
],
"scores": [
0.8927718997001648,
0.10722804069519043
]
}
]
}