Spaces:
Sleeping
Sleeping
File size: 2,400 Bytes
3d1fcc8 8eeda40 3d1fcc8 8eeda40 3d1fcc8 | 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 62 63 64 | """
IndoBERT Financial Sentiment API β Hugging Face Space
Loads the finetuned model from reehandn/model-financial-sentiment
and serves predictions via REST API.
"""
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
import os
app = FastAPI(title="IndoBERT Financial Sentiment API")
# βββ Load model from HF repo βββββββββββββββββββββββββββββββββββββββββββββββββ
MODEL_ID = os.getenv("MODEL_ID", "reehandn/model-financial-sentiment")
HF_TOKEN = os.getenv("HF_TOKEN", None) # Secret di Space settings
print(f"[Init] Loading model: {MODEL_ID}")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID, token=HF_TOKEN)
model.eval()
print("[Init] Model loaded successfully!")
# Label map: 0=bearish/negative, 1=neutral, 2=bullish/positive
LABEL_MAP = {0: "negative", 1: "neutral", 2: "positive"}
# βββ API schema βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class PredictRequest(BaseModel):
inputs: List[str]
# βββ Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/predict")
async def predict(req: PredictRequest):
"""Classify sentiment for a batch of texts."""
results = []
for text in req.inputs:
encoded = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=512,
padding=True,
)
with torch.no_grad():
outputs = model(**encoded)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]
top_idx = torch.argmax(probs).item()
top_score = probs[top_idx].item()
results.append({
"label": LABEL_MAP.get(top_idx, f"LABEL_{top_idx}"),
"score": round(top_score, 4),
})
return results
@app.get("/health")
async def health():
return {"status": "ok", "model": MODEL_ID}
|