Malruwan commited on
Commit
4d632b4
·
verified ·
1 Parent(s): fc31109

Update sentiment_api.py

Browse files
Files changed (1) hide show
  1. 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
- # Load model and tokenizer once at startup
7
- model_name = "tabularisai/multilingual-sentiment-analysis"
8
- tokenizer = AutoTokenizer.from_pretrained(model_name)
9
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
10
-
11
- app = FastAPI()
12
-
13
- # Sentiment map
14
- sentiment_map = {
15
- 0: "Very Negative",
16
- 1: "Negative",
17
- 2: "Neutral",
18
- 3: "Positive",
19
- 4: "Very Positive"
20
- }
21
-
22
- # Request body schema
23
- class ReviewRequest(BaseModel):
24
- text: str
25
-
26
- @app.post("/predict-sentiment")
27
- def predict_sentiment(review: ReviewRequest):
28
- inputs = tokenizer(review.text, return_tensors="pt", truncation=True, padding=True, max_length=512)
29
- with torch.no_grad():
30
- outputs = model(**inputs)
31
- probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
32
- predicted_label = torch.argmax(probabilities, dim=-1).item()
33
- sentiment = sentiment_map[predicted_label]
34
- return {"text": review.text, "sentiment": sentiment}
 
 
 
 
 
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}