File size: 4,255 Bytes
5f12713 b8b1a4d 36cc551 057a9dd 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 b8b1a4d 5f12713 | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | # 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"
} |