ModelA_API / app.py
Miruzen's picture
Rename App.py to app.py
aba9560 verified
raw
history blame
2.81 kB
# app.py
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
import torch
app = FastAPI(title="Forex Sentiment API", version="1.0")
# ===============================
# Load Models
# ===============================
finbert_name = "ProsusAI/finbert"
longformer_name = "Miruzen/LongFormer_Skripsi"
device = 0 if torch.cuda.is_available() else -1
print("πŸ“₯ Loading FinBERT model...")
finbert = pipeline("text-classification",
model=finbert_name,
tokenizer=finbert_name,
return_all_scores=True,
device=device)
print("πŸ“₯ Loading LongFormer model...")
longformer = pipeline("text-classification",
model=longformer_name,
tokenizer=longformer_name,
return_all_scores=True,
device=device)
# ===============================
# Input Schema
# ===============================
class InputData(BaseModel):
title: str | None = None
content: str | None = None
# ===============================
# Helper Functions
# ===============================
def extract_scores(predictions):
"""Convert HF model output into {positive, neutral, negative} dict."""
scores = {"positive": 0.0, "neutral": 0.0, "negative": 0.0}
for item in predictions[0]:
label = item["label"].lower()
if "pos" in label:
scores["positive"] = item["score"]
elif "neg" in label:
scores["negative"] = item["score"]
elif "neu" in label:
scores["neutral"] = item["score"]
dominant = max(scores, key=scores.get)
return {"label": dominant, "scores": scores}
# ===============================
# Main Endpoint
# ===============================
@app.post("/analyze")
def analyze(data: InputData):
result = {}
if data.title:
finbert_out = finbert(data.title)
result["title"] = extract_scores(finbert_out)
if data.content:
longformer_out = longformer(data.content)
result["content"] = extract_scores(longformer_out)
# Gabungkan menjadi mood_score sederhana
mood_score = (
result.get("title", {}).get("scores", {}).get("positive", 0)
+ result.get("content", {}).get("scores", {}).get("positive", 0)
- result.get("title", {}).get("scores", {}).get("negative", 0)
- result.get("content", {}).get("scores", {}).get("negative", 0)
)
return {
"mood_score": mood_score,
"details": result,
"status": "ok"
}
@app.get("/")
def root():
return {"message": "Forex Sentiment API active!"}