Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
4 |
+
import torch
|
5 |
+
|
6 |
+
# 创建 FastAPI 应用
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# 加载模型和分词器
|
10 |
+
model_name = "IDEA-CCNL/Erlangshen-Roberta-330M-Sentiment"
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
13 |
+
|
14 |
+
# 定义请求数据格式
|
15 |
+
class TextRequest(BaseModel):
|
16 |
+
text: str
|
17 |
+
|
18 |
+
# 定义情感分析 API
|
19 |
+
@app.post("/predict")
|
20 |
+
def predict_sentiment(request: TextRequest):
|
21 |
+
inputs = tokenizer(request.text, return_tensors="pt", truncation=True, padding=True)
|
22 |
+
outputs = model(**inputs)
|
23 |
+
prediction = torch.argmax(outputs.logits, dim=1).item()
|
24 |
+
return {"sentiment": ["负面", "中性", "正面"][prediction]}
|