File size: 22,214 Bytes
f609ef4 91ce77c a639941 3516043 1417423 040d551 8f4291b d9e4ee7 8f4291b a3c224b d9e4ee7 1417423 60e80a3 040d551 07ea209 d3ec9d6 e8ffcd3 d9e4ee7 f609ef4 60e80a3 d9e4ee7 e3e07da d9e4ee7 8f4291b e3e07da f609ef4 60e80a3 d9e4ee7 e3e07da d9e4ee7 e3e07da b650a5d e3e07da 8f4291b d9e4ee7 8f4291b e3e07da 8f4291b d9e4ee7 e3e07da d9e4ee7 e3e07da c110fa7 e3e07da c110fa7 e3e07da c110fa7 e3e07da 91ce77c c110fa7 91ce77c e3e07da 1417423 60e80a3 5896bfc 07ea209 5896bfc 07ea209 1417423 60e80a3 07ea209 60e80a3 07ea209 60e80a3 07ea209 5896bfc 1417423 60e80a3 297071c 1417423 60e80a3 297071c 60e80a3 297071c 60e80a3 297071c 60e80a3 297071c 60e80a3 040d551 60e80a3 040d551 60e80a3 1417423 040d551 e5213b2 040d551 60e80a3 040d551 60e80a3 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 5896bfc 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 07ea209 64002c0 040d551 07ea209 64002c0 1417423 e3e07da 1417423 64002c0 07ea209 1417423 07ea209 e3e07da 07ea209 1417423 07ea209 1417423 d9e4ee7 8f4291b d9e4ee7 e3e07da 60e80a3 d9e4ee7 60e80a3 d9e4ee7 e3e07da f609ef4 60e80a3 d9e4ee7 91ce77c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
import os
import torch
import pandas as pd
import logging
import re
import faiss
import numpy as np
import time
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
from datasets import load_dataset
from huggingface_hub import login
from sentence_transformers import SentenceTransformer
from joblib import Parallel, delayed
from tqdm import tqdm
# Pydantic λͺ¨λΈ μ μ (API μ
λ ₯μ©)
class RecommendRequest(BaseModel):
search_query: str
top_k: int = 10
# πΉ λ‘κ·Έ μ€μ
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info(f"β
NumPy λ²μ : {np.__version__}")
logger.info(f"β
FAISS λ²μ : {faiss.__version__}")
# πΉ FastAPI μΈμ€ν΄μ€ μμ±
app = FastAPI(title="π νκΈ LLAMA 3.2 μΆμ² μμ€ν
API", version="1.3")
# β
λͺ¨λΈ μ 보
MODEL_NAME = "Bllossom/llama-3.2-Korean-Bllossom-3B"
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
# β
Hugging Face λ‘κ·ΈμΈ
if HF_API_TOKEN:
logger.info("π Hugging Face API ν ν°μ μ¬μ©νμ¬ λ‘κ·ΈμΈ μ€...")
login(token=HF_API_TOKEN)
else:
logger.warning("β οΈ νκ²½ λ³μ 'HF_API_TOKEN'μ΄ μ€μ λμ§ μμμ΅λλ€!")
# β
GPU μ¬μ© μ¬λΆ νμΈ
device = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"π μ€ν λλ°μ΄μ€: {device.upper()}")
# β
λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ
logger.info(f"π {MODEL_NAME} λͺ¨λΈ λ‘λ μ€...")
try:
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_API_TOKEN)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
token=HF_API_TOKEN,
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
device_map="auto" if device == "cuda" else None
)
logger.info("β
νκΈ LLAMA 3.2 λͺ¨λΈ λ‘λ μλ£!")
except Exception as e:
logger.error(f"β λͺ¨λΈ λ‘λ μ€ μ€λ₯ λ°μ: {e}")
model = None
# β
λ°μ΄ν° λ‘λ ν¨μ
def load_huggingface_jsonl(dataset_name, split="train"):
if HF_API_TOKEN:
login(token=HF_API_TOKEN)
try:
repo_id = f"aikobay/{dataset_name}"
dataset = load_dataset(repo_id, split=split)
df = dataset.to_pandas().dropna() # β
NaN κ° μ κ±°
return df
except Exception as e:
logger.error(f"β λ°μ΄ν° λ‘λ μ€ μ€λ₯ λ°μ: {e}")
return pd.DataFrame()
# β
μ§ν μ€μΈ κ²½λ§€ μν λ°μ΄ν° λ‘λ
try:
active_sale_items = load_huggingface_jsonl("initial_saleitem_dataset")
logger.info(f"β
μ§ν μ€μΈ κ²½λ§€ μν λ°μ΄ν° λ‘λ μλ£! μ΄ {len(active_sale_items)}κ° μν")
except Exception as e:
logger.error(f"β μν λ°μ΄ν° λ‘λ μ€ μ€λ₯ λ°μ: {e}")
active_sale_items = pd.DataFrame()
# β
FAISS λ²‘ν° λͺ¨λΈ
embedding_model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
# β
λ©ν°μ½μ΄ 벑ν°ν ν¨μ
def encode_texts_parallel(texts, batch_size=512):
"""λ©ν° νλ‘μΈμ±μ νμ©ν 벑ν°ν μλ μ΅μ ν"""
num_cores = os.cpu_count() # CPU κ°μ νμΈ
logger.info(f"π λ©ν°μ½μ΄ 벑ν°ν μ§ν (μ½μ΄ μ: {num_cores})")
def encode_batch(batch):
return embedding_model.encode(batch, convert_to_numpy=True)
# λ°°μΉ λ¨μλ‘ λ³λ ¬ μ²λ¦¬
text_batches = [texts[i:i + batch_size] for i in range(0, len(texts), batch_size)]
embeddings = Parallel(n_jobs=num_cores)(delayed(encode_batch)(batch) for batch in text_batches)
return np.vstack(embeddings).astype("float32")
"""
def encode_texts_parallel(texts, batch_size=128):
# μ½μ΄ μ μ ν (GPU λ©λͺ¨λ¦¬ λΆμ‘± λ°©μ§)
num_cores = min(2, os.cpu_count())
logger.info(f"π λ©ν°μ½μ΄ 벑ν°ν μ§ν (μ½μ΄ μ: {num_cores}, λ°°μΉ ν¬κΈ°: {batch_size})")
def encode_batch(batch):
try:
# κ° λ°°μΉ μ²λ¦¬ μμ/μ’
λ£ λ‘κΉ
μΆκ°
batch_id = hash(str(batch[0]))[:6] if batch else "empty"
logger.debug(f"λ°°μΉ {batch_id} μ²λ¦¬ μμ (ν¬κΈ°: {len(batch)})")
result = embedding_model.encode(batch, convert_to_numpy=True)
logger.debug(f"λ°°μΉ {batch_id} μ²λ¦¬ μλ£")
return result
except Exception as e:
logger.error(f"λ°°μΉ μΈμ½λ© μ€ μ€λ₯ λ°μ: {e}")
# μ€λ₯ λ°μ μ λΉ λ°°μ΄ λμ λλ―Έ λ°μ΄ν°λ‘ μ±μ μ 체 μ€ν¨ λ°©μ§
return np.zeros((len(batch), 384), dtype=np.float32) # SentenceTransformer λͺ¨λΈμ μΆλ ₯ μ°¨μμ λ§κ² μ‘°μ
# μ 체 λ°μ΄ν° ν¬κΈ° νμΈ
total_batches = (len(texts) + batch_size - 1) // batch_size
logger.info(f"μ΄ {total_batches}κ° λ°°μΉλ‘ λλμ΄ μ²λ¦¬ν©λλ€")
# λ°°μΉ λ¨μλ‘ λλκΈ°
text_batches = [texts[i:i + batch_size] for i in range(0, len(texts), batch_size)]
# νμμμ μ¦κ° λ° verbose νμ±ν
embeddings = Parallel(n_jobs=num_cores, timeout=600, verbose=10)(
delayed(encode_batch)(batch) for batch in text_batches
)
# κ²°κ³Ό ν©μΉκΈ°
try:
result = np.vstack(embeddings).astype("float32")
logger.info(f"β
벑ν°ν μλ£: {result.shape[0]}κ° νλͺ©, μ°¨μ: {result.shape[1]}")
return result
except Exception as e:
logger.error(f"β λ²‘ν° κ²°ν© μ€ μ€λ₯ λ°μ: {e}")
# μ¬κ°ν μ€λ₯ μ μ¬μλ λ‘μ§
logger.warning("λΉμ λμμΌλ‘ μμ°¨ μ²λ¦¬λ₯Ό μλν©λλ€...")
# μμ°¨ μ²λ¦¬λ‘ λ체 (λ리μ§λ§ μμ μ )
single_embeddings = []
for item in tqdm(texts, desc="π μμ°¨ μλ² λ© μ§ν", ncols=80):
try:
emb = embedding_model.encode(item, convert_to_numpy=True)
single_embeddings.append(emb)
except Exception as item_err:
logger.error(f"νλͺ© μΈμ½λ© μ€ μ€λ₯: {item_err}")
# μ€λ₯ λ°μ μ κΈ°λ³Έ μλ² λ© μ¬μ©
single_embeddings.append(np.zeros(384, dtype=np.float32))
return np.vstack(single_embeddings).astype("float32")
"""
# β
FAISS μΈλ±μ€ μ μ₯ & λ‘λ
def save_faiss_index():
"""FAISS μΈλ±μ€λ₯Ό Hugging Face Hubμ μ μ₯νμ¬ μλ² μ¬μμ μμλ λ°μ΄ν° μ μ§"""
from huggingface_hub import HfApi, create_repo
import tempfile
try:
# λ ν¬μ§ν 리 ID (νκ²½ λ³μμμ κ°μ Έμ€κ±°λ κΈ°λ³Έκ° μ¬μ©)
repo_id = os.getenv("HF_INDEX_REPO", "aikobay/saleitem_faiss_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)}
- λͺ¨λΈ: {MODEL_NAME}
μ΄ μ μ₯μλ, '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}")
except Exception as e:
logger.error(f"β FAISS μΈλ±μ€ Hub μ μ₯ μ€ μ€λ₯ λ°μ: {e}")
# λ‘컬μ λ°±μ
μ μ₯ μλ
try:
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}")
except Exception as local_err:
logger.error(f"β λ‘컬 λ°±μ
μ μ₯λ μ€ν¨: {local_err}")
def load_faiss_index():
"""Hugging Face Hubμμ FAISS μΈλ±μ€λ₯Ό λ‘λνμ¬ κ²μ μλ ν₯μ"""
from huggingface_hub import hf_hub_download, HfApi
global faiss_index, indexed_items, active_sale_items
# λ ν¬μ§ν 리 ID (νκ²½ λ³μμμ κ°μ Έμ€κ±°λ κΈ°λ³Έκ° μ¬μ©)
repo_id = os.getenv("HF_INDEX_REPO", "aikobay/saleitem_faiss_index")
try:
# λ ν¬μ§ν 리 μ‘΄μ¬ νμΈ
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"
)
# νμΌ λ‘λ
faiss_index = faiss.read_index(index_path)
with open(items_path, "r", encoding="utf-8") as f:
indexed_items = f.read().splitlines()
logger.info(f"β
FAISS μΈλ±μ€κ° Hubμμ λ‘λλμμ΅λλ€. μ΄ {len(indexed_items)}κ° μν")
except Exception as e:
logger.warning(f"β οΈ Hubμμ FAISS μΈλ±μ€ λ‘λ μ€ μ€λ₯ λ°μ: {e}")
# λ‘컬 νμΌ νμΈ
try:
faiss_index = faiss.read_index("faiss_index.bin")
with open("indexed_items.txt", "r", encoding="utf-8") as f:
indexed_items = f.read().splitlines()
logger.info(f"β
λ‘컬 FAISS μΈλ±μ€ λ‘λ μ±κ³΅. μ΄ {len(indexed_items)}κ° μν")
except FileNotFoundError:
logger.warning("β οΈ FAISS μΈλ±μ€ νμΌμ΄ μ‘΄μ¬νμ§ μμ΅λλ€. μλ‘ κ΅¬μΆν©λλ€.")
rebuild_faiss_index()
except Exception as local_err:
logger.error(f"β λ‘컬 FAISS μΈλ±μ€ λ‘λ μ€ μ€λ₯: {local_err}")
rebuild_faiss_index()
# β
FAISS μΈλ±μ€ μμ± (μ§νλ₯ νμ μΆκ°)
def rebuild_faiss_index():
global faiss_index, indexed_items, active_sale_items
logger.info("π μλ‘μ΄ sale_item λ°μ΄ν°λ‘ FAISS μΈλ±μ€λ₯Ό μ¬κ΅¬μΆν©λλ€...")
active_sale_items = load_huggingface_jsonl("initial_saleitem_dataset")
item_names = active_sale_items["ITEMNAME"].tolist()
logger.info(f"πΉ μ΄ {len(item_names)}κ° μν 벑ν°ν μμ...")
# λ³λ ¬ μ²λ¦¬λ₯Ό ν΅ν 벑ν°ν (λ λΉ λ₯Έ μ²λ¦¬)
item_vectors = encode_texts_parallel(item_names)
# β
FAISS μΈλ±μ€ μμ±
faiss_index = faiss.IndexFlatL2(item_vectors.shape[1])
faiss_index.add(item_vectors)
indexed_items = item_names
logger.info(f"β
FAISS μΈλ±μ€κ° {len(indexed_items)}κ° μνμΌλ‘ μλ‘κ² κ΅¬μΆλμμ΅λλ€.")
save_faiss_index()
# ν€μλ μΆμΆ ν¨μ μΆκ°
#def extract_keywords(query):
# """κ²μ 쿼리μμ μ£Όμ ν€μλ μΆμΆ λ° μ μ """
# try:
# # κΈ°λ³Έ μ μ (νΉμλ¬Έμ μ κ±°, μλ¬Έμ λ³ν λ±)
# cleaned_query = re.sub(r'[^\w\s]', ' ', query).strip().lower()
# # ννμ λΆμμ ν΅ν λͺ
μ¬ μΆμΆ
# nouns = okt.nouns(cleaned_query)
# # 2κΈμ μ΄μ λͺ
μ¬λ§ μ ν (μλ―Έμλ ν€μλ μμ£Ό)
# keywords = [noun for noun in nouns if len(noun) >= 2]
# # λͺ
μ¬κ° μκ±°λ μΆμΆ μ€ν¨ μ, μλ³Έ 쿼리μ 곡백μΌλ‘ ꡬλΆλ ν ν° μ¬μ©
# if not keywords:
# keywords = cleaned_query.split()
# return keywords
# except Exception as e:
# logger.error(f"β ν€μλ μΆμΆ μ€ μ€λ₯ λ°μ: {e}")
# # μ€λ₯ λ°μ μ μλ³Έ 쿼리 κ·Έλλ‘ λ°ν
# return [query]
# κ²μ κ²°κ³Ό ν₯μμ μν ν€μλ λ§€μΉ μ μ κ³μ° ν¨μ
#def calculate_keyword_score(item_name, keywords):
# """μμ΄ν
μ΄λ¦κ³Ό ν€μλ κ°μ λ§€μΉ μ μ κ³μ°"""
# score = 0
# item_lower = item_name.lower()
# # 1. μ 체 μΏΌλ¦¬κ° μνλͺ
μ ν¬ν¨λλ©΄ λμ μ μ
# if ''.join(keywords).lower() in item_lower:
# score += 10
# # 2. κ°λ³ ν€μλ λ§€μΉ μ μ
# for keyword in keywords:
# if keyword.lower() in item_lower:
# # μ νν μΌμΉνλ κ²½μ° λμ μ μ
# if keyword.lower() == item_lower:
# score += 15
# # μνλͺ
μ΄ ν€μλλ‘ μμνλ κ²½μ°
# elif item_lower.startswith(keyword.lower()):
# score += 8
# # λ¨μ ν¬ν¨λλ κ²½μ°
# else:
# score += 5
# return score
# κΈ°μ‘΄ extract_keywords ν¨μ λμ μ κ·μ κΈ°λ° ν¨μλ‘ λ체
def extract_keywords_simple(query):
"""νκ΅μ΄ κ²μμ΄μ μ΅μ νλ ν€μλ μΆμΆ"""
# νΉμλ¬Έμ μ κ±° λ° μλ¬Έμ λ³ν
cleaned_query = re.sub(r'[^\w\sκ°-ν£]', ' ', query).strip().lower()
# νκΈ λ¨μ΄μ μλ¬Έ λ¨μ΄ λΆλ¦¬ μ κ·μ
#pattern = re.compile(r'[κ°-ν£]+|[a-zA-Z]+')
# νκΈ λ¨μ΄ μλ¬Έ λ¨μ΄ μ€κ΅μ΄ λΆλ¦¬ μ κ·μ
pattern = re.compile(r'[κ°-ν£]+|[\u4e00-\u9fff]+|[a-zA-Z]+')
# λͺ¨λ λ§€μΉ μ°ΎκΈ°
matches = pattern.findall(cleaned_query)
# κΈΈμ΄ νν°λ§ (νκΈμ 1μ μ΄μ, μλ¬Έμ 2μ μ΄μ)
words = []
for word in matches:
if re.match(r'[κ°-ν£]+', word) and len(word) >= 1:
words.append(word)
elif re.match(r'[a-zA-Z]+', word) and len(word) >= 2:
words.append(word)
# 곡백μΌλ‘ ꡬλΆλ μλ³Έ ν ν°λ μΆκ° (볡ν©μ΄ κ³ λ €)
for token in cleaned_query.split():
if token not in words and len(token) >= 2:
words.append(token)
# λΉ λ¦¬μ€νΈμΈ κ²½μ° μλ³Έ 쿼리μ ν ν° μ¬μ©
if not words:
return [w for w in cleaned_query.split() if w]
return words
# ν€μλ λ§€μΉ μ μ κ³μ° ν¨μ κ°μ
def calculate_keyword_score(item_name, keywords):
"""κ°μ λ ν€μλ λ§€μΉ μ μ κ³μ°"""
score = 0
item_lower = item_name.lower()
# μ 체 μΏΌλ¦¬κ° μμ ν μΌμΉνλ©΄ κ°μ₯ λμ μ μ
joined_query = ''.join(keywords).lower()
if item_lower == joined_query:
return 100 # μμ μΌμΉλ μ΅κ³ μ μ
# μ 체 μΏΌλ¦¬κ° λΆλΆ μΌμΉνλ κ²½μ°
if joined_query in item_lower:
score += 50
# κ°λ³ ν€μλ λ§€μΉ (λ¨, κΈΈμ΄κ° 2μ μ΄μμΈ μλ―Έμλ ν€μλλ§)
meaningful_keywords = [k for k in keywords if len(k) >= 2]
for keyword in meaningful_keywords:
kw_lower = keyword.lower()
if kw_lower in item_lower:
# λ¨μ΄ κ²½κ³μμ μμνλμ§ νμΈ (λ μ νν λ§€μΉ)
word_boundary_match = re.search(r'(^|\s|_)' + re.escape(kw_lower), item_lower) is not None
# μ νν μΌμΉνλ κ²½μ°
if item_lower == kw_lower:
score += 40
# μνλͺ
μ΄ ν€μλλ‘ μμνλ κ²½μ°
elif item_lower.startswith(kw_lower):
score += 30
# λ¨μ΄ κ²½κ³μμ λ§€μΉλλ κ²½μ°
elif word_boundary_match:
score += 20
# λ¨μ ν¬ν¨λλ κ²½μ°
else:
score += 10
# μ μλ―Έν ν€μλκ° λ§μμλ‘ λ λμ μ μ λΆμ¬
if meaningful_keywords:
matched_keywords = sum(1 for k in meaningful_keywords if k.lower() in item_lower)
coverage_ratio = matched_keywords / len(meaningful_keywords)
score += coverage_ratio * 15
return score
# β
FAISS κ²μ ν¨μ (κ²μ μλ λͺ¨λν°λ§)
#def search_faiss(query, top_k=10):
# if faiss_index is None or indexed_items is None:
# logger.error("β FAISS μΈλ±μ€κ° μ΄κΈ°νλμ§ μμμ΅λλ€.")
# return []
# start_time = time.time() # πΉ κ²μ μκ° μΈ‘μ μμ
# query_vector = np.array([embedding_model.encode(query)]).astype("float32")
# _, indices = faiss_index.search(query_vector, top_k)
# end_time = time.time() # πΉ κ²μ μκ° μΈ‘μ λ
# logger.info(f"π κ²μ μν μλ£! κ±Έλ¦° μκ°: {end_time - start_time:.4f}μ΄")
# recommendations = []
# for idx in indices[0]:
# if idx >= len(indexed_items):
# continue
# item_name = indexed_items[idx]
# item_seq = active_sale_items.loc[active_sale_items["ITEMNAME"] == item_name, "ITEMSEQ"].values[0]
# recommendations.append({"ITEMSEQ": item_seq, "ITEMNAME": item_name})
# return recommendations
# FAISS κ²μ ν¨μ μμ
# search_faiss ν¨μ λ΄μμ extract_keywords λμ extract_keywords_simple μ¬μ©νλλ‘ μμ
def search_faiss(query, top_k=10):
if faiss_index is None or indexed_items is None:
logger.error("β FAISS μΈλ±μ€κ° μ΄κΈ°νλμ§ μμμ΅λλ€.")
return []
# ν€μλ μΆμΆ λ° λ‘κΉ
(extract_keywords_simple μ¬μ©)
keywords = extract_keywords_simple(query)
logger.info(f"π κ²μ 쿼리: '{query}' β μΆμΆ ν€μλ: {keywords}")
start_time = time.time()
# μλ³Έ λ²‘ν° κΈ°λ° κ²μ
query_vector = np.array([embedding_model.encode(query)]).astype("float32")
distances, indices = faiss_index.search(query_vector, top_k * 2) # λ λ§μ ν보 κ²μ
# κ²°κ³Όλ₯Ό μ μ₯ν 리μ€νΈ
candidates = []
# κ²μ κ²°κ³Όμ ν€μλ λ§€μΉ μ μ μΆκ°
for i, idx in enumerate(indices[0]):
if idx >= len(indexed_items):
continue
item_name = indexed_items[idx]
# ν€μλ λ§€μΉ μ μ κ³μ°
keyword_score = calculate_keyword_score(item_name, keywords)
# λ²‘ν° μ μ¬λ μ μ (거리λ₯Ό 0~1 μ¬μ΄ μ μλ‘ λ³ν)
vector_score = max(0, 100 - distances[0][i] * 10) # κ±°λ¦¬κ° μμμλ‘ μ μ λμ
# μ΅μ’
μ μ (ν€μλ λ§€μΉ κ°μ€μΉ + λ²‘ν° μ μ¬λ κ°μ€μΉ)
final_score = (keyword_score * 0.7) + (vector_score * 0.3)
try:
item_seq = active_sale_items.loc[active_sale_items["ITEMNAME"] == item_name, "ITEMSEQ"].values[0]
candidates.append({
"ITEMSEQ": item_seq,
"ITEMNAME": item_name,
"score": final_score,
"keyword_match": keyword_score > 0
})
except (IndexError, KeyError) as e:
logger.warning(f"β οΈ μν μ 보 λ§€ν μ€λ₯ (ID: {idx}): {e}")
# μ΅μ’
μ μλ‘ μ λ ¬
candidates.sort(key=lambda x: x["score"], reverse=True)
# top_kκ° μ ν
recommendations = candidates[:top_k]
end_time = time.time()
logger.info(f"π κ²μ μν μλ£! κ±Έλ¦° μκ°: {end_time - start_time:.4f}μ΄, κ²°κ³Ό: {len(recommendations)}κ°")
# κ²°κ³Ό λ‘κΉ
(μμ 3κ°λ§)
for i, rec in enumerate(recommendations[:3]):
logger.info(f" #{i+1}: {rec['ITEMNAME']} (μ μ: {rec['score']:.2f}, ν€μλ λ§€μΉ: {rec['keyword_match']})")
# API μλ΅μλ μ μ μ 보 μ μΈ
for rec in recommendations:
rec.pop("score", None)
rec.pop("keyword_match", None)
return recommendations
# β
μΆμ² API μλν¬μΈνΈ
@app.post("/api/recommend")
async def recommend(request: RecommendRequest):
try:
recommendations = search_faiss(request.search_query, request.top_k)
return {"query": request.search_query, "recommendations": recommendations}
except Exception as e:
raise HTTPException(status_code=500, detail=f"μΆμ² μ€λ₯: {str(e)}")
# β
μΈλ±μ€ κ°±μ API
@app.post("/api/update_index")
async def update_index():
rebuild_faiss_index()
return {"message": "β
FAISS μΈλ±μ€ μ
λ°μ΄νΈ μλ£!"}
# β
FastAPI μ€ν
if __name__ == "__main__":
load_faiss_index()
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|