File size: 1,445 Bytes
e88eaf5 cb3234d e88eaf5 0d5773a e88eaf5 cb3234d e88eaf5 |
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 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
# Inisialisasi model dan tokenizer
model_name = "w11wo/indonesian-roberta-base-sentiment-classifier"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
# Inisialisasi FastAPI
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Bisa disesuaikan dengan daftar asal yang diizinkan
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Model request body
class TextInput(BaseModel):
text: str
# Fungsi untuk analisis sentimen
def predict_sentiment(text):
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
outputs = model(**inputs)
scores = outputs.logits[0].detach().numpy()
predictions = torch.nn.functional.softmax(torch.tensor(scores), dim=0)
sentiment = torch.argmax(predictions).item()
return sentiment, predictions[sentiment].item()
# Endpoint untuk analisis sentimen
@app.post("/predict")
async def predict(input: TextInput):
sentiment, confidence = predict_sentiment(input.text)
return {"sentiment": sentiment, "confidence": confidence}
# Endpoint root
@app.get("/")
async def read_root():
return {"message": "Sentiment Analysis API"}
|