paac_api / app.py
Dimrror's picture
Update app.py
36cc551 verified
Raw History Blame Contribute Delete
4.26 kB
# app.py
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import numpy as np
from contextlib import asynccontextmanager
# -------------------------
# CONFIG
# -------------------------
# Use official BERT GoEmotions from Hugging Face Hub
MODEL_NAME = "monologg/bert-base-cased-goemotions-original"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
# -------------------------
# FastAPI lifespan (startup/shutdown)
# -------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
print("Loading BERT GoEmotions model from Hugging Face Hub...")
global tokenizer, model, LABELS
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
model.eval()
LABELS = model.config.id2label
print(f"Model loaded successfully from: {MODEL_NAME}")
yield
print("API shutting down...")
app = FastAPI(lifespan=lifespan)
# -------------------------
# Emotion → Flower mapping
# -------------------------
GOEMO_TO_FLOWERS = {
# Positive / Warm
"admiration": "Admiration",
"amusement": "Amusement",
"approval": "Approval",
"caring": "Caring",
"curiosity": "Curiosity",
"desire": "Desire",
"excitement": "Excitement",
"gratitude": "Gratitude",
"joy": "Joy",
"love": "Love",
"optimism": "Optimism",
"pride": "Pride",
"relief": "Relief",
"surprise": "Surprise",
# Neutral / Complex
"realization": "Realization",
"confusion": "Confusion",
# Negative / Heavy
"anger": "Anger",
"annoyance": "Annoyance",
"disapproval": "Disapproval",
"disgust": "Disgust",
"embarrassment": "Embarrassment",
"fear": "Fear",
"grief": "Grief",
"nervousness": "Nervousness",
"remorse": "Remorse",
"sadness": "Sadness",
"disappointment": "Disappointment"
}
FLOWER_EMOTIONS = sorted(set(GOEMO_TO_FLOWERS.values()))
# -------------------------
# Request schema
# -------------------------
class TextIn(BaseModel):
text: str
threshold: float = 0.3
top_k: int = 3
# -------------------------
# Prediction endpoint
# -------------------------
@app.post("/predict_emotion")
async def predict_emotion(data: TextIn):
text = data.text.strip()
if not text:
return {"error": "Empty text input."}
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=512
)
with torch.no_grad():
logits = model(**inputs).logits
probs = torch.sigmoid(logits).cpu()[0].numpy()
# Get indices above threshold or fallback to top_k
indices = np.where(probs > data.threshold)[0]
if len(indices) == 0:
indices = np.argsort(probs)[-data.top_k:][::-1]
# Aggregate by flower emotion
flower_scores = {}
for idx in indices:
label = LABELS[idx]
score = float(probs[idx])
flower = GOEMO_TO_FLOWERS.get(label, "Neutral/Unknown")
flower_scores[flower] = max(score, flower_scores.get(flower, 0))
results = [{"flower_emotion": flower, "score": score} for flower, score in flower_scores.items()]
results.sort(key=lambda x: x["score"], reverse=True)
results = results[:data.top_k]
dominant = results[0] if results else {"flower_emotion": "Neutral/Unknown", "score": 0.0}
return {
"text": text,
"dominant_emotion": dominant["flower_emotion"],
"dominant_score": dominant["score"],
"all_emotions": results,
"threshold_used": data.threshold
}
# -------------------------
# List flower emotions
# -------------------------
@app.get("/flower_emotions")
async def get_flower_emotions():
return {"available_emotions": FLOWER_EMOTIONS, "count": len(FLOWER_EMOTIONS)}
# -------------------------
# Root endpoint
# -------------------------
@app.get("/")
async def root():
return {
"message": "BERT GoEmotions API (Online Hub)",
"model_source": MODEL_NAME,
"flower_emotions_count": len(FLOWER_EMOTIONS),
"status": "running"
}