Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
import torch
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
app = FastAPI(
|
| 8 |
+
title="Indonesian Sentiment API",
|
| 9 |
+
version="1.0"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
MODEL_NAME = "taufiqdp/indonesian-sentiment"
|
| 13 |
+
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 15 |
+
MODEL_NAME,
|
| 16 |
+
trust_remote_code=True
|
| 17 |
+
)
|
| 18 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 19 |
+
MODEL_NAME,
|
| 20 |
+
trust_remote_code=True
|
| 21 |
+
)
|
| 22 |
+
model.eval()
|
| 23 |
+
|
| 24 |
+
labels = ["negatif", "netral", "positif"]
|
| 25 |
+
|
| 26 |
+
# 🔥 ROOT ENDPOINT (WAJIB ADA)
|
| 27 |
+
@app.get("/")
|
| 28 |
+
def root():
|
| 29 |
+
return {"status": "ok", "message": "Sentiment API is running"}
|
| 30 |
+
|
| 31 |
+
# Schema batch
|
| 32 |
+
class InputBatch(BaseModel):
|
| 33 |
+
texts: List[str]
|
| 34 |
+
|
| 35 |
+
@app.post("/predict-batch")
|
| 36 |
+
def predict_batch(data: InputBatch):
|
| 37 |
+
results = []
|
| 38 |
+
|
| 39 |
+
inputs = tokenizer(
|
| 40 |
+
data.texts,
|
| 41 |
+
return_tensors="pt",
|
| 42 |
+
truncation=True,
|
| 43 |
+
padding=True,
|
| 44 |
+
max_length=128
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
outputs = model(**inputs)
|
| 49 |
+
|
| 50 |
+
probs = torch.softmax(outputs.logits, dim=1)
|
| 51 |
+
preds = torch.argmax(probs, dim=1)
|
| 52 |
+
|
| 53 |
+
for text, idx, prob in zip(data.texts, preds, probs):
|
| 54 |
+
results.append({
|
| 55 |
+
"text": text,
|
| 56 |
+
"sentiment": labels[idx],
|
| 57 |
+
"score": round(prob[idx].item(), 4)
|
| 58 |
+
})
|
| 59 |
+
|
| 60 |
+
return {"results": results}
|