File size: 36,638 Bytes
c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed b8c7ffb c8635ed |
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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 |
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
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 HF_API_TOKEN:
logger.info("๐ Hugging Face API ๋ก๊ทธ์ธ ์ค...")
login(token=HF_API_TOKEN)
else:
logger.error("โ 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")
original_embedding_model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")
logger.info("โ
KeyBERT ๋ชจ๋ธ ๋ก๋ ์๋ฃ!")
# โ
ํ๊ตญ์ด ํนํ ์๋ฒ ๋ฉ ๋ชจ๋ธ๋ก ๊ต์ฒด
embedding_model = None
try:
logger.info("๐ ํ๊ตญ์ด ํนํ ์๋ฒ ๋ฉ ๋ชจ๋ธ๋ก ๊ต์ฒด ์๋...")
# ํ๊ตญ์ด ํนํ ๋ชจ๋ธ ๋ก๋ ์๋ (์คํจ์ ๊ธฐ์กด ๋ชจ๋ธ ์ ์ง)
embedding_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
logger.info("โ
ํ๊ตญ์ด ํนํ ์๋ฒ ๋ฉ ๋ชจ๋ธ ๋ก๋ ์๋ฃ!")
except Exception as e:
logger.warning(f"โ ๏ธ ํ๊ตญ์ด ํนํ ๋ชจ๋ธ ๋ก๋ ์คํจ, ๊ธฐ์กด ๋ชจ๋ธ ์ ์ง: {e}")
embedding_model = original_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():
# ๋ฒกํฐํ ์ต์ ํ - GPU ํ์ฉ + ๋ฐฐ์น ์ฌ์ด์ฆ ์ต์ ํ
return embedding_model.encode(
texts,
batch_size=batch_size,
convert_to_numpy=True,
show_progress_bar=False,
device=device # GPU ์ฌ์ฉ
)
# ์ค๋ ๋ ํ์์ ์คํ
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():
vector = embedding_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(app, host="0.0.0.0", port=7860) |