traning / searchWorker.py
aikobay's picture
Update searchWorker.py
2ae61db verified
raw
history blame contribute delete
30.4 kB
import os
import torch
import pandas as pd
import logging
import faiss
import numpy as np
import time
import gensim
import random
import multiprocessing
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel
from datasets import load_dataset
from huggingface_hub import login, hf_hub_download, HfApi, create_repo
from keybert import KeyBERT
from sentence_transformers import SentenceTransformer
from joblib import Parallel, delayed
from tqdm import tqdm
from fastapi.middleware.cors import CORSMiddleware
import tempfile
import re
import sys
import asyncio
import gc
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# โœ… ๋กœ๊ทธ ์„ค์ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# โœ… ์Šค๋ ˆ๋“œ ํ’€ ์ตœ์ ํ™” (์ž‘์—…์ž ์ˆ˜ ๊ฐ์†Œ๋กœ ์˜ค๋ฒ„ํ—ค๋“œ ๊ฐ์†Œ)
thread_pool = ThreadPoolExecutor(max_workers=min(32, os.cpu_count() * 2))
# โœ… ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ ์ „์—ญ ๋ณ€์ˆ˜
last_gc_time = time.time()
request_count = 0
CLEANUP_INTERVAL = 100 # 100 ์š”์ฒญ๋งˆ๋‹ค ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
startup_semaphore = asyncio.Semaphore(1) # ํ•œ ๋ฒˆ์— 1๊ฐœ์˜ ์›Œ์ปค๋งŒ ์ดˆ๊ธฐํ™” ๊ฐ€๋Šฅ
# โœ… FastAPI ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
app = FastAPI(title="๐Ÿš€ KeyBERT + Word2Vec ๊ธฐ๋ฐ˜ FAISS ๊ฒ€์ƒ‰ API", version="1.2")
# ์—ฌ๊ธฐ์„œ CORS ๋ฏธ๋“ค์›จ์–ด ๋“ฑ๋ก
app.add_middleware(
CORSMiddleware,
allow_origins=["https://dev.kobay.co.kr"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# โœ… GPU ์‚ฌ์šฉ ์—ฌ๋ถ€ ํ™•์ธ
device = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"๐Ÿš€ ์‹คํ–‰ ๋””๋ฐ”์ด์Šค: {device.upper()}")
# โœ… Hugging Face ๋กœ๊ทธ์ธ
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
if multiprocessing.current_process().name == "MainProcess":
if HF_API_TOKEN and HF_API_TOKEN.startswith("hf_"):
logger.info("๐Ÿ”‘ Hugging Face API ๋กœ๊ทธ์ธ ์ค‘ (MainProcess)...")
login(token=HF_API_TOKEN)
else:
logger.warning("โš ๏ธ HF_API_TOKEN์ด ์—†๊ฑฐ๋‚˜ ์ž˜๋ชป๋œ ํ˜•์‹์ž…๋‹ˆ๋‹ค.")
# โœ… ๋ชจ๋ธ ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™”๋งŒ (์‹ค์ œ ๋กœ๋“œ๋Š” ๋‚˜์ค‘์—)
word2vec_model = None
kw_model = None
embedding_model = None
# โœ… ์ง€์—ฐ ๋กœ๋”ฉ ๊ตฌํ˜„ - ๋ชจ๋ธ ๋กœ๋“œ ํ•จ์ˆ˜
async def load_models():
"""๋ชจ๋“  ํ•„์š”ํ•œ ๋ชจ๋ธ์„ ๋กœ๋“œํ•˜๋Š” ํ•จ์ˆ˜ (์ง€์—ฐ ๋กœ๋”ฉ)"""
global word2vec_model, kw_model, embedding_model
# ์ด๋ฏธ ๋กœ๋“œ๋˜์—ˆ๋Š”์ง€ ํ™•์ธ (์ค‘๋ณต ๋กœ๋“œ ๋ฐฉ์ง€)
if word2vec_model is not None and embedding_model is not None:
return True
worker_id = os.getenv("WORKER_ID", multiprocessing.current_process().name)
logger.info(f"๐Ÿ”„ ์›Œ์ปค {worker_id}: ๋ชจ๋ธ ๋กœ๋“œ ์‹œ์ž‘...")
try:
# 1. Word2Vec ๋ชจ๋ธ ๋กœ๋“œ
if word2vec_model is None:
MODEL_REPO = "aikobay/item-model"
model_path = hf_hub_download(repo_id=MODEL_REPO, filename="item_vectors.bin", repo_type="dataset", token=HF_API_TOKEN)
word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=True)
logger.info(f"โœ… ์›Œ์ปค {worker_id}: Word2Vec ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ! ๋‹จ์–ด ์ˆ˜: {len(word2vec_model.key_to_index)}")
# 2. KeyBERT ๋ชจ๋ธ ๋กœ๋“œ
if kw_model is None:
kw_model = KeyBERT("paraphrase-multilingual-MiniLM-L12-v2")
logger.info(f"โœ… ์›Œ์ปค {worker_id}: KeyBERT ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
# 3. ํ•œ๊ตญ์–ด ํŠนํ™” ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ
if embedding_model is None:
try:
embedding_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
logger.info(f"โœ… ์›Œ์ปค {worker_id}: ํ•œ๊ตญ์–ด ํŠนํ™” ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
except Exception as e:
logger.warning(f"โš ๏ธ ์›Œ์ปค {worker_id}: ํ•œ๊ตญ์–ด ํŠนํ™” ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ, ๊ธฐ๋ณธ ๋ชจ๋ธ ์‚ฌ์šฉ: {e}")
embedding_model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
logger.info(f"โœ… ์›Œ์ปค {worker_id}: ๊ธฐ๋ณธ ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
if device == "cuda":
try:
# ์ฒซ ๋ฒˆ์งธ ์›Œ์ปค๋‚˜ ์ง์ˆ˜ ๋ฒˆํ˜ธ์˜ ์›Œ์ปค๋งŒ GPU ์‚ฌ์šฉ
if worker_id == "MainProcess" or worker_id.endswith("0") or worker_id.endswith("1") or worker_id.endswith("2"):
embedding_model.to(device)
embedding_model.eval() # ํ‰๊ฐ€ ๋ชจ๋“œ๋กœ ์„ค์ •
logger.info(f"โœ… ์›Œ์ปค {worker_id}: GPU์— ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
else:
logger.info(f"โš ๏ธ ์›Œ์ปค {worker_id}: ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจํ™”๋ฅผ ์œ„ํ•ด CPU ๋ชจ๋“œ ์‚ฌ์šฉ")
except Exception as e:
logger.error(f"โŒ ์›Œ์ปค {worker_id}: GPU ๋ชจ๋ธ ์ดˆ๊ธฐํ™” ์˜ค๋ฅ˜: {e}")
# ๊ฐ€๋น„์ง€ ์ปฌ๋ ‰์…˜ ์ˆ˜ํ–‰
await cleanup_memory(force=True)
return True
except Exception as e:
logger.error(f"โŒ ์›Œ์ปค {worker_id}: ๋ชจ๋ธ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
return False
# โœ… ์ง„ํ–‰ ์ค‘์ธ ๊ฒฝ๋งค ์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
async def load_huggingface_jsonl(dataset_name, split="train"):
"""Hugging Face Hub์—์„œ ๋ฐ์ดํ„ฐ์…‹ ๋น„๋™๊ธฐ ๋กœ๋“œ"""
try:
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ์‹คํ–‰ํ•˜์—ฌ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ
loop = asyncio.get_event_loop()
def _load_dataset():
repo_id = f"aikobay/{dataset_name}"
dataset = load_dataset(repo_id, split=split)
return dataset.to_pandas().dropna()
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ๋น„๋™๊ธฐ๋กœ ์‹คํ–‰
df = await loop.run_in_executor(thread_pool, _load_dataset)
return df
except Exception as e:
logger.error(f"โŒ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
return pd.DataFrame()
# ์ดˆ๊ธฐํ™”๋งŒ ์ˆ˜ํ–‰, ์‹ค์ œ ๋กœ๋“œ๋Š” startup์—์„œ
active_sale_items = None
# โœ… FAISS ์ธ๋ฑ์Šค ์ดˆ๊ธฐํ™”
faiss_index = None
indexed_items = []
# โœ… ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ํ•จ์ˆ˜
async def cleanup_memory(force=False):
"""์ฃผ๊ธฐ์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ์ˆ˜ํ–‰"""
global last_gc_time
# ํ˜„์žฌ ์‹œ๊ฐ„ ํ™•์ธ
current_time = time.time()
# 15์ดˆ๋งˆ๋‹ค ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ๋˜๋Š” ๊ฐ•์ œ ์ •๋ฆฌ ์š”์ฒญ ์‹œ
if force or (current_time - last_gc_time > 15):
# ๊ฐ€๋น„์ง€ ์ปฌ๋ ‰์…˜ ์‹คํ–‰
gc.collect()
# GPU ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
if torch.cuda.is_available():
torch.cuda.empty_cache()
# ์‹œ๊ฐ„ ์—…๋ฐ์ดํŠธ
last_gc_time = current_time
logger.debug("๐Ÿงน ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ์™„๋ฃŒ")
return True
return False
# โœ… ๋ฉ€ํ‹ฐ์ฝ”์–ด ๋ฒกํ„ฐํ™” ํ•จ์ˆ˜ - ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ํ•ด๊ฒฐ
async def encode_texts_parallel(texts, batch_size=1024):
"""GPU ํ™œ์šฉ + ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ๋ฐฉ์ง€ ์ตœ์ ํ™” ๋ฒกํ„ฐํ™”"""
# ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์—ˆ๋Š”์ง€ ํ™•์ธ
if embedding_model is None:
# ๋น„๋™๊ธฐ ์ปจํ…์ŠคํŠธ์—์„œ ๋™๊ธฐ ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋ฐฉ์ง€
worker_id = multiprocessing.current_process().name
logger.warning(f"โš ๏ธ ์›Œ์ปค {worker_id}: ๋ฒกํ„ฐํ™” ์ „ ๋ชจ๋ธ ๋กœ๋“œ ํ•„์š”")
if not await load_models(): # ๋น„๋™๊ธฐ ํ˜ธ์ถœ๋กœ ์ˆ˜์ •
logger.error(f"โŒ ์›Œ์ปค {worker_id}: ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ, ๋ฒกํ„ฐํ™” ๋ถˆ๊ฐ€")
return np.array([]).astype("float32")
if not texts:
return np.array([]).astype("float32")
try:
# ๋ฐฐ์น˜ ํฌ๊ธฐ ์กฐ์ • - ์งง์€ ํ…์ŠคํŠธ๋Š” ํฐ ๋ฐฐ์น˜, ๊ธธ๋ฉด ์ž‘๊ฒŒ
if len(texts) > 10:
batch_size = min(1024, batch_size) # ๋งŽ์€ ํ…์ŠคํŠธ๋Š” ๋ฐฐ์น˜ ํฌ๊ธฐ ์ œํ•œ
else:
batch_size = min(2048, batch_size) # ์ ์€ ํ…์ŠคํŠธ๋Š” ๋” ํฐ ๋ฐฐ์น˜ ๊ฐ€๋Šฅ
loop = asyncio.get_event_loop()
def _encode_efficiently():
# ์ž‘์€ ๋ฐฐ์น˜๋กœ ๋‚˜๋ˆ„์–ด ์ธ์ฝ”๋”ฉ (๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”)
with torch.no_grad():
return embedding_model.encode(
texts,
batch_size=batch_size,
convert_to_numpy=True,
show_progress_bar=False,
device=device,
normalize_embeddings=True
)
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ์‹คํ–‰
embeddings = await loop.run_in_executor(thread_pool, _encode_efficiently)
return embeddings.astype("float32")
except Exception as e:
logger.error(f"โŒ ๋ฒกํ„ฐํ™” ์˜ค๋ฅ˜: {str(e)}")
return np.array([]).astype("float32")
finally:
# ์ˆ˜ํ–‰ ํ›„ ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ (์š”์ฒญ์ด ๋งŽ์„ ๊ฒฝ์šฐ๋Š” ๊ฐ€๋”์”ฉ๋งŒ)
global request_count
if request_count % 25 == 0:
await cleanup_memory(force=True)
# โœ… FAISS ์ธ๋ฑ์Šค ์ €์žฅ ํ•จ์ˆ˜ (Hugging Face Hub)
async def save_faiss_index():
"""FAISS ์ธ๋ฑ์Šค๋ฅผ Hugging Face Hub์— ์ €์žฅ (๋น„๋™๊ธฐ ์ง€์›)"""
global faiss_index, indexed_items
if faiss_index is None or not indexed_items:
logger.error("โŒ ์ €์žฅํ•  FAISS ์ธ๋ฑ์Šค๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
return False
try:
# ๋ ˆํฌ์ง€ํ† ๋ฆฌ ID
repo_id = os.getenv("HF_INDEX_REPO", "aikobay/saleitem_faiss_index")
# ๋น„๋™๊ธฐ ์ž‘์—…์„ ์œ„ํ•œ ๋ฃจํ”„
loop = asyncio.get_event_loop()
# ๋น„๋™๊ธฐ ์ž‘์—…์œผ๋กœ ์‹คํ–‰
def _save_index():
# HfApi ๊ฐ์ฒด ์ƒ์„ฑ
api = HfApi()
# ๋ ˆํฌ์ง€ํ† ๋ฆฌ ์กด์žฌ ์—ฌ๋ถ€ ํ™•์ธ ๋ฐ ์ƒ์„ฑ
try:
api.repo_info(repo_id=repo_id, repo_type="dataset")
logger.info(f"โœ… ๊ธฐ์กด ๋ ˆํฌ์ง€ํ† ๋ฆฌ ์‚ฌ์šฉ: {repo_id}")
except Exception:
logger.info(f"๐Ÿ”„ ๋ ˆํฌ์ง€ํ† ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์•„ ์ƒˆ๋กœ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค: {repo_id}")
create_repo(
repo_id=repo_id,
repo_type="dataset",
private=True,
exist_ok=True
)
logger.info(f"โœ… ๋ ˆํฌ์ง€ํ† ๋ฆฌ ์ƒ์„ฑ ์™„๋ฃŒ: {repo_id}")
# ์ž„์‹œ ํŒŒ์ผ๋กœ ๋จผ์ € ๋กœ์ปฌ์— ์ €์žฅ
with tempfile.TemporaryDirectory() as temp_dir:
index_path = os.path.join(temp_dir, "faiss_index.bin")
items_path = os.path.join(temp_dir, "indexed_items.txt")
# FAISS ์ธ๋ฑ์Šค ์ €์žฅ
faiss.write_index(faiss_index, index_path)
# ์•„์ดํ…œ ๋ชฉ๋ก ์ €์žฅ
with open(items_path, "w", encoding="utf-8") as f:
f.write("\n".join(indexed_items))
# README ํŒŒ์ผ ์ƒ์„ฑ
readme_path = os.path.join(temp_dir, "README.md")
with open(readme_path, "w", encoding="utf-8") as f:
f.write(f"""# FAISS ์ธ๋ฑ์Šค ์ €์žฅ์†Œ
์ด ์ €์žฅ์†Œ๋Š” ์ƒํ’ˆ ๊ฒ€์ƒ‰์„ ์œ„ํ•œ FAISS ์ธ๋ฑ์Šค์™€ ๊ด€๋ จ ๋ฐ์ดํ„ฐ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
- ์ตœ์ข… ์—…๋ฐ์ดํŠธ: {pd.Timestamp.now()}
- ์ธ๋ฑ์Šค ํ•ญ๋ชฉ ์ˆ˜: {len(indexed_items)}
- ๋ชจ๋ธ: KeyBERT + Word2Vec
์ด ์ €์žฅ์†Œ๋Š” 'aikobay/initial_saleitem_dataset'์˜ ์ƒํ’ˆ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ƒ์„ฑ๋œ ๋ฒกํ„ฐ ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์ž๋™ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.
""")
# ํŒŒ์ผ ์—…๋กœ๋“œ
for file_path, file_name in [
(index_path, "faiss_index.bin"),
(items_path, "indexed_items.txt"),
(readme_path, "README.md")
]:
api.upload_file(
path_or_fileobj=file_path,
path_in_repo=file_name,
repo_id=repo_id,
repo_type="dataset"
)
logger.info(f"โœ… FAISS ์ธ๋ฑ์Šค๊ฐ€ Hugging Face Hub์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋ ˆํฌ: {repo_id}")
return True
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ๋น„๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
result = await loop.run_in_executor(thread_pool, _save_index)
return result
except Exception as e:
logger.error(f"โŒ FAISS ์ธ๋ฑ์Šค Hub ์ €์žฅ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
# ๋กœ์ปฌ์— ๋ฐฑ์—… ์ €์žฅ ์‹œ๋„
try:
loop = asyncio.get_event_loop()
def _local_backup():
local_path = os.path.join(os.getcwd(), "faiss_index.bin")
faiss.write_index(faiss_index, local_path)
with open("indexed_items.txt", "w", encoding="utf-8") as f:
f.write("\n".join(indexed_items))
logger.info(f"โœ… FAISS ์ธ๋ฑ์Šค๊ฐ€ ๋กœ์ปฌ์— ๋ฐฑ์—… ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค: {local_path}")
return True
result = await loop.run_in_executor(thread_pool, _local_backup)
return result
except Exception as local_err:
logger.error(f"โŒ ๋กœ์ปฌ ๋ฐฑ์—… ์ €์žฅ๋„ ์‹คํŒจ: {local_err}")
return False
# โœ… FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ํ•จ์ˆ˜ (Hugging Face Hub)
async def load_faiss_index_safe():
"""์•ˆ์ „ํ•˜๊ฒŒ FAISS ์ธ๋ฑ์Šค๋ฅผ ์ฝ๊ธฐ ์ „์šฉ์œผ๋กœ ๋กœ๋“œ"""
global faiss_index, indexed_items
# ์ตœ๋Œ€ ์žฌ์‹œ๋„ ํšŸ์ˆ˜
max_retries = 5
retry_delay = 1 # ์ดˆ๊ธฐ ์ง€์—ฐ (์ดˆ)
worker_id = os.getenv("WORKER_ID", multiprocessing.current_process().name)
for attempt in range(max_retries):
try:
# ๋ ˆํฌ์ง€ํ† ๋ฆฌ ID
repo_id = os.getenv("HF_INDEX_REPO", "aikobay/saleitem_faiss_index")
# Hub์—์„œ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ (์ฝ๊ธฐ ์ „์šฉ)
index_path = hf_hub_download(
repo_id=repo_id,
filename="faiss_index.bin",
repo_type="dataset"
)
items_path = hf_hub_download(
repo_id=repo_id,
filename="indexed_items.txt",
repo_type="dataset"
)
# ์ง์ ‘ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ธ๋ฑ์Šค ๋กœ๋“œ - ์ด ๋ฐฉ๋ฒ•์ด ๊ฐ€์žฅ ์•ˆ์ •์ 
loaded_index = faiss.read_index(index_path)
# ํ•ญ๋ชฉ ๋ชฉ๋ก ์ฝ๊ธฐ
with open(items_path, "r", encoding="utf-8") as f:
loaded_items = f.read().splitlines()
# ์ „์—ญ ๋ณ€์ˆ˜์— ํ• ๋‹น
faiss_index = loaded_index
indexed_items = loaded_items
logger.info(f"โœ… ์›Œ์ปค {worker_id}: FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์™„๋ฃŒ. ์ด {len(indexed_items)}๊ฐœ ํ•ญ๋ชฉ")
return True
except Exception as e:
logger.warning(f"โš ๏ธ ์›Œ์ปค {worker_id}: ์ธ๋ฑ์Šค ๋กœ๋“œ ์‹คํŒจ (์‹œ๋„ {attempt+1}/{max_retries}): {e}")
# ์ง€์—ฐ ํ›„ ์žฌ์‹œ๋„
await asyncio.sleep(retry_delay * (2 ** attempt)) # ์ง€์ˆ˜ ๋ฐฑ์˜คํ”„
logger.error(f"โŒ ์›Œ์ปค {worker_id}: ์ธ๋ฑ์Šค ๋กœ๋“œ ์ตœ๋Œ€ ์žฌ์‹œ๋„ ํšŸ์ˆ˜ ์ดˆ๊ณผ")
return False
# โœ… ์ตœ์ ํ™”๋œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ ํ•จ์ˆ˜
async def extract_keywords(query: str, top_n: int = 2):
"""KeyBERT ์ตœ์ ํ™” ํ‚ค์›Œ๋“œ ์ถ”์ถœ (์„ฑ๋Šฅ ์ค‘์‹ฌ)"""
# ๋งค์šฐ ์งง์€ ์ฟผ๋ฆฌ๋Š” ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ (์ฒ˜๋ฆฌ ๋น„์šฉ ์ ˆ๊ฐ)
if len(query) <= 3:
return [query]
loop = asyncio.get_event_loop()
def _optimized_extract():
# ์„ฑ๋Šฅ ์ค‘์‹ฌ ์„ค์ •
return kw_model.extract_keywords(
query,
keyphrase_ngram_range=(1, 1), # ๋‹จ์ผ ๋‹จ์–ด๋งŒ ์ถ”์ถœ
stop_words=["์ด", "๊ทธ", "์ €", "์„", "๋ฅผ", "์—", "์—์„œ", "์€", "๋Š”"], # ํ•œ๊ตญ์–ด ๋ถˆ์šฉ์–ด
use_mmr=True,
diversity=0.5,
top_n=top_n
)
try:
keywords = await loop.run_in_executor(thread_pool, _optimized_extract)
# ๊ฐ€์ค‘์น˜๊ฐ€ ๋„ˆ๋ฌด ๋‚ฎ์€ ํ‚ค์›Œ๋“œ ์ œ์™ธ
filtered = [(k, s) for k, s in keywords if s > 0.2]
return [k[0] for k in filtered]
except Exception as e:
logger.error(f"โŒ ํ‚ค์›Œ๋“œ ์ถ”์ถœ ์˜ค๋ฅ˜: {str(e)}")
# ๋‹จ์–ด ๋ถ„๋ฆฌ๋กœ ํด๋ฐฑ
return query.split()[:2]
# โœ… ๋ฐฐ์น˜ ๊ฒ€์ƒ‰ ํ†ตํ•ฉ ํ•จ์ˆ˜ - ํ•œ๋ฒˆ์— ๊ฒ€์ƒ‰์œผ๋กœ ํšจ์œจ ํ–ฅ์ƒ
async def unified_search(vectors, top_k=5):
"""๋ชจ๋“  ๋ฒกํ„ฐ๋ฅผ ํ•œ ๋ฒˆ์— ๊ฒ€์ƒ‰ํ•˜์—ฌ ํšจ์œจ์„ฑ ํ–ฅ์ƒ"""
if vectors.size == 0:
return []
# nprobe ๋™์  ์กฐ์ • (์„œ๋ฒ„ ๋ถ€ํ•˜์— ๋”ฐ๋ผ)
global request_count
if request_count % 100 == 0: # 100๊ฐœ ์š”์ฒญ๋งˆ๋‹ค ์กฐ์ •
if faiss_index.nprobe > 8: # ํ˜„์žฌ ๊ฐ’์ด ๋†’์œผ๋ฉด
faiss_index.nprobe = 8 # ๋‚ฎ์€ ๊ฐ’์œผ๋กœ ์„ค์ • (์†๋„ ์ค‘์‹œ)
loop = asyncio.get_event_loop()
def _batch_search():
# ๋ชจ๋“  ๋ฒกํ„ฐ๋ฅผ ํ•œ ๋ฒˆ์— ๊ฒ€์ƒ‰
distances, indices = faiss_index.search(vectors, top_k)
return distances, indices
try:
# ์ผ๊ด„ ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰
distances, indices = await loop.run_in_executor(thread_pool, _batch_search)
# ๊ฒฐ๊ณผ ์ •๋ฆฌ
results = []
for i in range(len(indices)):
items = []
for j, (idx, dist) in enumerate(zip(indices[i], distances[i])):
if idx < len(indexed_items):
items.append((idx, float(dist)))
results.append(items)
return results
except Exception as e:
logger.error(f"โŒ ๊ฒ€์ƒ‰ ์˜ค๋ฅ˜: {str(e)}")
return []
# โœ… ์ตœ์ ํ™”๋œ search_faiss_with_keywords ํ•จ์ˆ˜
async def search_faiss_with_keywords(query: str, top_k: int = 5, keywords=None):
"""๊ณ ์† ํ‚ค์›Œ๋“œ ๊ธฐ๋ฐ˜ FAISS ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰ (ํšจ์œจ์  ์ตœ์ ํ™”)"""
global faiss_index, indexed_items, request_count
# ํƒ€์ด๋จธ ์‹œ์ž‘
start_time = time.time()
# ์š”์ฒญ ์นด์šดํ„ฐ ์ฆ๊ฐ€
request_count += 1
# ์กฐ๊ธฐ ์ตœ์ ํ™” - ๋งค์šฐ ์งง์€ ์ฟผ๋ฆฌ
if len(query) <= 2:
# ๊ฐ„๋‹จํ•œ ์ฒ˜๋ฆฌ๋กœ ๋น ๋ฅด๊ฒŒ ๋ฐ˜ํ™˜
vector = await encode_texts_parallel([query])
distances, indices = faiss_index.search(vector, top_k)
quick_results = []
for idx, dist in zip(indices[0], distances[0]):
if idx < len(indexed_items):
item_name = indexed_items[idx]
try:
item_seq = active_sale_items.loc[active_sale_items["ITEMNAME"] == item_name, "ITEMSEQ"].values[0]
quick_results.append({
"ITEMSEQ": item_seq,
"ITEMNAME": item_name,
"score": float(dist)
})
except:
continue
# ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
if request_count % CLEANUP_INTERVAL == 0:
await cleanup_memory()
return quick_results
# 1. ํ‚ค์›Œ๋“œ ์ถ”์ถœ
if keywords is None:
keywords = await extract_keywords(query)
# ๋ถˆํ•„์š”ํ•œ ํ™•์žฅ ์ ˆ์ฐจ ์ œ๊ฑฐ (์„ฑ๋Šฅ ํ–ฅ์ƒ)
# 2. ๋ฒกํ„ฐ ์ธ์ฝ”๋”ฉ - ๋ชจ๋“  ํ…์ŠคํŠธ๋ฅผ ํ•œ ๋ฒˆ์— ์ฒ˜๋ฆฌ
search_texts = [query] + keywords
try:
# ๋ฒกํ„ฐ ์ธ์ฝ”๋”ฉ - ์ตœ์ ํ™”๋œ ํ•จ์ˆ˜ ์‚ฌ์šฉ (์ •๊ทœํ™” ํฌํ•จ)
all_vectors = await encode_texts_parallel(search_texts)
if all_vectors.size == 0:
logger.warning(f"โš ๏ธ ๋ฒกํ„ฐํ™” ์‹คํŒจ: {query}")
return []
# 3. ์ผ๊ด„ ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰ (ํšจ์œจ์ )
search_results = await unified_search(all_vectors, top_k=top_k)
if not search_results:
return []
# 4. ๊ฒฐ๊ณผ ํ†ตํ•ฉ ๋ฐ ์ค‘๋ณต ์ œ๊ฑฐ
all_results = {}
# ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ (๊ฐ€์ค‘์น˜ ๋†’๊ฒŒ)
for idx, score in search_results[0]:
if idx < len(indexed_items):
all_results[idx] = score * 3.0 # ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ์— ๊ฐ€์ค‘์น˜ 3๋ฐฐ
# ํ‚ค์›Œ๋“œ ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ
for i in range(1, len(search_results)):
keyword_results = search_results[i]
weight = 0.5 # ํ‚ค์›Œ๋“œ ๊ฐ€์ค‘์น˜
for idx, score in keyword_results:
if idx in all_results:
# ๊ธฐ์กด ์ ์ˆ˜์— ์ถ”๊ฐ€
all_results[idx] = max(all_results[idx], score * weight)
else:
# ์ƒˆ ํ•ญ๋ชฉ ์ถ”๊ฐ€
all_results[idx] = score * weight
# 5. ์ตœ์ข… ์ฒ˜๋ฆฌ ๋ฐ ๋ฐ˜ํ™˜
# ์ ์ˆ˜ ๊ธฐ์ค€ ์ •๋ ฌ
sorted_items = sorted(all_results.items(), key=lambda x: x[1], reverse=True)
# ์ตœ์ข… ๊ฒฐ๊ณผ ๋ณ€ํ™˜ (์ตœ์†Œํ•œ์˜ ๋ฃฉ์—…์œผ๋กœ ์ตœ์ ํ™”)
recommendations = []
item_indices = [idx for idx, _ in sorted_items[:top_k]]
# ๋ฐฐ์น˜๋กœ ํ•ญ๋ชฉ ์กฐํšŒ (์„ฑ๋Šฅ ํ–ฅ์ƒ)
if item_indices:
item_names = [indexed_items[idx] for idx in item_indices]
# ํšจ์œจ์ ์ธ ๋ฐฐ์น˜ ์กฐํšŒ
items_df = active_sale_items[active_sale_items["ITEMNAME"].isin(item_names)]
items_map = dict(zip(items_df["ITEMNAME"], items_df["ITEMSEQ"]))
for idx, score in sorted_items[:top_k]:
item_name = indexed_items[idx]
if item_name in items_map:
recommendations.append({
"ITEMSEQ": items_map[item_name],
"ITEMNAME": item_name,
"score": float(score)
})
# ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
if request_count % CLEANUP_INTERVAL == 0:
await cleanup_memory()
# ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด 1์ดˆ ์ด์ƒ์ธ ๊ฒฝ์šฐ์—๋งŒ ๋กœ๊น…
elapsed = time.time() - start_time
if elapsed > 1.0:
logger.info(f"๐Ÿ” ๊ฒ€์ƒ‰ ์™„๋ฃŒ | ์†Œ์š”์‹œ๊ฐ„: {elapsed:.2f}์ดˆ | ๊ฒฐ๊ณผ: {len(recommendations)}๊ฐœ")
return recommendations[:top_k]
except Exception as e:
logger.error(f"โŒ ๊ฒ€์ƒ‰ ํ”„๋กœ์„ธ์Šค ์˜ค๋ฅ˜: {str(e)}")
return []
# โœ… API ์š”์ฒญ ๋ชจ๋ธ
class RecommendRequest(BaseModel):
search_query: str
top_k: int = 5
use_expansion: bool = True # ํ‚ค์›Œ๋“œ ํ™•์žฅ ์‚ฌ์šฉ ์—ฌ๋ถ€
# ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์—ˆ๋Š”์ง€ ๊ฒ€์ฆํ•˜๋Š” ํ•จ์ˆ˜ ์ถ”๊ฐ€
def validate_models():
"""ํ•„์š”ํ•œ ๋ชจ๋ธ๋“ค์ด ๋ชจ๋‘ ๋กœ๋“œ๋˜์—ˆ๋Š”์ง€ ํ™•์ธ"""
models_loaded = (
word2vec_model is not None and
kw_model is not None and
embedding_model is not None
)
return models_loaded
# โœ… ์ถ”์ฒœ API ์—”๋“œํฌ์ธํŠธ (๋‹ค์ค‘ ์š”์ฒญ ์ฒ˜๋ฆฌ ์ตœ์ ํ™”)
@app.post("/api/recommend")
async def recommend(request: RecommendRequest, background_tasks: BackgroundTasks):
if not validate_models():
# ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์„ ๋•Œ ์žฌ์‹œ๋„ ๋˜๋Š” ์˜ค๋ฅ˜ ๋ฐ˜ํ™˜
await load_models() # ๋น„๋™๊ธฐ ํ˜ธ์ถœ๋กœ ์ˆ˜์ •
if not validate_models():
raise HTTPException(status_code=503, detail="์„œ๋น„์Šค๊ฐ€ ์ค€๋น„๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.")
"""๊ณ ์† ์ถ”์ฒœ API (๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ ์ตœ์ ํ™” + ์„ฑ๋Šฅ ๊ฐœ์„ )"""
try:
# ๋ฒค์น˜๋งˆํฌ์šฉ ํƒ€์ด๋จธ ์‹œ์ž‘
start_time = time.time()
# ํŒŒ๋ผ๋ฏธํ„ฐ ์ตœ์ ํ™” ๋ฐ ๊ฒ€์ฆ
search_query = request.search_query.strip()
if not search_query:
raise HTTPException(status_code=400, detail="๊ฒ€์ƒ‰์–ด๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”")
top_k = min(max(1, request.top_k), 20) # 1~20 ๋ฒ”์œ„๋กœ ์ œํ•œ
# ์ตœ์ ํ™” ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰
recommendations = await search_faiss_with_keywords(
search_query,
top_k
)
# ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜ (๊ฐ„์†Œํ™”)
result = {
"query": search_query,
"recommendations": recommendations
}
# ์‘๋‹ต ์‹œ๊ฐ„ ์ธก์ • (1์ดˆ ์ด์ƒ๋งŒ ๋กœ๊น…)
elapsed = time.time() - start_time
if elapsed > 1.0:
logger.info(f"โฑ๏ธ API ์‘๋‹ต ์‹œ๊ฐ„: {elapsed:.2f}์ดˆ | ์ฟผ๋ฆฌ: '{search_query}'")
return result
except Exception as e:
logger.error(f"โŒ ์ถ”์ฒœ ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}")
raise HTTPException(status_code=500, detail=f"์ถ”์ฒœ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค")
# ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ํ•จ์ˆ˜
async def periodic_memory_monitor():
"""์ฃผ๊ธฐ์ ์œผ๋กœ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰์„ ๋ชจ๋‹ˆํ„ฐ๋งํ•˜๊ณ  ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค."""
try:
worker_id = multiprocessing.current_process().name
logger.info(f"๐Ÿ”„ ์›Œ์ปค {worker_id}: ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘")
while True:
await asyncio.sleep(1800) # 30๋ถ„๋งˆ๋‹ค ์‹คํ–‰
# ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ (์ค‘๋ณต ์ œ๊ฑฐ)
await cleanup_memory(force=True)
# ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ๋กœ๊น…
if device == "cuda":
allocated = torch.cuda.memory_allocated() / (1024**3)
reserved = torch.cuda.memory_reserved() / (1024**3)
logger.info(f"๐Ÿ“Š ์›Œ์ปค {worker_id}: GPU ๋ฉ”๋ชจ๋ฆฌ - ํ• ๋‹น: {allocated:.2f}GB, ์˜ˆ์•ฝ: {reserved:.2f}GB")
# ์‹œ์Šคํ…œ ๋ฉ”๋ชจ๋ฆฌ ๋กœ๊น… (์„ ํƒ ์‚ฌํ•ญ)
import psutil
process = psutil.Process()
memory_info = process.memory_info()
logger.info(f"๐Ÿ“Š ์›Œ์ปค {worker_id}: ์‹œ์Šคํ…œ ๋ฉ”๋ชจ๋ฆฌ - RSS: {memory_info.rss/(1024**3):.2f}GB")
except Exception as e:
logger.error(f"โŒ ์›Œ์ปค {worker_id}: ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์ค‘ ์˜ค๋ฅ˜: {e}")
# FastAPI ์‹œ์ž‘ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ํ™•์žฅ
@app.on_event("startup")
async def startup_event():
try:
worker_id = multiprocessing.current_process().name
logger.warning(f"๐ŸŸก ์›Œ์ปค {worker_id} STARTUP ์‹œ์ž‘")
# ๋ฆฌ์†Œ์Šค ์‚ฌ์šฉ๋Ÿ‰ ๋กœ๊น… ์ถ”๊ฐ€ (์—ฌ๊ธฐ์— ์ถ”๊ฐ€)
if device == "cuda":
logger.info(f"๐Ÿ”„ ์›Œ์ปค {worker_id}: GPU ๋ฉ”๋ชจ๋ฆฌ ์ƒํƒœ:")
logger.info(f" - ์ด ๋ฉ”๋ชจ๋ฆฌ: {torch.cuda.get_device_properties(0).total_memory/(1024**3):.2f}GB")
logger.info(f" - ํ˜„์žฌ ํ• ๋‹น: {torch.cuda.memory_allocated()/(1024**3):.2f}GB")
logger.info(f" - ์˜ˆ์•ฝ: {torch.cuda.memory_reserved()/(1024**3):.2f}GB")
logger.info(f"๐Ÿ”„ ์›Œ์ปค {worker_id}: ์ดˆ๊ธฐํ™” ์„ธ๋งˆํฌ์–ด ๋Œ€๊ธฐ ์ค‘...")
async with startup_semaphore:
logger.info(f"โœ… ์›Œ์ปค {worker_id}: ์ดˆ๊ธฐํ™” ์‹œ์ž‘")
# ๋ชจ๋ธ ๋กœ๋“œ ๋ถ€๋ถ„์— ๋” ๊ฒฌ๊ณ ํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ์ถ”๊ฐ€ ----------
try:
if not await load_models(): # ๋น„๋™๊ธฐ ํ˜ธ์ถœ๋กœ ์ˆ˜์ •
logger.error(f"โŒ ์›Œ์ปค {worker_id} ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ")
# ์˜ค๋ฅ˜๊ฐ€ ์žˆ์–ด๋„ ๊ณ„์† ์ง„ํ–‰
except Exception as model_err:
logger.error(f"๐Ÿ’ฅ ์›Œ์ปค {worker_id} ๋ชจ๋ธ ๋กœ๋“œ ์ค‘ ์‹ฌ๊ฐํ•œ ์˜ค๋ฅ˜: {model_err}")
# ์˜ค๋ฅ˜๋ฅผ ๊ธฐ๋กํ•˜๊ณ  ๊ณ„์† ์ง„ํ–‰ (์ข…๋ฃŒํ•˜์ง€ ์•Š์Œ)
# ๋ฐ์ดํ„ฐ ๋กœ๋“œ ๋ถ€๋ถ„ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ๊ฐ•ํ™” -----------
global active_sale_items
try:
active_sale_items = await load_huggingface_jsonl("initial_saleitem_dataset")
if active_sale_items is not None and not active_sale_items.empty:
logger.info(f"โœ… ์›Œ์ปค {worker_id} ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์™„๋ฃŒ: {len(active_sale_items)}๊ฐœ ํ•ญ๋ชฉ")
else:
logger.error(f"โŒ ์›Œ์ปค {worker_id} ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจ - ๋นˆ ๋ฐ์ดํ„ฐ์…‹")
# ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์–ด๋„ ๊ณ„์† ์ง„ํ–‰
except Exception as data_err:
logger.error(f"๐Ÿ’ฅ ์›Œ์ปค {worker_id} ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {data_err}")
# ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจํ•ด๋„ ๊ณ„์† ์ง„ํ–‰
active_sale_items = pd.DataFrame() # ๋นˆ DataFrame์œผ๋กœ ์ดˆ๊ธฐํ™”
# FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ๋ถ€๋ถ„ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ๊ฐ•ํ™” -----------
faiss_loaded = False
try:
if await load_faiss_index_safe():
logger.info(f"โœ… ์›Œ์ปค {worker_id} FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์„ฑ๊ณต")
faiss_loaded = True
else:
logger.warning(f"โš ๏ธ ์›Œ์ปค {worker_id} FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์‹คํŒจ")
except Exception as faiss_err:
logger.error(f"๐Ÿ’ฅ ์›Œ์ปค {worker_id} FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {faiss_err}")
# ์ธ๋ฑ์Šค ๋กœ๋“œ ์‹คํŒจํ•ด๋„ ๊ณ„์† ์ง„ํ–‰
# ์—ฌ๊ธฐ์— ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘
try:
asyncio.create_task(periodic_memory_monitor())
logger.info(f"โœ… ์›Œ์ปค {worker_id} ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘")
except Exception as monitor_err:
logger.error(f"โš ๏ธ ์›Œ์ปค {worker_id} ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘ ์‹คํŒจ: {monitor_err}")
# ์ตœ์ข… ์›Œ์ปค ์ƒํƒœ ๊ธฐ๋ก
status = "๐ŸŸข ์ •์ƒ" if faiss_loaded else "๐ŸŸ  ๋ถ€๋ถ„์  (์ธ๋ฑ์Šค ์—†์Œ)"
logger.info(f"๐Ÿ ์›Œ์ปค {worker_id} STARTUP ์™„๋ฃŒ: {status}")
except Exception as e:
logger.exception(f"๐Ÿ”ฅ ์›Œ์ปค {worker_id} STARTUP ์‹คํŒจ: {e}")
# ์ƒ์„ธ ์˜ค๋ฅ˜ ๋กœ๊น… ์ถ”๊ฐ€ (์—ฌ๊ธฐ์— ์ถ”๊ฐ€)
import traceback
logger.error(f"์Šคํƒ ์ถ”์ : {traceback.format_exc()}")
# ์‹ฌ๊ฐํ•œ ์˜ค๋ฅ˜ ์‹œ ์›Œ์ปค ์ข…๋ฃŒ ๊ณ ๋ ค
# sys.exit(1) # ํ”„๋กœ๋•์…˜์—์„œ๋Š” ์ฃผ์˜ํ•ด์„œ ์‚ฌ์šฉ
# โœ… FastAPI ์‹คํ–‰
# Uvicorn ์‹คํ–‰ ์„ค์ • ์ตœ์ ํ™”
if __name__ == "__main__":
import uvicorn
# ์›Œ์ปค ์ˆ˜ ์„ค์ •
workers = int(os.getenv("WORKERS", 3))
# GPU ๋ฉ”๋ชจ๋ฆฌ ๋ถ„๋ฐฐ๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ • (์—ฌ๊ธฐ์— ์ถ”๊ฐ€)
if device == "cuda":
# ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ GPU ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ
torch.cuda.set_per_process_memory_fraction(0.28) # ๊ฐ ์›Œ์ปค๊ฐ€ ์ตœ๋Œ€ 40%์˜ GPU ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์‚ฌ์šฉ
uvicorn.run(
"searchWorker:app",
host="0.0.0.0",
port=7860,
workers=workers,
log_level="info",
timeout_keep_alive=65, # ์—ฐ๊ฒฐ ์œ ์ง€ ์‹œ๊ฐ„ ์ฆ๊ฐ€
limit_concurrency=100, # ๋™์‹œ ์—ฐ๊ฒฐ ์ œํ•œ(๊ธฐ๋ณธ 100์—์„œ ๋ณ€๊ฒฝํ•จ)
timeout_graceful_shutdown=30 # ์ข…๋ฃŒ ์‹œ ๋Œ€๊ธฐ ์‹œ๊ฐ„
)