Spaces:
Sleeping
Sleeping
Create sentimental.py
Browse files- sentimental.py +33 -0
sentimental.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
+
|
| 6 |
+
# === Загрузка модели ===
|
| 7 |
+
MODEL_NAME = "nlptown/bert-base-multilingual-uncased-sentiment"
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 9 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 10 |
+
model.eval()
|
| 11 |
+
|
| 12 |
+
# === FastAPI приложение ===
|
| 13 |
+
app = FastAPI(title="Sentiment Analysis API")
|
| 14 |
+
|
| 15 |
+
# === Схема запроса ===
|
| 16 |
+
class TextRequest(BaseModel):
|
| 17 |
+
text: str
|
| 18 |
+
|
| 19 |
+
# === Логика сентимента ===
|
| 20 |
+
def analyze_sentiment(message: str) -> float:
|
| 21 |
+
inputs = tokenizer(message, return_tensors="pt", truncation=True)
|
| 22 |
+
with torch.no_grad():
|
| 23 |
+
logits = model(**inputs).logits
|
| 24 |
+
probs = torch.softmax(logits, dim=-1)
|
| 25 |
+
stars = torch.argmax(probs, dim=-1).item() + 1 # от 1 до 5
|
| 26 |
+
sentiment = (stars - 3) * 2.5 # нормируем -5..+5
|
| 27 |
+
return round(sentiment, 2)
|
| 28 |
+
|
| 29 |
+
# === Эндпоинт API ===
|
| 30 |
+
@app.post("/sentiment")
|
| 31 |
+
def sentiment(request: TextRequest):
|
| 32 |
+
score = analyze_sentiment(request.text)
|
| 33 |
+
return {"sentiment_score": score}
|