zypernike commited on
Commit
6d516e8
·
verified ·
1 Parent(s): b4994a9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 UNTUK HF)
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
+ inputs = tokenizer(
38
+ data.texts,
39
+ return_tensors="pt",
40
+ truncation=True,
41
+ padding=True,
42
+ max_length=128
43
+ )
44
+
45
+ with torch.no_grad():
46
+ outputs = model(**inputs)
47
+
48
+ probs = torch.softmax(outputs.logits, dim=1)
49
+ preds = torch.argmax(probs, dim=1)
50
+
51
+ results = []
52
+ for text, idx, prob in zip(data.texts, preds, probs):
53
+ results.append({
54
+ "text": text,
55
+ "sentiment": labels[idx],
56
+ "score": round(prob[idx].item(), 4)
57
+ })
58
+
59
+ return {"results": results}