traning / searchAsyncTunning.py
aikobay's picture
Update searchAsyncTunning.py
8f1f77d verified
raw
history blame contribute delete
37 kB
import os
import torch
import pandas as pd
import logging
import faiss
import numpy as np
import time
import gensim
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 multiprocessing
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# โœ… ๋กœ๊ทธ ์„ค์ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# โœ… ์Šค๋ ˆ๋“œ ํ’€ ์„ค์ • (๋น„๋™๊ธฐ ์ž‘์—…์„ ์œ„ํ•œ)
thread_pool = ThreadPoolExecutor(max_workers=min(64, os.cpu_count() * 4))
# โœ… 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 ๋กœ๊ทธ์ธ ์ค‘...")
login(token=HF_API_TOKEN)
else:
logger.warning("โš ๏ธ HF_API_TOKEN์ด ์„ค์ •๋˜์ง€ ์•Š์•˜๊ฑฐ๋‚˜ ํ† ํฐ ํ˜•์‹์ด ์•„๋‹™๋‹ˆ๋‹ค.")
# โœ… Word2Vec ๋ชจ๋ธ ๋กœ๋“œ
word2vec_model = None
try:
logger.info("๐Ÿ”„ Word2Vec ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
MODEL_REPO = "aikobay/item-model"
model_path = hf_hub_download(repo_id=MODEL_REPO, filename="item_vectors.bin", repo_type="dataset")
word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=True)
logger.info(f"โœ… Word2Vec ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ! ๋‹จ์–ด ์ˆ˜: {len(word2vec_model.key_to_index)}")
except Exception as e:
logger.error(f"โŒ Word2Vec ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
# โœ… KeyBERT ๋ชจ๋ธ ๋กœ๋“œ
logger.info("๐Ÿ”„ KeyBERT ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
kw_model = KeyBERT("paraphrase-multilingual-MiniLM-L12-v2")
logger.info("โœ… KeyBERT ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
# โœ… ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋”ฉ ํ•จ์ˆ˜ (lazy-load ๋ฐฉ์‹)
embedding_model = None
def get_embedding_model():
global embedding_model
if embedding_model is None:
try:
logger.info("๐Ÿ”„ ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์ค‘ (lazy-load)...")
embedding_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
logger.info("โœ… ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ!")
except Exception as e:
logger.warning(f"โš ๏ธ ํ•œ๊ตญ์–ด ํŠนํ™” ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ, ๊ธฐ๋ณธ ๋ชจ๋ธ ์‚ฌ์šฉ: {e}")
embedding_model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
return embedding_model
# โœ… ์ง„ํ–‰ ์ค‘์ธ ๊ฒฝ๋งค ์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ
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()
# ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ๋กœ๋“œ - ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋ฅผ ๋™๊ธฐ์ ์œผ๋กœ ํ˜ธ์ถœํ•˜์—ฌ ์‹œ์ž‘ ์‹œ ๋กœ๋“œ
active_sale_items = None
try:
# ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋ฅผ ์‹œ์ž‘ ์‹œ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ์ž„์‹œ ์ด๋ฒคํŠธ ๋ฃจํ”„ ์‚ฌ์šฉ
loop = asyncio.new_event_loop()
active_sale_items = loop.run_until_complete(load_huggingface_jsonl("initial_saleitem_dataset"))
loop.close()
if active_sale_items.empty:
logger.error("โŒ ๋ฐ์ดํ„ฐ์…‹์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.")
exit(1)
logger.info(f"โœ… ๊ฒฝ๋งค ์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์™„๋ฃŒ! ์ด {len(active_sale_items)}๊ฐœ ์ƒํ’ˆ")
except Exception as e:
logger.error(f"โŒ ์ƒํ’ˆ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจ: {e}")
exit(1)
# โœ… FAISS ์ธ๋ฑ์Šค ์ดˆ๊ธฐํ™”
faiss_index = None
indexed_items = []
# โœ… ๋ฉ€ํ‹ฐ์ฝ”์–ด ๋ฒกํ„ฐํ™” ํ•จ์ˆ˜
async def encode_texts_parallel(texts, batch_size=1024):
"""GPU ํ™œ์šฉ + ๋ฐฐ์น˜ ์‚ฌ์ด์ฆˆ ์ตœ์ ํ™” ๋ฒกํ„ฐํ™” (๋Œ€๊ทœ๋ชจ ์„ฑ๋Šฅ ํ–ฅ์ƒ)"""
if not texts:
return np.array([]).astype("float32")
# ๋ฐฐ์น˜ ํฌ๊ธฐ ์ฆ๊ฐ€๋กœ ์ฒ˜๋ฆฌ ํšจ์œจ ํ–ฅ์ƒ
loop = asyncio.get_event_loop()
def _encode_efficiently():
model = get_embedding_model() # โœ… ์•ˆ์ „ํ•˜๊ฒŒ ๋ชจ๋ธ ๋กœ๋”ฉ
return model.encode(
texts,
batch_size=batch_size,
convert_to_numpy=True,
show_progress_bar=False,
device=device
)
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ์‹คํ–‰
embeddings = await loop.run_in_executor(thread_pool, _encode_efficiently)
return embeddings.astype("float32")
# โœ… 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():
"""Hugging Face Hub์—์„œ FAISS ์ธ๋ฑ์Šค๋ฅผ ๋กœ๋“œ (๋น„๋™๊ธฐ ์ง€์›)"""
global faiss_index, indexed_items
# ๋ ˆํฌ์ง€ํ† ๋ฆฌ ID
repo_id = os.getenv("HF_INDEX_REPO", "aikobay/saleitem_faiss_index")
try:
# ๋น„๋™๊ธฐ ์ž‘์—…์„ ์œ„ํ•œ ๋ฃจํ”„
loop = asyncio.get_event_loop()
# ๋น„๋™๊ธฐ ์ž‘์—…์œผ๋กœ ์‹คํ–‰
def _load_index():
# ๋ ˆํฌ์ง€ํ† ๋ฆฌ ์กด์žฌ ํ™•์ธ
api = HfApi()
try:
api.repo_info(repo_id=repo_id, repo_type="dataset")
logger.info(f"โœ… FAISS ์ธ๋ฑ์Šค ๋ ˆํฌ์ง€ํ† ๋ฆฌ ํ™•์ธ: {repo_id}")
except Exception as repo_err:
logger.warning(f"โš ๏ธ ๋ ˆํฌ์ง€ํ† ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค: {repo_err}")
raise FileNotFoundError("Hub ๋ ˆํฌ์ง€ํ† ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค")
# 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()
return loaded_index, loaded_items
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ๋น„๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
loaded_index, loaded_items = await loop.run_in_executor(thread_pool, _load_index)
# ์ „์—ญ ๋ณ€์ˆ˜์— ํ• ๋‹น
faiss_index = loaded_index
indexed_items = loaded_items
logger.info(f"โœ… FAISS ์ธ๋ฑ์Šค๊ฐ€ Hub์—์„œ ๋กœ๋“œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด {len(indexed_items)}๊ฐœ ์ƒํ’ˆ")
return True
except Exception as e:
logger.warning(f"โš ๏ธ Hub์—์„œ FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
# ๋กœ์ปฌ ํŒŒ์ผ ํ™•์ธ
try:
loop = asyncio.get_event_loop()
def _load_local():
local_index_path = "faiss_index.bin"
local_items_path = "indexed_items.txt"
if os.path.exists(local_index_path) and os.path.exists(local_items_path):
loaded_index = faiss.read_index(local_index_path)
with open(local_items_path, "r", encoding="utf-8") as f:
loaded_items = f.read().splitlines()
return loaded_index, loaded_items
else:
logger.warning("โš ๏ธ ๋กœ์ปฌ FAISS ์ธ๋ฑ์Šค ํŒŒ์ผ์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
return None, None
# ์Šค๋ ˆ๋“œ ํ’€์—์„œ ๋น„๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
result = await loop.run_in_executor(thread_pool, _load_local)
if result[0] is not None:
faiss_index, indexed_items = result
logger.info(f"โœ… ๋กœ์ปฌ FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์„ฑ๊ณต. ์ด {len(indexed_items)}๊ฐœ ์ƒํ’ˆ")
return True
else:
return False
except Exception as local_err:
logger.error(f"โŒ ๋กœ์ปฌ FAISS ์ธ๋ฑ์Šค ๋กœ๋“œ ์ค‘ ์˜ค๋ฅ˜: {local_err}")
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=1024)
# ๋ฒกํ„ฐ ์ •๊ทœํ™” (์ฝ”์‚ฌ์ธ ์œ ์‚ฌ๋„๋ฅผ ์œ„ํ•ด)
norms = np.linalg.norm(item_vectors, axis=1, keepdims=True)
norms[norms == 0] = 1.0 # 0์œผ๋กœ ๋‚˜๋ˆ” ๋ฐฉ์ง€
normalized_vectors = item_vectors / norms
# 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(normalized_vectors)
index.add(normalized_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)}๊ฐœ ํ•ญ๋ชฉ")
# ๊ตฌ์ถ• ํ›„ 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():
# ๋กœ๋“œ ์‹คํŒจ ์‹œ ์ƒˆ๋กœ ๊ตฌ์ถ•
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): # top_n ๊ฐ์†Œ
"""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): # max_new ๊ฐ์†Œ
"""Word2Vec ํ‚ค์›Œ๋“œ ํ™•์žฅ ์ตœ์ ํ™”"""
global word2vec_model
if word2vec_model is None or not keywords:
return keywords
# ๊ฒฐ๊ณผ ์ €์žฅ์„ ์œ„ํ•œ ์ง‘ํ•ฉ
expanded = set(keywords)
loop = asyncio.get_event_loop()
def _expand_keywords():
for keyword in keywords:
# ๋‹จ์ผ ๋‹จ์–ด์ธ ๊ฒฝ์šฐ
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)
# ๋ณตํ•ฉ์–ด ์ฒ˜๋ฆฌ (์ฒซ ๋‹จ์–ด๋งŒ)
elif len(keyword.split()) > 1:
word = keyword.split()[0]
if word in word2vec_model and len(word) > 1:
similar = word2vec_model.most_similar(word, topn=1)
if similar and similar[0][1] > 0.8: # ๋†’์€ ์ž„๊ณ„๊ฐ’
expanded.add(similar[0][0])
# ๊ฒฐ๊ณผ ๋ณ€ํ™˜
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 # ์˜ค๋ฅ˜ ์‹œ ์›๋ณธ ํ‚ค์›Œ๋“œ ๋ฐ˜ํ™˜
# โœ… ์ตœ์ ํ™”๋œ search_faiss_with_keywords ํ•จ์ˆ˜
async def search_faiss_with_keywords(query: str, top_k: int = 5, keywords=None, expanded_keywords=None):
"""๊ณ ์† ํ‚ค์›Œ๋“œ ๊ธฐ๋ฐ˜ FAISS ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰"""
global faiss_index, indexed_items
# FAISS ์ธ๋ฑ์Šค ํ™•์ธ - ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰
if faiss_index is None:
await check_faiss_index()
# ํƒ€์ด๋จธ ์‹œ์ž‘
start_time = time.time()
# ๋ณ‘๋ ฌ ์‹คํ–‰์„ ์œ„ํ•œ ์ค€๋น„
loop = asyncio.get_event_loop()
# 1. ํ‚ค์›Œ๋“œ ์ถ”์ถœ ๋ฐ ํ™•์žฅ ์ตœ์ ํ™”
if keywords is None:
keywords = await extract_keywords(query)
if expanded_keywords is None:
expanded_keywords = await expand_keywords_with_word2vec(keywords)
# 2. ๋ฒกํ„ฐ ์ธ์ฝ”๋”ฉ ์ตœ์ ํ™” - ์ฟผ๋ฆฌ์™€ ํ‚ค์›Œ๋“œ ํ•œ ๋ฒˆ์— ์ฒ˜๋ฆฌ
search_texts = [query] + expanded_keywords
# ๋ฒกํ„ฐ ์ธ์ฝ”๋”ฉ - ์ตœ์ ํ™”๋œ ํ•จ์ˆ˜ ์‚ฌ์šฉ
all_vectors = await encode_texts_parallel(search_texts)
# ๋ฒกํ„ฐ ์ •๊ทœํ™” - ์ตœ์ ํ™”๋œ ๋ฐฉ์‹
def normalize_batch(vectors):
if vectors.size == 0:
return vectors
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
norms[norms == 0] = 1.0 # 0์œผ๋กœ ๋‚˜๋ˆ” ๋ฐฉ์ง€
return vectors / norms
# ๋ฒกํ„ฐ ์ •๊ทœํ™” ์‹คํ–‰
all_vectors = await loop.run_in_executor(thread_pool, lambda: normalize_batch(all_vectors))
# ์ฟผ๋ฆฌ ๋ฒกํ„ฐ์™€ ํ‚ค์›Œ๋“œ ๋ฒกํ„ฐ ๋ถ„๋ฆฌ
if len(all_vectors) > 0:
query_vector = all_vectors[0:1]
keyword_vectors = all_vectors[1:] if len(all_vectors) > 1 else np.array([])
else:
return [] # ๋ฒกํ„ฐํ™” ์‹คํŒจ ์‹œ ๋นˆ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
# 3. FAISS ๊ฒ€์ƒ‰ ์ตœ์ ํ™” - ์ผ๊ด„ ๋ฐฐ์น˜ ์ฒ˜๋ฆฌ
def _optimized_batch_search():
all_results = {}
# ์ฟผ๋ฆฌ ๋ฒกํ„ฐ ๊ฒ€์ƒ‰ (๊ฐ€์ค‘์น˜ 3๋ฐฐ๋กœ ์ฆ๊ฐ€)
if query_vector.shape[0] > 0:
distances, indices = faiss_index.search(query_vector, top_k * 2)
# ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ๊ฐ€์ค‘์น˜ ์ ์šฉ (์ค‘์š”๋„ ์ƒํ–ฅ)
for idx, dist in zip(indices[0], distances[0]):
if idx < len(indexed_items):
all_results[idx] = dist * 3.0 # ๊ฐ€์ค‘์น˜ 3.0
# ํ‚ค์›Œ๋“œ ๋ฒกํ„ฐ ๋ฐฐ์น˜ ๊ฒ€์ƒ‰
if keyword_vectors.shape[0] > 0:
# ๋ฐฐ์น˜ ๊ฒ€์ƒ‰ ํ•œ ๋ฒˆ์— ์ฒ˜๋ฆฌ
k_distances, k_indices = faiss_index.search(keyword_vectors, top_k)
# ํ‚ค์›Œ๋“œ๋ณ„ ๊ฐ€์ค‘์น˜ ์ ์šฉ ๋ฐ ๊ฒฐ๊ณผ ๋ณ‘ํ•ฉ
for i in range(keyword_vectors.shape[0]):
for j, (idx, dist) in enumerate(zip(k_indices[i], k_distances[i])):
if idx < len(indexed_items):
# ์ˆœ์œ„์— ๋”ฐ๋ผ ๊ฐ€์ค‘์น˜ ์ฐจ๋“ฑ ์ ์šฉ (์ƒ์œ„ ๊ฒฐ๊ณผ ์šฐ๋Œ€)
rank_weight = 1.0 / (1 + j * 0.2) # ์ˆœ์œ„๋ณ„ ๊ฐ€์ค‘์น˜ ๊ฐ์†Œ
weight = 0.6 * rank_weight # ๊ธฐ๋ณธ ๊ฐ€์ค‘์น˜ 0.6
# ๊ธฐ์กด ์ ์ˆ˜์— ์ถ”๊ฐ€
all_results[idx] = all_results.get(idx, 0) + dist * weight
return all_results
# ์ตœ์ ํ™”๋œ ๋ฐฐ์น˜ ๊ฒ€์ƒ‰ ์‹คํ–‰
result_scores = await loop.run_in_executor(thread_pool, _optimized_batch_search)
# 4. ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ๋ฐ ์ •๋ ฌ ์ตœ์ ํ™”
def _process_results():
# ์ž„๊ณ„๊ฐ’ ํ•„ํ„ฐ๋ง ๋ฐ ์ •๋ ฌ
filtered_items = [(idx, score) for idx, score in result_scores.items()
if score >= 0.3] # ์ตœ์†Œ ์ ์ˆ˜ ํ•„ํ„ฐ๋ง
# ์ ์ˆ˜ ๊ธฐ์ค€ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
sorted_items = sorted(filtered_items, key=lambda x: x[1], reverse=True)
# ์ตœ์ข… ๊ฒฐ๊ณผ ๋ณ€ํ™˜
recommendations = []
for idx, score in sorted_items[:top_k]: # top_k๊ฐœ๋งŒ ์ฒ˜๋ฆฌ
item_name = indexed_items[idx]
try:
# ๋ฉ”๋ชจ๋ฆฌ ๋‚ด ์กฐํšŒ ์ตœ์ ํ™”
mask = active_sale_items["ITEMNAME"] == item_name
if mask.any():
item_seq = active_sale_items.loc[mask, "ITEMSEQ"].values[0]
recommendations.append({
"ITEMSEQ": item_seq,
"ITEMNAME": item_name,
"score": float(score)
})
except (IndexError, KeyError):
continue
return recommendations
# ๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ์‹คํ–‰
recommendations = await loop.run_in_executor(thread_pool, _process_results)
# 5. ์ง์ ‘ ๋งค์นญ ์ถ”๊ฐ€ ์ตœ์ ํ™” (ํ•„์š”ํ•œ ๊ฒฝ์šฐ์—๋งŒ)
if len(recommendations) < top_k:
direct_matches = await find_direct_matches(query,
top_k - len(recommendations),
[r["ITEMNAME"] for r in recommendations])
if direct_matches:
recommendations.extend(direct_matches)
# ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด 1์ดˆ ์ด์ƒ์ธ ๊ฒฝ์šฐ์—๋งŒ ๋กœ๊น…
elapsed = time.time() - start_time
if elapsed > 1.0:
logger.info(f"๐Ÿ” ๊ฒ€์ƒ‰ ์™„๋ฃŒ | ์†Œ์š”์‹œ๊ฐ„: {elapsed:.2f}์ดˆ | ๊ฒฐ๊ณผ: {len(recommendations)}๊ฐœ")
return recommendations[:top_k]
# โœ… ์ง์ ‘ ๋งค์นญ ๋ถ„๋ฆฌ (์„ฑ๋Šฅ ์ตœ์ ํ™”)
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 # ํ‚ค์›Œ๋“œ ํ™•์žฅ ์‚ฌ์šฉ ์—ฌ๋ถ€
# โœ… ์ถ”์ฒœ API ์—”๋“œํฌ์ธํŠธ
# โœ… ์ตœ์ ํ™”๋œ recommend API ์—”๋“œํฌ์ธํŠธ
@app.post("/api/recommend")
async def recommend(request: RecommendRequest, background_tasks: BackgroundTasks):
"""๊ณ ์† ์ถ”์ฒœ API (I/O ๋ณ‘๋ ฌํ™” + ๋ถˆํ•„์š” ์ž‘์—… ์ œ๊ฑฐ)"""
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 ๋ฒ”์œ„๋กœ ์ œํ•œ
# ๋ณ‘๋ ฌ ํ”„๋กœ์„ธ์‹ฑ์„ ์œ„ํ•œ ๋™์‹œ ์‹คํ–‰
keywords, expanded_keywords = await asyncio.gather(
extract_keywords(search_query),
expand_keywords_with_word2vec(
[search_query.split()[0]] if search_query.split() else [search_query],
max_new=2
) if request.use_expansion else None
)
# ๊ฒ€์ƒ‰ ์‹คํ–‰ - ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ๋œ ํ‚ค์›Œ๋“œ ํ™œ์šฉ
recommendations = await search_faiss_with_keywords(
search_query,
top_k,
keywords,
expanded_keywords
)
# ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
result = {
"query": search_query,
"recommendations": recommendations,
"keywords": keywords if len(keywords) > 0 else None,
"expanded_keywords": expanded_keywords if expanded_keywords and len(expanded_keywords) > 0 else None
}
# ์‘๋‹ต ์‹œ๊ฐ„ ์ธก์ • (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)}")
# โœ… ์ธ๋ฑ์Šค ๋””๋ฒ„๊น… API
@app.get("/api/debug_index")
async def debug_index(query: str, top_k: int = 20):
"""์ธ๋ฑ์Šค ๋””๋ฒ„๊น…์„ ์œ„ํ•œ API (๋น„๋™๊ธฐ ์ง€์›)"""
try:
await check_faiss_index()
loop = asyncio.get_event_loop()
def _get_vector():
model = get_embedding_model() # โœ… ๋ชจ๋ธ ๊ฐ€์ ธ์˜ค๊ธฐ
vector = model.encode(query, convert_to_numpy=True).astype("float32")
norm = np.linalg.norm(vector)
normalized_vector = vector / norm
return normalized_vector, norm
normalized_vector, norm = await loop.run_in_executor(thread_pool, _get_vector)
# ์›๋ณธ ์ฟผ๋ฆฌ๋กœ ๊ฒ€์ƒ‰ (๋น„๋™๊ธฐ)
def _search():
return faiss_index.search(np.array([normalized_vector]), top_k)
distances, indices = await loop.run_in_executor(thread_pool, _search)
# ๊ฒฐ๊ณผ ๋งคํ•‘
results = []
for i, (idx, dist) in enumerate(zip(indices[0], distances[0])):
if idx < len(indexed_items):
item_name = indexed_items[idx]
results.append({
"rank": i + 1,
"index": int(idx),
"item_name": item_name,
"distance/score": float(dist)
})
# ๋ฐ์ดํ„ฐ์…‹์— ํ•ด๋‹น ๋‹จ์–ด๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ (๋น„๋™๊ธฐ)
def _find_matches():
contains = [item for item in indexed_items if query.lower() in item.lower()][:5]
exact = [item for item in indexed_items if query.lower() == item.lower()]
return contains, exact
contains_query, exact_matches = await loop.run_in_executor(thread_pool, _find_matches)
return {
"query": query,
"vector_norm": float(norm),
"contains_query": contains_query,
"exact_matches": exact_matches,
"results": results
}
except Exception as e:
logger.error(f"โŒ ์ธ๋ฑ์Šค ๋””๋ฒ„๊น… ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
raise HTTPException(status_code=500, detail=f"์ธ๋ฑ์Šค ๋””๋ฒ„๊น… ์˜ค๋ฅ˜: {str(e)}")
# โœ… ๋ฌธ์ž์—ด ํฌํ•จ ๊ฒ€์ƒ‰ API
@app.get("/api/text_search")
async def text_search(query: str, top_k: int = 10):
"""๋‹จ์ˆœ ํ…์ŠคํŠธ ํฌํ•จ ๊ฒ€์ƒ‰ API (๋น„๋™๊ธฐ ์ง€์›)"""
try:
loop = asyncio.get_event_loop()
# ๋น„๋™๊ธฐ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜
def _text_search():
# ๋‹จ์ˆœ ํ…์ŠคํŠธ ํฌํ•จ ๊ฒ€์ƒ‰
matched_items = []
for idx, item_name in enumerate(indexed_items):
if query.lower() in item_name.lower():
try:
item_seq = active_sale_items.loc[active_sale_items["ITEMNAME"] == item_name, "ITEMSEQ"].values[0]
matched_items.append({"ITEMSEQ": item_seq, "ITEMNAME": item_name, "match_type": "contains"})
except (IndexError, KeyError):
continue
# ์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋Š” ํ•ญ๋ชฉ์„ ์•ž์œผ๋กœ
exact_matches = []
partial_matches = []
for item in matched_items:
if query.lower() == item["ITEMNAME"].lower():
item["match_type"] = "exact"
exact_matches.append(item)
else:
partial_matches.append(item)
# ๊ฒฐํ•ฉ ๋ฐ ์ œํ•œ
return exact_matches + partial_matches
# ๋น„๋™๊ธฐ์ ์œผ๋กœ ๊ฒ€์ƒ‰ ์‹คํ–‰
results = await loop.run_in_executor(thread_pool, _text_search)
logger.info(f"๐Ÿ” ํ…์ŠคํŠธ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ: {len(results)}๊ฐœ ์ฐพ์Œ, ์ฟผ๋ฆฌ: '{query}'")
return {
"query": query,
"total_matches": len(results),
"results": results[:top_k]
}
except Exception as e:
logger.error(f"โŒ ํ…์ŠคํŠธ ๊ฒ€์ƒ‰ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
raise HTTPException(status_code=500, detail=f"ํ…์ŠคํŠธ ๊ฒ€์ƒ‰ ์˜ค๋ฅ˜: {str(e)}")
# โœ… FastAPI ์‹คํ–‰
if __name__ == "__main__":
# ์„œ๋ฒ„ ์‹œ์ž‘ ์‹œ ์ €์žฅ๋œ ์ธ๋ฑ์Šค ๋กœ๋“œ ์‹œ๋„
try:
# ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋ฅผ ๋™๊ธฐ์ ์œผ๋กœ ํ˜ธ์ถœํ•˜๊ธฐ ์œ„ํ•œ ์ž„์‹œ ์ด๋ฒคํŠธ ๋ฃจํ”„ ์‚ฌ์šฉ
loop = asyncio.new_event_loop()
if not loop.run_until_complete(load_faiss_index()):
logger.warning("โš ๏ธ ๊ธฐ์กด ์ธ๋ฑ์Šค ๋กœ๋“œ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฆ‰์‹œ ์ƒˆ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌ์ถ•ํ•ฉ๋‹ˆ๋‹ค.")
# ์ธ๋ฑ์Šค ์ฆ‰์‹œ ์žฌ๊ตฌ์ถ•
loop.run_until_complete(rebuild_faiss_index())
logger.info("โœ… FAISS ์ธ๋ฑ์Šค ์ƒ์„ฑ ์™„๋ฃŒ!")
else:
logger.info("โœ… ๊ธฐ์กด ์ธ๋ฑ์Šค๋ฅผ ์„ฑ๊ณต์ ์œผ๋กœ ๋กœ๋“œํ–ˆ์Šต๋‹ˆ๋‹ค.")
loop.close()
except Exception as e:
logger.error(f"โŒ ์ธ๋ฑ์Šค ์ดˆ๊ธฐ ๊ตฌ์ถ• ์‹คํŒจ: {e}")
logger.warning("โš ๏ธ ์ธ๋ฑ์Šค ์—†์ด ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ์ด ์ œํ•œ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
import uvicorn
uvicorn.run("searchAsyncTunning:app",
host="0.0.0.0",
port=7860,
workers=8,
loop="uvloop",
http="httptools",
limit_concurrency=200,
timeout_keep_alive=5)