Spaces:
Sleeping
Sleeping
File size: 19,265 Bytes
bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 628ca9d bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a 765d7a0 f349c1a 1bd381a f349c1a 765d7a0 f349c1a 765d7a0 f349c1a 765d7a0 f349c1a 765d7a0 f349c1a 765d7a0 1bd381a 765d7a0 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 017633f bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 f349c1a bf511a8 | 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | """
FastAPI backend for Gairaigo Map.
Endpoints:
GET /health - liveness check
GET /languages - returns the 3 classifiable languages
POST /predict - classifies a katakana word
POST /emotion - detects emotion from plain text, returns music list + loanwords
Usage:
uvicorn main:app --reload --port 8000
"""
import re
import numpy as np
import joblib
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, field_validator
from transformers import pipeline
# โโ Paths โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
BASE_DIR = Path(__file__).parent
MODELS_DIR = BASE_DIR.parent / "models"
# Fallback for Docker where /home/user/app is the working root
if not MODELS_DIR.exists():
MODELS_DIR = Path("/home/user/app/models")
MODEL_PATH = MODELS_DIR / "model.joblib"
VECTORIZER_PATH = MODELS_DIR / "vectorizer.joblib"
ENCODER_PATH = MODELS_DIR / "encoder.joblib"
KATAKANA_RE = re.compile(r"^[\u30A0-\u30FF\u30FC\u30FB\u30FE\u30FD]+$")
def is_katakana(text: str) -> bool:
return bool(KATAKANA_RE.match(text.strip()))
# โโ Language metadata (SVM classifier) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
LANGUAGE_META = {
"English": {"iso2": "GB", "country": "United Kingdom", "color": "#4a90d9"},
"French": {"iso2": "FR", "country": "France", "color": "#e85d5d"},
"German": {"iso2": "DE", "country": "Germany", "color": "#f0a500"},
}
# โโ Emotion โ Music playlist (multiple songs per emotion for variety) โโโโโโโโโโ
# All video IDs verified via Wikipedia / official sources
EMOTION_MUSIC: dict[str, list[dict]] = {
"joy": [
{"title": "ATARASHII GAKKO! - Que Sera Sera", "video_id": "0S1-b9xGQac"},
{"title": "Wonderland x Showtime - Kyoufuu All Back", "video_id": "nq_x3D0_lgw"},
{"title": "Sumika - Fiction", "video_id": "IKHGAuNaGuA"},
{"title": "ATARASHII GAKKO! - OTONABLUE", "video_id": "l446hUqQ7GY"},
{"title": "Wonderland x Showtime - SEIBAITAAAAAASU!", "video_id": "w0lpuKNZRQ0"},
{"title": "Creepy Nuts - Bling-Bang-Bang-Born", "video_id": "mLW35YMzELE"},
{"title": "Wonderland x Showtime - Taiyoukei Disco", "video_id": "oA6aCY4bMg4"},
{"title": "Gen Hoshino - Koi", "video_id": "jhOVibLEDhA"},
{"title": "Yumi Arai - Rouge no Dengon", "video_id": "MH-P4mXvDPE"},
],
"sadness": [
{"title": "ZONE - Kimi ga Kureta Mono", "video_id": "Of36Qh7WLSQ"},
{"title": "YOSHIKI - Red Swan", "video_id": "r1XE8ON8fos"},
{"title": "Galileo Galilei - Aoi Shiori", "video_id": "T3bxbVGWy5k"},
{"title": "seven oops - Orange", "video_id": "nf-L5R8U-Q0"},
{"title": "DAOKO x Kenshi Yonezu - Fireworks", "video_id": "-tKVN2mAKRI"},
{"title": "Yorushika - Say It", "video_id": "F64yFFnZfkI"},
{"title": "Kenshi Yonezu - Lemon", "video_id": "SX_ViT4Ra7k"},
{"title": "Yoh Kamiyama - Irokousui", "video_id": "kQYLHjgUh_g"},
],
"anger": [
{"title": "Ado - Usseewa", "video_id": "Qp3b-RXtz4w"},
{"title": "Neru - Lost One's Weeping", "video_id": "U1aS62Juz70"},
{"title": "Hige Dandism - Cry Baby", "video_id": "O1bhZgkC4Gw"},
{"title": "Minami - Crying for Rain", "video_id": "0YF8vecQWYs"},
{"title": "Eve - Dramaturgy", "video_id": "jJzw1h5CR-I"},
{"title": "Kenshi Yonezu - Kick Back", "video_id": "M2cckDmNLMI"},
],
"fear": [
{"title": "TK - Unravel", "video_id": "Fve_lHIPa-I"},
{"title": "Nightcord at 25:00 x KAITO - Bakenohana", "video_id": "UFRIsspP9UE"},
{"title": "ATARASHII GAKKO! - Tokyo Calling", "video_id": "pHMH408ltEM"},
{"title": "Nightcord at 25:00 x KAITO - Heat Abnormal", "video_id": "ToqKNyZi2NQ"},
{"title": "Yuzu - Hyori Ittai", "video_id": "eKoD2CRr_KA"},
{"title": "Nightcord at 25:00 - Bug", "video_id": "2Ii7UBMxWVw"},
{"title": "RADWIMPS - Nandemonaiya", "video_id": "n89SKAymNfA"},
{"title": "sakanaction - Arukuaround", "video_id": "cADu9rtlZGQ"},
],
"surprise": [
{"title": "YOASOBI - Idol", "video_id": "ZRtdQ81jPUQ"},
{"title": "Ado - Buriki no Dance", "video_id": "iL7uoLCbJoc"},
{"title": "Ado - New Genesis", "video_id": "1FliVTcX8bQ"},
{"title": "RADWIMPS - Grand Escape", "video_id": "epQGR34yiTY"},
],
"disgust": [
{"title": "Nightcord at 25:00 - Bocca della Veritร ", "video_id": "ZjNUJUgyoOw"},
{"title": "Ado - Readymade", "video_id": "jg09lNupc1s"},
{"title": "Eve - Literary Nonsense", "video_id": "OskXF3s0UT8"},
],
"neutral": [
{"title": "Vaundy - Odoriko", "video_id": "7HgJIAUtICU"},
{"title": "Hanae - Kamisama Hajimemashita", "video_id": "gZaelu4lieE"},
{"title": "Fuji Kaze - Matsuri", "video_id": "NwOvu-j_WjY"},
{"title": "Tomofumi Tanizawa - Kimi ni Todoke", "video_id": "9o7tKXUjC6E"},
{"title": "ATARASHII GAKKO! - Dounimo Tomaranai", "video_id": "59bnq4wlGx8"},
{"title": "Yorushika - Just a Sunny Day for You", "video_id": "-VKIqrvVOpo"},
{"title": "natori - Overdose", "video_id": "H08YWE4CIFQ"},
{"title": "Mitchie M - Tokugawa Cup Noodle Kinshirei", "video_id": "jPXAgWkqbo4"},
{"title": "Homecomings - Cakes", "video_id": "u1A53wFN9A0"},
],
}
# โโ Emotion โ curated loanwords โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
EMOTION_LOANWORDS: dict[str, list[dict]] = {
"joy": [
{"katakana": "ใซใผใใใซ", "meaning": "carnival", "language": "English", "iso2": "GB"},
{"katakana": "ใใงในใใฃใใซ", "meaning": "festival", "language": "English", "iso2": "GB"},
{"katakana": "ใใณใน", "meaning": "dance", "language": "English", "iso2": "GB"},
{"katakana": "ใทใงใผใญ", "meaning": "choro; chorinho; style of Brazilian popular music", "language": "Portuguese", "iso2": "PT"},
{"katakana": "ใซในใใฉ", "meaning": "castella (type of sponge cake)", "language": "Portuguese", "iso2": "PT"},
{"katakana": "ใใฌใจ", "meaning": "ballet", "language": "French", "iso2": "FR"},
{"katakana": "ใทใฃใณใฝใณ", "meaning": "chanson; French song", "language": "French", "iso2": "FR"},
{"katakana": "ใใงใใ", "meaning": "fรชte; festival; celebration", "language": "French", "iso2": "FR"},
],
"sadness": [
{"katakana": "ใในใฟใซใธใผ", "meaning": "nostalgia", "language": "French", "iso2": "FR"},
{"katakana": "ใกใฉใณใณใชใผ", "meaning": "melancholy", "language": "French", "iso2": "FR"},
{"katakana": "ใขใใฅใผ", "meaning": "adieu; goodbye", "language": "French", "iso2": "FR"},
{"katakana": "ใใณใ", "meaning": "love of a knight for a courtly lady (upon which he is unable to act)", "language": "German", "iso2": "DE"},
{"katakana": "ใใญใคใฉใคใณ", "meaning": "miss (German title for an unmarried woman)", "language": "German", "iso2": "DE"},
{"katakana": "ใซใใ", "meaning": "raincoat", "language": "Portuguese", "iso2": "PT"},
{"katakana": "ใญใณใชใผ", "meaning": "lonely", "language": "English", "iso2": "GB"},
{"katakana": "ใใซใผใน", "meaning": "blues (music genre)", "language": "English", "iso2": "GB"},
],
"anger": [
{"katakana": "ใใชใใฃใฎ", "meaning": "axe kick; ax kick", "language": "Korean", "iso2": "KR"},
{"katakana": "ใตใณใ", "meaning": "sanda; sanshou; Chinese boxing; Chinese kickboxing", "language": "Chinese", "iso2": "CN"},
{"katakana": "ใใญใซ", "meaning": "terror; terrorism", "language": "German", "iso2": "DE"},
{"katakana": "ในใใฉใคใญ", "meaning": "strike (labor action)", "language": "English", "iso2": "GB"},
{"katakana": "ใใญใในใ", "meaning": "protest", "language": "English", "iso2": "GB"},
{"katakana": "ใฌใธในใฟใณใน", "meaning": "resistance (movement)", "language": "French", "iso2": "FR"},
{"katakana": "ใใใซ", "meaning": "battle", "language": "English", "iso2": "GB"},
{"katakana": "ใใฏใผ", "meaning": "power", "language": "English", "iso2": "GB"},
],
"fear": [
{"katakana": "ใใฏใผใซ", "meaning": "black; dark", "language": "French", "iso2": "FR"},
{"katakana": "ใจใใฉใณใผ", "meaning": "stranger; outsider; foreigner", "language": "French", "iso2": "FR"},
{"katakana": "ใใญใซ", "meaning": "terror; terrorism", "language": "German", "iso2": "DE"},
{"katakana": "ใใใดใฎใผ", "meaning": "false rumor; false alarm; misinformation", "language": "German", "iso2": "DE"},
{"katakana": "ใดใผในใ", "meaning": "ghost", "language": "English", "iso2": "GB"},
{"katakana": "ใใฉใผ", "meaning": "horror", "language": "English", "iso2": "GB"},
{"katakana": "ใใใใฏ", "meaning": "panic", "language": "English", "iso2": "GB"},
{"katakana": "ใในใใชใผ", "meaning": "mystery", "language": "English", "iso2": "GB"},
],
"surprise": [
{"katakana": "ใฒใชใฉใฉใคใ", "meaning": "surprise concert", "language": "English", "iso2": "GB"},
{"katakana": "ในใฉใคใใณใ", "meaning": "sleight of hand (e.g. in magic tricks)", "language": "English", "iso2": "GB"},
{"katakana": "ใใธใใฏ", "meaning": "magic", "language": "English", "iso2": "GB"},
{"katakana": "ใคใชใฅใผใธใงใณ", "meaning": "illusion", "language": "English", "iso2": "GB"},
{"katakana": "ใตใผใซใน", "meaning": "circus", "language": "English", "iso2": "GB"},
{"katakana": "ในใใฏใฟใฏใซ", "meaning": "spectacle", "language": "French", "iso2": "FR"},
{"katakana": "ใใชใฅใใ", "meaning": "brut; dry sparkling wine", "language": "French", "iso2": "FR"},
{"katakana": "ใตใใฉใคใบ", "meaning": "surprise", "language": "English", "iso2": "GB"},
],
"disgust": [
{"katakana": "ใใงใฆใใฆใ", "meaning": "stinky tofu; fermented tofu", "language": "Chinese", "iso2": "CN"},
{"katakana": "ใทใใฏใใฆใน", "meaning": "sick building; building which causes people to feel unwell", "language": "English", "iso2": "GB"},
{"katakana": "ใใญใทใใฏ", "meaning": "toxic", "language": "English", "iso2": "GB"},
{"katakana": "ใในใใทใฅใผใ", "meaning": "garbage chute; trash chute", "language": "English", "iso2": "GB"},
{"katakana": "ใใคใบใณ", "meaning": "poison", "language": "English", "iso2": "GB"},
{"katakana": "ในใญใฃใณใใซ", "meaning": "scandal", "language": "English", "iso2": "GB"},
{"katakana": "ใใฌใใฃใ", "meaning": "negative", "language": "English", "iso2": "GB"},
{"katakana": "ใดใ", "meaning": "rubbish; trash; garbage", "language": "English", "iso2": "GB"},
],
"neutral": [
{"katakana": "ใขใซใใคใฟใผ", "meaning": "part-time worker; part-timer", "language": "German", "iso2": "DE"},
{"katakana": "ใใณใคใณ", "meaning": "Pinyin (Chinese romanization system)", "language": "Chinese", "iso2": "CN"},
{"katakana": "ในใฑใธใฅใผใซ", "meaning": "schedule", "language": "English", "iso2": "GB"},
{"katakana": "ใทในใใ ", "meaning": "system", "language": "English", "iso2": "GB"},
{"katakana": "ใใญใฅใกใณใ", "meaning": "document", "language": "English", "iso2": "GB"},
{"katakana": "ใใใใฏใผใฏ", "meaning": "network", "language": "English", "iso2": "GB"},
{"katakana": "ใใใธใกใณใ", "meaning": "management", "language": "English", "iso2": "GB"},
{"katakana": "ในใฟใณใใผใ", "meaning": "standard", "language": "English", "iso2": "GB"},
],
}
# โโ Startup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
artifacts: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
for path in (MODEL_PATH, VECTORIZER_PATH, ENCODER_PATH):
if not path.exists():
raise RuntimeError(f"Model artifact not found: {path}")
artifacts["model"] = joblib.load(MODEL_PATH)
artifacts["vectorizer"] = joblib.load(VECTORIZER_PATH)
artifacts["encoder"] = joblib.load(ENCODER_PATH)
artifacts["emotion"] = pipeline(
"text-classification",
model="j-hartmann/emotion-english-distilroberta-base",
top_k=1,
)
print("โ Model artifacts loaded")
print("โ Emotion classifier loaded")
yield
artifacts.clear()
# โโ App โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
app = FastAPI(title="Gairaigo Map API", version="2.0.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"http://127.0.0.1:5173",
"https://kotabi.vercel.app",
],
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
# โโ Schemas โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class PredictRequest(BaseModel):
word: str
@field_validator("word")
@classmethod
def must_be_katakana(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("Word must not be empty.")
if not is_katakana(v):
raise ValueError("Input must be katakana (e.g. ใณใผใใผ).")
return v
class LanguageResult(BaseModel):
language: str
country: str
iso2: str
confidence: float
color: str
class PredictResponse(BaseModel):
word: str
prediction: LanguageResult
all_scores: list[LanguageResult]
class EmotionRequest(BaseModel):
text: str
@field_validator("text")
@classmethod
def must_not_be_empty(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("Text must not be empty.")
return v
class MusicEntry(BaseModel):
title: str
video_id: str
class LoanwordResult(BaseModel):
katakana: str
meaning: str
language: str
iso2: str
class EmotionResponse(BaseModel):
text: str
emotion: str
music_list: list[MusicEntry] # full playlist โ frontend cycles through these
loanwords: list[LoanwordResult]
# โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def softmax(scores: np.ndarray) -> np.ndarray:
exp_scores = np.exp(scores - np.max(scores))
return exp_scores / exp_scores.sum()
def classify(word: str) -> PredictResponse:
model = artifacts["model"]
vectorizer = artifacts["vectorizer"]
encoder = artifacts["encoder"]
X = vectorizer.transform([word])
decision_scores = model.decision_function(X)[0]
confidences = softmax(decision_scores)
classes = encoder.classes_
all_scores = [
LanguageResult(
language=classes[i],
country=LANGUAGE_META[classes[i]]["country"],
iso2=LANGUAGE_META[classes[i]]["iso2"],
confidence=round(float(confidences[i]), 4),
color=LANGUAGE_META[classes[i]]["color"],
)
for i in range(len(classes))
]
all_scores.sort(key=lambda r: r.confidence, reverse=True)
return PredictResponse(word=word, prediction=all_scores[0], all_scores=all_scores)
# โโ Routes โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
@app.get("/health", tags=["Meta"])
def health():
return {"status": "ok", "model_loaded": bool(artifacts)}
@app.get("/languages", tags=["Meta"])
def get_languages():
return {lang: meta for lang, meta in LANGUAGE_META.items()}
@app.post("/predict", response_model=PredictResponse, tags=["Classification"])
def predict(body: PredictRequest):
try:
return classify(body.word)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/emotion", response_model=EmotionResponse, tags=["Emotion"])
def detect_emotion(body: EmotionRequest):
"""
Detect emotion from plain English text.
Returns the detected emotion, a playlist of matching Japanese songs, and related loanwords.
The frontend can cycle through music_list to let users skip to the next song.
"""
try:
result = artifacts["emotion"](body.text)
label: str = result[0][0]["label"].lower()
if label not in EMOTION_MUSIC:
label = "neutral"
music_list = [MusicEntry(**m) for m in EMOTION_MUSIC[label]]
loanwords = [LoanwordResult(**w) for w in EMOTION_LOANWORDS[label]]
return EmotionResponse(
text=body.text,
emotion=label,
music_list=music_list,
loanwords=loanwords,
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
|