Spaces:
Sleeping
Sleeping
File size: 6,536 Bytes
f0a4b63 aa1a383 f0a4b63 96a4d11 aa1a383 96a4d11 f0a4b63 aa1a383 f0a4b63 aa1a383 f0a4b63 | 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 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import sys
import os
import pandas as pd
import numpy as np
import threading
# ๊ฐ์ ํด๋์ logic.py ์ํฌํธ๋ฅผ ์ํด ๊ฒฝ๋ก ์ถ๊ฐ
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import logic
app = FastAPI(title="K-Recipe2Vec API")
# CORS ์ค์
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Request Models ---
class IngredientRequest(BaseModel):
recipe_id: int
target: List[str]
stopwords: List[str] = []
w_w2v: float = 0.5
w_d2v: float = 0.5
w_method: float = 0.0
w_cat: float = 0.0
class CustomContextRequest(BaseModel):
context_ings: List[str]
target: List[str]
stopwords: List[str] = []
w_w2v: float = 0.5
w_d2v: float = 0.5
excluded: List[str] = []
# --- Startup ---
@app.on_event("startup")
def startup_event():
# ๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์์ ๋ชจ๋ธ ๋ก๋ฉ ์์ (์ฑ ์์์ ๋ง์ง ์์)
threading.Thread(target=logic.load_resources).start()
# --- ๋ถ์ฉ์ด ์บ์ ๋ฐ ํํฐ๋ง ---
_stopwords_cache = None
def get_stopwords():
"""๋ถ์ฉ์ด ๋ชฉ๋ก์ ์บ์ํ์ฌ ๋ฐํ"""
global _stopwords_cache
if _stopwords_cache is None:
try:
_stopwords_cache = set(logic.load_global_stopwords())
except:
_stopwords_cache = set()
return _stopwords_cache
def filter_ingredients(ingredients_list):
"""์ฌ๋ฃ ๋ชฉ๋ก์์ ๋ถ์ฉ์ด ์ ๊ฑฐ"""
stopwords = get_stopwords()
if not stopwords:
return ingredients_list
return [ing for ing in ingredients_list if ing not in stopwords]
# --- Endpoints ---
@app.get("/")
def health_check():
# ๋ชจ๋ธ ๋ก๋ฉ ์ํ ํ์ธ
status = "loading" if logic.df is None else "ok"
return {"status": status, "service": "K-Recipe2Vec API"}
@app.get("/recipes")
def list_recipes(limit: int = 50, offset: int = 0):
"""์ ์ฒด ๋ ์ํผ ๋ชฉ๋ก ์กฐํ (ํ์ด์ง๋ค์ด์
)"""
logic.ensure_initialized()
try:
total = len(logic.df)
subset = logic.df.iloc[offset:offset+limit][['๋ ์ํผ์ผ๋ จ๋ฒํธ', '์๋ฆฌ๋ช
', '์ฌ๋ฃํ ํฐ', '์๋ฆฌ๋ฐฉ๋ฒ๋ณ๋ช
', '์๋ฆฌ์ข
๋ฅ๋ณ๋ช
_์ธ๋ถํ']]
output = []
for _, row in subset.iterrows():
output.append({
"id": int(row['๋ ์ํผ์ผ๋ จ๋ฒํธ']),
"name": row['์๋ฆฌ๋ช
'],
"ingredients": filter_ingredients(row['์ฌ๋ฃํ ํฐ']),
"method": row['์๋ฆฌ๋ฐฉ๋ฒ๋ณ๋ช
'],
"category": row['์๋ฆฌ์ข
๋ฅ๋ณ๋ช
_์ธ๋ถํ']
})
return {"total": total, "recipes": output}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/recipes/search")
def search_recipes(q: str):
"""์๋ฆฌ๋ช
์ผ๋ก ๋ ์ํผ ๊ฒ์"""
logic.ensure_initialized() # ๋ก๋ฉ ๋๊ธฐ
if not q: return []
try:
mask = logic.df['์๋ฆฌ๋ช
'].str.contains(q, case=False, na=False)
results = logic.df.loc[mask, ['๋ ์ํผ์ผ๋ จ๋ฒํธ', '์๋ฆฌ๋ช
', '์ฌ๋ฃํ ํฐ']].head(20)
output = []
for _, row in results.iterrows():
output.append({
"id": int(row['๋ ์ํผ์ผ๋ จ๋ฒํธ']),
"name": row['์๋ฆฌ๋ช
'],
"ingredients": filter_ingredients(row['์ฌ๋ฃํ ํฐ'])
})
return output
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/recipes/{recipe_id}")
def get_recipe_detail(recipe_id: int):
"""๋ ์ํผ ์์ธ ์ ๋ณด ์กฐํ"""
logic.ensure_initialized() # ๋ก๋ฉ ๋๊ธฐ
try:
row = logic.df[logic.df['๋ ์ํผ์ผ๋ จ๋ฒํธ'] == recipe_id]
if row.empty:
raise HTTPException(status_code=404, detail="Recipe not found")
row = row.iloc[0]
return {
"id": int(row['๋ ์ํผ์ผ๋ จ๋ฒํธ']),
"name": row['์๋ฆฌ๋ช
'],
"method": row['์๋ฆฌ๋ฐฉ๋ฒ๋ณ๋ช
'],
"category": row['์๋ฆฌ์ข
๋ฅ๋ณ๋ช
_์ธ๋ถํ'],
"ingredients": filter_ingredients(row['์ฌ๋ฃํ ํฐ'])
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/recommend/db/single")
def recommend_db_single(req: IngredientRequest):
"""DB ๋ ์ํผ ๊ธฐ๋ฐ ๋จ์ผ ์ฌ๋ฃ ๋์ฒด"""
logic.ensure_initialized() # ๋ก๋ฉ ๋๊ธฐ
if not req.target:
raise HTTPException(status_code=400, detail="Target ingredient required")
try:
df = logic.substitute_single(
req.recipe_id, req.target[0], req.stopwords,
req.w_w2v, req.w_d2v, req.w_method, req.w_cat
)
if df.empty: return []
df = df.replace([np.inf, -np.inf], 0).fillna(0)
return df.to_dict(orient="records")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/recommend/db/multi")
def recommend_db_multi(req: IngredientRequest):
"""DB ๋ ์ํผ ๊ธฐ๋ฐ ๋ค์ค ์ฌ๋ฃ ๋์ฒด"""
logic.ensure_initialized() # ๋ก๋ฉ ๋๊ธฐ
try:
results = logic.substitute_multi(
req.recipe_id, req.target, req.stopwords,
req.w_w2v, req.w_d2v, req.w_method, req.w_cat
)
formatted = []
for subs, score, saving in results:
formatted.append({
"substitutes": subs,
"score": float(score),
"saving_score": int(saving)
})
return formatted
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/recommend/custom/single")
def recommend_custom_single(req: CustomContextRequest):
"""์ฌ์ฉ์ ์ ์ ์ฌ๋ฃ ๊ธฐ๋ฐ ๋จ์ผ ๋์ฒด"""
logic.ensure_initialized() # ๋ก๋ฉ ๋๊ธฐ
if not req.target:
raise HTTPException(status_code=400, detail="Target ingredient required")
try:
df = logic.substitute_single_custom(
req.target[0], req.context_ings, req.stopwords,
req.w_w2v, req.w_d2v, excluded_ings=req.excluded
)
if df.empty: return []
df = df.replace([np.inf, -np.inf], 0).fillna(0)
return df.to_dict(orient="records")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
|