traning / searchWorkerBackup.py
aikobay's picture
Create searchWorkerBackup.py
9b959aa verified
raw
history blame contribute delete
42.5 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
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 ์š”์ฒญ๋งˆ๋‹ค ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
# โœ… FastAPI ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
app = FastAPI(title="๐Ÿš€ KeyBERT + Word2Vec ๊ธฐ๋ฐ˜ FAISS ๊ฒ€์ƒ‰ API", version="1.2")
# โœ… 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
original_embedding_model = None
# โœ… ์ง€์—ฐ ๋กœ๋”ฉ ๊ตฌํ˜„ - ๋ชจ๋ธ ๋กœ๋“œ ํ•จ์ˆ˜
def load_models():
"""๋ชจ๋“  ํ•„์š”ํ•œ ๋ชจ๋ธ์„ ๋กœ๋“œํ•˜๋Š” ํ•จ์ˆ˜ (์ง€์—ฐ ๋กœ๋”ฉ)"""
global word2vec_model, kw_model, embedding_model, original_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:
original_embedding_model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
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 = original_embedding_model
# GPU ์ตœ์ ํ™” - ์›Œ์ปค ID๊ฐ€ ์ง์ˆ˜์ธ ๊ฒฝ์šฐ๋งŒ GPU ์‚ฌ์šฉ (๋ฉ”๋ชจ๋ฆฌ ๋ถ€ํ•˜ ๋ถ„์‚ฐ)
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}")
# ๊ฐ€๋น„์ง€ ์ปฌ๋ ‰์…˜ ์ˆ˜ํ–‰
gc.collect()
if device == "cuda":
torch.cuda.empty_cache()
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():
"""์ฃผ๊ธฐ์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ์ˆ˜ํ–‰"""
global last_gc_time
# ํ˜„์žฌ ์‹œ๊ฐ„ ํ™•์ธ
current_time = time.time()
# 15์ดˆ๋งˆ๋‹ค ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ (๋„ˆ๋ฌด ์ž์ฃผํ•˜๋ฉด ์„ฑ๋Šฅ ์ €ํ•˜)
if 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 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 and device == "cuda": # 25 ์š”์ฒญ๋งˆ๋‹ค ์ •๋ฆฌ
torch.cuda.empty_cache()
# โœ… 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
# โœ… FAISS ์–‘์žํ™” ์ธ๋ฑ์Šค ๊ตฌ์ถ• ํ•จ์ˆ˜ (IVF ๊ธฐ๋ฐ˜์œผ๋กœ ๋ณ€๊ฒฝ)
async def rebuild_faiss_index():
"""FAISS ์ธ๋ฑ์Šค๋ฅผ IVF ๊ธฐ๋ฐ˜์œผ๋กœ ์ƒˆ๋กญ๊ฒŒ ๊ตฌ์ถ• (์†๋„ ์ตœ์ ํ™”)"""
global faiss_index, indexed_items, active_sale_items
logger.info("๐Ÿ”„ FAISS ์ธ๋ฑ์Šค๋ฅผ ๊ณ ์† IVF ๊ธฐ๋ฐ˜์œผ๋กœ ์žฌ๊ตฌ์ถ• ์ค‘...")
# ์ตœ์‹  ์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
active_sale_items = await load_huggingface_jsonl("initial_saleitem_dataset")
if active_sale_items.empty:
logger.error("โŒ ์ƒํ’ˆ ๋ฐ์ดํ„ฐ๋ฅผ ๋กœ๋“œํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
raise RuntimeError("์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจ")
# ์ƒํ’ˆ๋ช… ๋ชฉ๋ก ์ถ”์ถœ
item_names = active_sale_items["ITEMNAME"].tolist()
indexed_items = item_names
# ๊ฐ„์†Œํ™”๋œ ๋กœ๊น…
total_items = len(item_names)
logger.info(f"๐Ÿ”น ์ด {total_items}๊ฐœ ์ƒํ’ˆ ๊ณ ์† ๋ฒกํ„ฐํ™” ์‹œ์ž‘...")
# ๋ฒกํ„ฐํ™” ์ตœ์ ํ™” - ๋ฐฐ์น˜ ์‚ฌ์ด์ฆˆ ์ฆ๊ฐ€
item_vectors = await encode_texts_parallel(item_names, batch_size=2048)
# GPU ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
if device == "cuda":
torch.cuda.empty_cache()
# IVF ๊ธฐ๋ฐ˜ ์ธ๋ฑ์Šค ๊ตฌ์ถ• (์†๋„ ๋Œ€ํญ ๊ฐœ์„ )
loop = asyncio.get_event_loop()
def _build_ivf_index():
dimension = item_vectors.shape[1]
# IVF ํด๋Ÿฌ์Šคํ„ฐ ์ˆ˜ - ๋ฐ์ดํ„ฐ ํฌ๊ธฐ์— ๋”ฐ๋ผ ์กฐ์ • (โˆšn ๊ทœ์น™ ์‚ฌ์šฉ)
nlist = int(np.sqrt(total_items) * 4) # ํด๋Ÿฌ์Šคํ„ฐ ์ˆ˜ ์ฆ๊ฐ€
nlist = max(32, min(nlist, 1024)) # ์ตœ์†Œ 32, ์ตœ๋Œ€ 1024๊ฐœ ์ œํ•œ
# ์–‘์žํ™” ํŒŒ๋ผ๋ฏธํ„ฐ - ์ฐจ์› ์ˆ˜์— ๋งž๊ฒŒ ์กฐ์ •
M = min(64, dimension // 2) # ์„œ๋ธŒ๋ฒกํ„ฐ ์ˆ˜
nbits = 8 # ๋น„ํŠธ ์ˆ˜
# ๊ณ ์† IVF ์ธ๋ฑ์Šค ์ƒ์„ฑ
if total_items > 10000: # ๋ฒกํ„ฐ๊ฐ€ ๋งŽ์œผ๋ฉด ์••์ถ• ๊ธฐ๋ฒ• ์‚ฌ์šฉ
# IVF + PQ (Product Quantization) ์กฐํ•ฉ - ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ 
quantizer = faiss.IndexFlatIP(dimension)
index = faiss.IndexIVFPQ(quantizer, dimension, nlist, M, nbits)
else:
# ์ผ๋ฐ˜ IVF - ์†๋„ ํ–ฅ์ƒ
quantizer = faiss.IndexFlatIP(dimension)
index = faiss.IndexIVFFlat(quantizer, dimension, nlist)
# ํ•™์Šต ๋ฐ ์ถ”๊ฐ€
index.train(item_vectors)
index.add(item_vectors)
# ๊ฒ€์ƒ‰ ํ’ˆ์งˆ ํ–ฅ์ƒ์„ ์œ„ํ•œ ์„ค์ •
# nprobe = ๋ช‡ ๊ฐœ์˜ ํด๋Ÿฌ์Šคํ„ฐ๋ฅผ ๊ฒ€์ƒ‰ํ• ์ง€ (๋†’์„์ˆ˜๋ก ์ •ํ™•๋„ โ†‘, ์†๋„ โ†“)
index.nprobe = min(32, nlist // 4) # ํด๋Ÿฌ์Šคํ„ฐ์˜ 25% ๊ฒ€์ƒ‰
logger.info(f"โœ… IVF ์ธ๋ฑ์Šค ๊ตฌ์ถ• ์™„๋ฃŒ: clusters={nlist}, nprobe={index.nprobe}")
return index
# ์ธ๋ฑ์Šค ๊ตฌ์ถ• ์‹คํ–‰
faiss_index = await loop.run_in_executor(thread_pool, _build_ivf_index)
logger.info(f"โœ… ๊ณ ์† FAISS ์ธ๋ฑ์Šค ๊ตฌ์ถ• ์™„๋ฃŒ! ์ด {len(indexed_items)}๊ฐœ ํ•ญ๋ชฉ")
# ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
if device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# ๊ตฌ์ถ• ํ›„ Hub์— ์ €์žฅ
await save_faiss_index()
return True
# โœ… FAISS ์ธ๋ฑ์Šค ์ƒํƒœ ํ™•์ธ ๋ฐ ํ•„์š”์‹œ์—๋งŒ ๊ตฌ์ถ•
async def check_faiss_index():
"""FAISS ์ธ๋ฑ์Šค๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ์—†์œผ๋ฉด ๊ตฌ์ถ• (๋น„๋™๊ธฐ ์ง€์›)"""
global faiss_index
if faiss_index is None:
# Hub์—์„œ ๋กœ๋“œ ์‹œ๋„
if not await load_faiss_index_safe(): # ์—ฌ๊ธฐ๋ฅผ ์ˆ˜์ •
# ๋กœ๋“œ ์‹คํŒจ ์‹œ ์ƒˆ๋กœ ๊ตฌ์ถ•
logger.warning("โš ๏ธ ์ €์žฅ๋œ ์ธ๋ฑ์Šค๊ฐ€ ์—†์–ด ์ƒˆ๋กœ ๊ตฌ์ถ•ํ•ฉ๋‹ˆ๋‹ค.")
await rebuild_faiss_index()
# ๋ชจ๋“  ๊ณผ์ • ํ›„์—๋„ ์ธ๋ฑ์Šค๊ฐ€ None์ด๋ฉด ์˜ค๋ฅ˜
if faiss_index is None:
raise RuntimeError("FAISS ์ธ๋ฑ์Šค ์ดˆ๊ธฐํ™”์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.")
# โœ… ์ตœ์ ํ™”๋œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ ํ•จ์ˆ˜
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 expand_keywords_with_word2vec(keywords: list, max_new=2):
"""Word2Vec ํ‚ค์›Œ๋“œ ํ™•์žฅ ์ตœ์ ํ™”"""
global word2vec_model
if word2vec_model is None or not keywords:
return keywords
# ๊ฒฐ๊ณผ ์ €์žฅ์„ ์œ„ํ•œ ์ง‘ํ•ฉ
expanded = set(keywords)
# ์ฒ˜๋ฆฌ ์กฐ๊ธฐ ์ข…๋ฃŒ ์กฐ๊ฑด (์ตœ์ ํ™”)
if len(keywords) >= 4: # ์ด๋ฏธ ์ถฉ๋ถ„ํ•œ ํ‚ค์›Œ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด ํ™•์žฅ ๋ถˆํ•„์š”
return keywords
loop = asyncio.get_event_loop()
def _expand_keywords():
for keyword in keywords:
# ๋ถˆํ•„์š”ํ•œ ํ™•์žฅ ๋ฐฉ์ง€
if len(expanded) >= 5: # ์ตœ๋Œ€ 5๊ฐœ ํ‚ค์›Œ๋“œ๋กœ ์ œํ•œ
break
# ๋‹จ์ผ ๋‹จ์–ด์ธ ๊ฒฝ์šฐ๋งŒ ์ฒ˜๋ฆฌ (์ตœ์ ํ™”)
if keyword in word2vec_model:
# ์œ ์‚ฌ๋„๊ฐ€ ๋†’์€ ๋‹จ์–ด๋งŒ ์„ ํƒ (์ž„๊ณ„๊ฐ’ ์ ์šฉ)
similar_words = word2vec_model.most_similar(keyword, topn=max_new)
for word, score in similar_words:
if score > 0.7: # ๋†’์€ ์œ ์‚ฌ๋„ ์ž„๊ณ„๊ฐ’ ์ ์šฉ
expanded.add(word)
# ๊ฒฐ๊ณผ ๋ณ€ํ™˜
result = list(expanded)
# ํ‚ค์›Œ๋“œ๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์œผ๋ฉด ์ œํ•œ
if len(result) > 5:
return keywords + result[len(keywords):5]
return result
try:
# ํ™•์žฅ ์‹คํ–‰
expanded_keywords = await loop.run_in_executor(thread_pool, _expand_keywords)
return expanded_keywords
except Exception as e:
logger.error(f"โŒ Word2Vec ํ™•์žฅ ์˜ค๋ฅ˜: {str(e)}")
return keywords # ์˜ค๋ฅ˜ ์‹œ ์›๋ณธ ํ‚ค์›Œ๋“œ ๋ฐ˜ํ™˜
# โœ… ๋ฐฐ์น˜ ๊ฒ€์ƒ‰ ํ†ตํ•ฉ ํ•จ์ˆ˜ - ํ•œ๋ฒˆ์— ๊ฒ€์ƒ‰์œผ๋กœ ํšจ์œจ ํ–ฅ์ƒ
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
# FAISS ์ธ๋ฑ์Šค ํ™•์ธ - ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰
if faiss_index is None:
await check_faiss_index()
# ํƒ€์ด๋จธ ์‹œ์ž‘
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 []
# โœ… ์ง์ ‘ ๋งค์นญ ๋ถ„๋ฆฌ (์„ฑ๋Šฅ ์ตœ์ ํ™”)
async def find_direct_matches(query, limit=5, existing_names=None):
"""์ง์ ‘ ํ…์ŠคํŠธ ๋งค์นญ ๊ฒ€์ƒ‰ (๋ถ„๋ฆฌํ•˜์—ฌ ์ตœ์ ํ™”)"""
loop = asyncio.get_event_loop()
def _find_matches():
matches = []
query_lower = query.lower()
existing = set(existing_names or [])
# ๋ฐ์ดํ„ฐ ์ธ๋ฑ์‹ฑ ์ตœ์ ํ™”
item_dict = {}
for idx, item_name in enumerate(indexed_items):
if len(matches) >= limit:
break
if item_name in existing:
continue
if query_lower in item_name.lower():
item_dict[item_name] = idx
# ํ•œ ๋ฒˆ์— ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„ ์กฐํšŒ
if item_dict:
mask = active_sale_items["ITEMNAME"].isin(item_dict.keys())
filtered_items = active_sale_items[mask]
for _, row in filtered_items.iterrows():
if len(matches) >= limit:
break
matches.append({
"ITEMSEQ": row["ITEMSEQ"],
"ITEMNAME": row["ITEMNAME"],
"score": 1.0
})
return matches
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ์‹คํ–‰
return await loop.run_in_executor(thread_pool, _find_matches)
# โœ… 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():
# ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์„ ๋•Œ ์žฌ์‹œ๋„ ๋˜๋Š” ์˜ค๋ฅ˜ ๋ฐ˜ํ™˜
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 check_index_health():
"""์ธ๋ฑ์Šค ์ƒํƒœ๋ฅผ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ™•์ธํ•˜๋Š” ๋ฐฑ๊ทธ๋ผ์šด๋“œ ํƒœ์Šคํฌ"""
try:
# ์ธ๋ฑ์Šค ์‚ฌ์šฉ ์ƒํƒœ ํ™•์ธ
if faiss_index is None:
logger.warning("โš ๏ธ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ฒดํฌ: FAISS ์ธ๋ฑ์Šค๊ฐ€ ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
await check_faiss_index()
# ์ถ”๊ฐ€์ ์ธ ์ƒํƒœ ํ™•์ธ ๋กœ์ง์„ ์—ฌ๊ธฐ์— ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Œ
logger.debug("โœ… ์ธ๋ฑ์Šค ์ƒํƒœ ํ™•์ธ ์™„๋ฃŒ")
except Exception as e:
logger.error(f"โŒ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ธ๋ฑ์Šค ์ฒดํฌ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
# โœ… ์œ ์‚ฌ ๋‹จ์–ด ๊ฒ€์ƒ‰ API
@app.post("/api/similar_words")
async def similar_words(word: str, top_k: int = 10):
"""Word2Vec ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•œ ์œ ์‚ฌ ๋‹จ์–ด ๊ฒ€์ƒ‰ API (๋น„๋™๊ธฐ ์ง€์›)"""
try:
if word2vec_model is None:
return {"error": "Word2Vec ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."}
loop = asyncio.get_event_loop()
def _get_similar():
if word not in word2vec_model:
return []
similar = word2vec_model.most_similar(word, topn=top_k)
return [{"word": w, "similarity": float(s)} for w, s in similar]
result = await loop.run_in_executor(thread_pool, _get_similar)
if not result:
return {"word": word, "similar_words": [], "message": "๋‹จ์–ด๊ฐ€ ๋ชจ๋ธ์— ์—†์Šต๋‹ˆ๋‹ค."}
return {"word": word, "similar_words": result}
except Exception as e:
logger.error(f"โŒ ์œ ์‚ฌ ๋‹จ์–ด ๊ฒ€์ƒ‰ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
raise HTTPException(status_code=500, detail=f"์œ ์‚ฌ ๋‹จ์–ด ๊ฒ€์ƒ‰ ์˜ค๋ฅ˜: {str(e)}")
# โœ… FAISS ์ธ๋ฑ์Šค ๊ฐฑ์‹  API (๋ช…์‹œ์ ์œผ๋กœ ์š”์ฒญํ•  ๋•Œ๋งŒ ์‹คํ–‰)
@app.post("/api/update_index")
async def update_index(background_tasks: BackgroundTasks):
"""FAISS ์ธ๋ฑ์Šค๋ฅผ ์ƒˆ๋กญ๊ฒŒ ๊ตฌ์ถ• (๋ช…์‹œ์  ์š”์ฒญ ์‹œ์—๋งŒ, ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ)"""
try:
# ์ธ๋ฑ์Šค ์žฌ๊ตฌ์ถ•์„ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ํƒœ์Šคํฌ๋กœ ์‹คํ–‰
background_tasks.add_task(rebuild_and_log_index)
return {"message": "โœ… FAISS ์ธ๋ฑ์Šค ์—…๋ฐ์ดํŠธ๊ฐ€ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์‹œ์ž‘๋˜์—ˆ์Šต๋‹ˆ๋‹ค."}
except Exception as e:
logger.exception("โŒ [API] ์ธ๋ฑ์Šค ์—…๋ฐ์ดํŠธ ์ฒ˜๋ฆฌ ์ค‘ ์˜ˆ์™ธ ๋ฐœ์ƒ")
raise HTTPException(status_code=500, detail=f"์ธ๋ฑ์Šค ์—…๋ฐ์ดํŠธ ์‹คํŒจ: {str(e)}")
# ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ž‘์—…์šฉ ์ธ๋ฑ์Šค ์žฌ๊ตฌ์ถ• ํ•จ์ˆ˜
async def rebuild_and_log_index():
"""๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์ธ๋ฑ์Šค๋ฅผ ์žฌ๊ตฌ์ถ•ํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ๋กœ๊น…"""
try:
logger.info("๐Ÿ”„ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์ธ๋ฑ์Šค ์žฌ๊ตฌ์ถ• ์‹œ์ž‘")
start_time = time.time()
await rebuild_faiss_index()
elapsed = time.time() - start_time
logger.info(f"โœ… ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ธ๋ฑ์Šค ์žฌ๊ตฌ์ถ• ์™„๋ฃŒ! ์†Œ์š” ์‹œ๊ฐ„: {elapsed:.2f}์ดˆ")
except Exception as e:
logger.error(f"โŒ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ธ๋ฑ์Šค ์žฌ๊ตฌ์ถ• ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
# ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
await cleanup_memory()
# โœ… ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ํ™•์ธ ๋ฐ ๊ด€๋ฆฌ API
@app.get("/api/memory_status")
async def memory_status():
"""๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ํ™•์ธ ๋ฐ ์ •๋ฆฌ"""
try:
if device == "cuda":
# GPU ๋ฉ”๋ชจ๋ฆฌ ์ •๋ณด ์ˆ˜์ง‘
gpu_stats = {}
# PyTorch GPU ๋ฉ”๋ชจ๋ฆฌ ์ •๋ณด
torch.cuda.empty_cache() # ์บ์‹œ ์ •๋ฆฌ
gpu_stats["allocated"] = torch.cuda.memory_allocated() / (1024**3)
gpu_stats["reserved"] = torch.cuda.memory_reserved() / (1024**3)
# ๊ฐ€๋น„์ง€ ์ปฌ๋ ‰์…˜ ๊ฐ•์ œ ์‹คํ–‰
gc.collect()
# ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ ํ›„ ์ •๋ณด
torch.cuda.empty_cache()
gpu_stats["after_cleanup_allocated"] = torch.cuda.memory_allocated() / (1024**3)
gpu_stats["after_cleanup_reserved"] = torch.cuda.memory_reserved() / (1024**3)
return {
"device": "GPU",
"memory_stats": {
"allocated_gb": round(gpu_stats["allocated"], 3),
"reserved_gb": round(gpu_stats["reserved"], 3),
"after_cleanup_allocated_gb": round(gpu_stats["after_cleanup_allocated"], 3),
"after_cleanup_reserved_gb": round(gpu_stats["after_cleanup_reserved"], 3)
},
"request_count": request_count
}
else:
# CPU ๋ชจ๋“œ ์ •๋ณด
return {
"device": "CPU",
"message": "CPU ๋ชจ๋“œ์—์„œ ์‹คํ–‰ ์ค‘์ž…๋‹ˆ๋‹ค. ๋ฉ”๋ชจ๋ฆฌ ์ •๋ณด๊ฐ€ ์ œํ•œ์ ์ž…๋‹ˆ๋‹ค.",
"request_count": request_count
}
except Exception as e:
logger.error(f"โŒ ๋ฉ”๋ชจ๋ฆฌ ์ƒํƒœ ํ™•์ธ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
raise HTTPException(status_code=500, detail=f"๋ฉ”๋ชจ๋ฆฌ ์ƒํƒœ ํ™•์ธ ์˜ค๋ฅ˜: {str(e)}")
# ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ํ•จ์ˆ˜
async def periodic_memory_monitor():
"""์ฃผ๊ธฐ์ ์œผ๋กœ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰์„ ๋ชจ๋‹ˆํ„ฐ๋งํ•˜๊ณ  ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค."""
try:
worker_id = multiprocessing.current_process().name
logger.info(f"๐Ÿ”„ ์›Œ์ปค {worker_id}: ์ฃผ๊ธฐ์  ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘")
while True:
await asyncio.sleep(300) # 5๋ถ„๋งˆ๋‹ค ์‹คํ–‰
# ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
gc.collect()
if device == "cuda":
torch.cuda.empty_cache()
# ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ๋กœ๊น…
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")
# ๋žœ๋ค ์ง€์—ฐ์œผ๋กœ ๋™์‹œ ์ ‘๊ทผ ๋ฐฉ์ง€
delay = random.uniform(1.0, 5.0) # ๋” ๊ธด ์ง€์—ฐ ์‹œ๊ฐ„
logger.info(f"โฑ๏ธ ์›Œ์ปค {worker_id}: {delay:.1f}์ดˆ ์ง€์—ฐ ์ค‘...")
#delay = random.uniform(0.5, 2.0)
await asyncio.sleep(delay)
# ๋ชจ๋ธ ๋กœ๋“œ ๋ถ€๋ถ„์— ๋” ๊ฒฌ๊ณ ํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ์ถ”๊ฐ€ ----------
try:
if not 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
# ์›Œ์ปค ์ˆ˜ ์„ค์ • - ํ—ˆ๊น…ํŽ˜์ด์Šค ํ™˜๊ฒฝ ๊ณ ๋ ค
# ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ์œผ๋กœ ์›Œ์ปค ์ˆ˜ ์ตœ์†Œํ™” (2-3๊ฐœ ๊ถŒ์žฅ)
#workers = int(os.getenv("WORKERS", min(2, os.cpu_count() or 1)))
workers = int(os.getenv("WORKERS", 3))
#workers = int(os.getenv("WORKERS", 10)) #๊ณ ์‚ฌ์–‘ GPU์‚ฌ์šฉ์‹œ๋‚˜ ํ•ด๋ณผ๋งŒํ•จ
# GPU ๋ฉ”๋ชจ๋ฆฌ ๋ถ„๋ฐฐ๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ • (์—ฌ๊ธฐ์— ์ถ”๊ฐ€)
if device == "cuda":
# ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ GPU ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ
torch.cuda.set_per_process_memory_fraction(0.28) # ๊ฐ ์›Œ์ปค๊ฐ€ ์ตœ๋Œ€ 40%์˜ GPU ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์‚ฌ์šฉ
#torch.cuda.set_per_process_memory_fraction(0.09) # ๊ฐ ์›Œ์ปค๊ฐ€ ์ตœ๋Œ€ 40%์˜ GPU ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์‚ฌ์šฉ ๊ณ ์‚ฌ์–‘ 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 # ์ข…๋ฃŒ ์‹œ ๋Œ€๊ธฐ ์‹œ๊ฐ„
)