Spaces:
Runtime error
Runtime error
Update sentiment_api.py
Browse files- sentiment_api.py +38 -34
sentiment_api.py
CHANGED
|
@@ -1,34 +1,38 @@
|
|
| 1 |
-
from fastapi import FastAPI, Request
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
-
import torch
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
import torch
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Set a custom cache directory
|
| 8 |
+
os.environ["TRANSFORMERS_CACHE"] = "./hf_cache"
|
| 9 |
+
|
| 10 |
+
# Load model and tokenizer once at startup
|
| 11 |
+
model_name = "tabularisai/multilingual-sentiment-analysis"
|
| 12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 13 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
| 14 |
+
|
| 15 |
+
app = FastAPI()
|
| 16 |
+
|
| 17 |
+
# Sentiment map
|
| 18 |
+
sentiment_map = {
|
| 19 |
+
0: "Very Negative",
|
| 20 |
+
1: "Negative",
|
| 21 |
+
2: "Neutral",
|
| 22 |
+
3: "Positive",
|
| 23 |
+
4: "Very Positive"
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# Request body schema
|
| 27 |
+
class ReviewRequest(BaseModel):
|
| 28 |
+
text: str
|
| 29 |
+
|
| 30 |
+
@app.post("/predict-sentiment")
|
| 31 |
+
def predict_sentiment(review: ReviewRequest):
|
| 32 |
+
inputs = tokenizer(review.text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
| 33 |
+
with torch.no_grad():
|
| 34 |
+
outputs = model(**inputs)
|
| 35 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 36 |
+
predicted_label = torch.argmax(probabilities, dim=-1).item()
|
| 37 |
+
sentiment = sentiment_map[predicted_label]
|
| 38 |
+
return {"text": review.text, "sentiment": sentiment}
|