File size: 1,357 Bytes
dd4e7ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from typing import List

app = FastAPI(
    title="Indonesian Sentiment API",
    version="1.0"
)

MODEL_NAME = "taufiqdp/indonesian-sentiment"

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_NAME,
    trust_remote_code=True
)
model = AutoModelForSequenceClassification.from_pretrained(
    MODEL_NAME,
    trust_remote_code=True
)
model.eval()

labels = ["negatif", "netral", "positif"]

# 🔥 ROOT ENDPOINT (WAJIB ADA)
@app.get("/")
def root():
    return {"status": "ok", "message": "Sentiment API is running"}

# Schema batch
class InputBatch(BaseModel):
    texts: List[str]

@app.post("/predict-batch")
def predict_batch(data: InputBatch):
    results = []

    inputs = tokenizer(
        data.texts,
        return_tensors="pt",
        truncation=True,
        padding=True,
        max_length=128
    )

    with torch.no_grad():
        outputs = model(**inputs)

    probs = torch.softmax(outputs.logits, dim=1)
    preds = torch.argmax(probs, dim=1)

    for text, idx, prob in zip(data.texts, preds, probs):
        results.append({
            "text": text,
            "sentiment": labels[idx],
            "score": round(prob[idx].item(), 4)
        })

    return {"results": results}