-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBeeMall_Chatbot.py
More file actions
2332 lines (1952 loc) · 96.6 KB
/
BeeMall_Chatbot.py
File metadata and controls
2332 lines (1952 loc) · 96.6 KB
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import base64
import json
import logging
import os
import re
import time
import urllib
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Union, List, Dict, Any, Tuple
from urllib.parse import quote
import math
import random
import numpy as np
import pandas as pd
import redis
import requests
import uvicorn
from dotenv import load_dotenv
from fastapi import APIRouter, BackgroundTasks, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from langchain_community.chat_message_histories import (
ChatMessageHistory,
RedisChatMessageHistory,
)
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI, OpenAIEmbeddings, OpenAI
from pydantic import BaseModel
from pymilvus import (
connections, utility,
FieldSchema, CollectionSchema,
DataType, Collection
)
from langdetect import detect
from openai import OpenAI as OpenAIClient # 공식 OpenAI 클라이언트
import uvicorn
from collections import defaultdict, Counter
from itertools import zip_longest
executor = ThreadPoolExecutor()
# ✅ 환경 변수 로드
load_dotenv()
API_KEY = os.getenv('OPENAI_API_KEY')
REDIS_URL = "redis://localhost:6379/0"
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
MANYCHAT_API_KEY = os.getenv('MANYCHAT_API_KEY')
key = os.getenv("MANYCHAT_API_KEY")
if isinstance(key, str) and "\x3a" in key:
key = key.replace("\x3a", ":")
LLM_MODEL = "gpt-4.1-mini"
EMB_MODEL = "text-embedding-3-small"
max_total=10 #몇개의 상품을 나올지
# 클라이언트 및 래퍼
client = OpenAIClient(api_key=API_KEY)
llm = OpenAI(api_key=API_KEY, model=LLM_MODEL, temperature=0)
embedder = OpenAIEmbeddings(api_key=API_KEY, model=EMB_MODEL) # ← embedder 정의 추가
# API_URL = os.getenv("API_URL", "").rstrip("/") # 예:
API_URL = "https://fb-narosu.duckdns.org" # 예:
print(f"🔍 로드된 VERIFY_TOKEN: {VERIFY_TOKEN}")
print(f"🔍 로드된 PAGE_ACCESS_TOKEN: {PAGE_ACCESS_TOKEN}")
print(f"🔍 로드된 API_KEY: {API_KEY}")
print(f"🔍 로드된 API_URL: {API_URL}")
# # ✅ FAISS 인덱스 파일 경로 설정
# faiss_file_path = f"04_28_faiss_3s.faiss"
# ─── Milvus import & 연결 ───────────────────────────────────────────────
# 올바른 공인 IP와 포트
connections.connect(
alias="default",
host="114.110.135.96",
port="19530"
)
print("✅ Milvus에 연결되었습니다.")
# OpenAI Embedding 모델 (쿼리용)
emb_model = OpenAIEmbeddings(
model="text-embedding-3-small",
openai_api_key=os.getenv("OPENAI_API_KEY")
)
# ────────────────────────────────────────────────────────────────────────
collection_cat = Collection("category_0821")
results = collection_cat.query(
expr="category_full != ''",
output_fields=["category_full"]
)
# ── 중복 제거하며 순서 보존해서 리스트 만들기 ─────────
seen = set()
categories = []
for row in results:
cat = row["category_full"]
if cat and cat not in seen:
seen.add(cat)
categories.append(cat)
print(f"✅ Milvus에서 불러온 카테고리 개수: {len(categories)}")
# 컬렉션 이름
collection_name = "ownerclan_weekly_0428"
# 컬렉션 객체 생성 (조회 용도)
collection = Collection(name=collection_name)
# 💡 저장된 벡터 수 확인
print(f"\n📊 저장된 엔트리 수: {collection.num_entities}")
def get_redis():
return redis.Redis.from_url(REDIS_URL)
# ✅ FastAPI 인스턴스 생성
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[API_URL, # 실제 배포 URL
"http://localhost:5050"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
# 로깅 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("response_time_logger")
print(f"🔐 API KEY: {MANYCHAT_API_KEY}")
# 응답 속도 측정을 위한 미들웨어 추가
@app.middleware("http")
async def measure_response_time(request: Request, call_next):
start_time = time.time() # 요청 시작 시간
response = await call_next(request) # 요청 처리
process_time = time.time() - start_time # 처리 시간 계산
response.headers["ngrok-skip-browser-warning"] = "1"
response.headers["X-Frame-Options"] = "ALLOWALL" # 또는 제거 방식도 가능 #BeeMall 챗봇 Iframe 막히는것 때문에 헤더 추가가
response.headers["Content-Security-Policy"] = "frame-ancestors *" #BeeMall 챗봇 Iframe 막히는것 때문에 헤더 추가가
# '/chatbot' 엔드포인트에 대한 응답 속도 로깅
if request.url.path == "/webhook":
print(f"📊 [TEST] Endpoint: {request.url.path}, 처리 시간: {process_time:.4f} 초") # print로 직접 확인
logger.info(f"📊 [Endpoint: {request.url.path}] 처리 시간: {process_time:.4f} 초")
response.headers["X-Process-Time"] = str(process_time) # 응답 헤더에 처리 시간 추가
return response
# ✅ Jinja2 템플릿 설정
templates = Jinja2Templates(directory="templates")
# 요청 모델
class QueryRequest(BaseModel):
query: str
# ✅ JSON 직렬화를 위한 int 변환 함수
def convert_to_serializable(obj):
# None 값 처리
if obj is None:
return 999
# 숫자 타입 처리
if isinstance(obj, (np.int64, np.int32, np.float32, np.float64)):
val = obj.item()
return max(0, val) # 음수값은 0으로 처리
# 문자열 처리 (숫자로 변환 가능한 경우)
if isinstance(obj, str):
try:
val = float(obj.replace(",", ""))
return max(0, int(val)) # 음수값은 0으로 처리
except:
return 999
# 그 외의 경우
try:
val = float(obj)
return max(0, int(val)) # 음수값은 0으로 처리
except:
return 999
def get_session_history(session_id: str) -> BaseChatMessageHistory:
"""Redis에서 세션 기록을 가져옵니다."""
try:
history = RedisChatMessageHistory(session_id=session_id, url=REDIS_URL)
# 세션이 존재하는지 확인
messages = history.messages
return history
except Exception as e:
print(f"❌ 대화 기록 가져오기 오류: {e}")
# 에러 발생 시 새로운 히스토리 객체 생성
return RedisChatMessageHistory(session_id=session_id, url=REDIS_URL)
def clear_message_history(session_id: str):
"""
Redis에 저장된 특정 세션의 대화 기록을 초기화합니다.
"""
try:
history = RedisChatMessageHistory(session_id=session_id, url=REDIS_URL)
history.clear()
print(f"✅ 세션 {session_id}의 대화 기록이 초기화되었습니다.")
except Exception as e:
print(f"❌ Redis 초기화 오류: {e}")
raise HTTPException(status_code=500, detail="대화 기록 초기화 중 오류가 발생했습니다.")
def quota_to_text(quota: Dict[str, int]) -> str:
return "\n".join([f'- {cat}: {q}개' for cat, q in quota.items()])
def compute_category_proportions(
candidates: List[Dict[str, Any]]
) -> Dict[str, float]:
total = len(candidates)
if total == 0:
return {}
counts = Counter(item["카테고리"] for item in candidates)
return {cat: cnt / total for cat, cnt in counts.items()}
# 🔥 상품 캐시 (전역 선언)
PRODUCT_CACHE = {}
# 🔗 구매하기 버튼 클릭 시 호출되는 ManyChat용 Hook 주소
MANYCHAT_HOOK_BASE_URL = f"{API_URL}/product-select"
@app.get("/webhook")
async def verify_webhook(request: Request):
try:
mode = request.query_params.get("hub.mode")
token = request.query_params.get("hub.verify_token")
challenge = request.query_params.get("hub.challenge")
print(f"🔍 받은 Verify Token: {token}")
print(f"🔍 서버 Verify Token: {VERIFY_TOKEN}")
if mode == "subscribe" and token == VERIFY_TOKEN:
print("✅ 웹훅 인증 성공")
return int(challenge)
else:
print("❌ 웹훅 인증 실패")
return {"status": "error", "message": "Invalid token"}
except Exception as e:
print(f"❌ 인증 처리 오류: {e}")
return {"status": "error", "message": str(e)}
@app.post("/webhook")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
start_time = time.time()
try:
# ✅ Step 1: 요청 데이터 파싱
data = await request.json()
parse_time = time.time() - start_time
logger.info(f"📊 [Parse Time]: {parse_time:.4f} 초")
# ✅ Step 2: 메시지 처리 시작
process_start = time.time()
if data.get("field") == "messages":
value = data.get("value", {})
sender_id = value.get("sender", {}).get("id")
user_message = value.get("message", {}).get("text", "").strip()
postback = value.get("postback", {})
# ✅ postback 처리
postback_payload = postback.get("payload")
if postback_payload and postback_payload.startswith("BUY::"):
product_code = postback_payload.split("::")[1]
background_tasks.add_task(handle_product_selection, sender_id, product_code)
return {
"version": "v2",
"content": {
"messages": [
{"type": "text", "text": f"✅ 상품 {product_code} 정보가 전송되었습니다!"}
]
}
}
# ✅ reset 처리
if sender_id and user_message:
if user_message.lower() == "reset":
print(f"🔄 [RESET] 세션 {sender_id}의 대화 기록 초기화!")
clear_message_history(sender_id)
return {
"version": "v2",
"content": {
"messages": [
{
"type": "text",
"text": f"🔄 All cleaned up and ready to start~ \n💬 Enter a keyword and let the AI work its magic 🛍️."
}
]
},
"message": f"{sender_id}님의 대화 기록이 초기화되었습니다."
}
# ✅ 일반 메시지 → AI 응답 처리
background_tasks.add_task(process_ai_response, sender_id, user_message)
process_time = time.time() - process_start
logger.info(f"📊 [Processing Time 전체]: {process_time:.4f} 초")
# 기본 응답
return {
"version": "v2",
"content": {
"messages": [
{
"type": "text",
"text": "🛍️ Just a moment, smart picks coming soon! ⏳"
}
]
}
}
except Exception as e:
print(f"❌ 웹훅 처리 오류: {e}")
raise HTTPException(status_code=500, detail=str(e))
# 🔁 추천 응답 처리 함수
async def process_ai_response(sender_id: str, user_message: str):
try:
print(f"🕒 [AI 처리 시작] 유저 ID: {sender_id}, 메시지: {user_message}")
# ✅ 외부 응답 생성 (동기 → 비동기 실행)
loop = asyncio.get_running_loop()
bot_response = await loop.run_in_executor(executor, external_search_and_generate_response, user_message, sender_id)
# ✅ 응답 확인 및 메시지 준비
if isinstance(bot_response, dict):
combined_message_text = bot_response.get("combined_message_text", "")
results = bot_response.get("results", [])
# ✅ 상품 캐시에 저장 (product_code → 상품 딕셔너리 전체 저장)
for product in results:
product_code = product.get("상품코드")
if product_code:
PRODUCT_CACHE[product_code] = product
messages_data = []
# ✅ AI 응답 메시지 먼저 추가
if combined_message_text:
messages_data.append({
"type": "text",
"text": combined_message_text
})
# ✅ 카드형 메시지를 하나로 묶기 위한 elements 리스트
cards_elements = []
for product in results:
product_code = product.get("상품코드", "None")
# 가격과 배송비 정수 변환 후 포맷팅
try:
price = int(float(product.get("가격", 0)))
except:
price = 0
try:
shipping = int(float(product.get("배송비", 0)))
except:
shipping = 0
cards_elements.append({
"title": f"✨ {product['제목']}",
"subtitle": (
f"가격: {price:,}원\n"
f"배송비: {shipping:,}원\n"
f"원산지: {product.get('원산지', '')}"
),
"image_url": product.get("이미지", ""),
"buttons": [
{
"type": "url",
"caption": "🤩 View Product 🧾",
"url": product.get("상품링크", "#")
},
{
"type": "dynamic_block_callback",
"caption": "🛍️ Buy Now 💰",
"url": f"{API_URL}/product-select",
"method": "post",
"payload": {
"product_code": product_code,
"sender_id": sender_id
}
}
]
})
# ✅ 전체 카드 메시지로 추가
messages_data.append({
"type": "cards",
"image_aspect_ratio": "horizontal", # 또는 "square"
"elements": cards_elements
})
# ✅ 메시지 전송
send_message(sender_id, messages_data)
print(f"✅ [Combined 메시지 전송 완료]: {combined_message_text}")
print(f"버튼 생성용 product_code: {product_code}")
# print("✅ 최종 messages_data:", json.dumps(messages_data, indent=2, ensure_ascii=False))
else:
print(f"❌ AI 응답 오류 발생")
except Exception as e:
print(f"❌ AI 응답 처리 오류: {e}")
def clean_html_content(html_raw: str) -> str:
try:
html_cleaned = html_raw.replace('\n', '').replace('\r', '')
html_cleaned = html_cleaned.replace(""", "\"").replace(""", "\"").replace("'", "'").replace("'", "'")
if html_cleaned.count("<center>") > html_cleaned.count("</center>"):
html_cleaned += "</center>"
if html_cleaned.count("<p") > html_cleaned.count("</p>"):
html_cleaned += "</p>"
return html_cleaned
except Exception as e:
print(f"❌ HTML 정제 오류: {e}")
return html_raw
##=========================================================================
# 디버깅용 요청 모델
class DebugRequest(BaseModel):
query: str
session_id: Optional[str] = None
# 디버깅 엔드포인트 추가
@app.post("/debug-search")
async def debug_search(data: DebugRequest):
"""
external_search_and_generate_response를 바로 호출해서
결과 payload를 JSON으로 반환합니다.
"""
try:
# sync 함수라도 바로 호출 가능
result = external_search_and_generate_response(data.query, data.session_id)
return JSONResponse(content=result)
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
##=========================================================================
'''####################################################################################################################
external_search_and_generate_response는 ManyChat 같은 외부 서비스와 연동되는 챗봇용 API이고, 구축된 UI 에는 사용되지 않음.
'''
# ✅ 외부 검색 및 응답 생성 함수
def external_search_and_generate_response(request: Union[QueryRequest, str], session_id: str = None) -> dict:
try:
start_time = time.time() # 시작 시간 기록
# ✅ 입력 쿼리 추출 및 타입 확인
query = request if isinstance(request, str) else request.query
print(f"🔍 사용자 검색어: {query}")
if not isinstance(query, str):
raise TypeError(f"❌ [ERROR] 잘못된 query 타입: {type(query)}")
# ✅ 세션 초기화 명령 처리
if query.lower() == "reset":
if session_id:
clear_message_history(session_id)
return {"message": f"세션 {session_id}의 대화 기록이 초기화되었습니다."}
# ✅ Redis 세션 기록 불러오기 및 최신 입력 저장
session_history = get_session_history(session_id)
session_history.add_user_message(query)
previous_queries = [msg.content for msg in session_history.messages if isinstance(msg, HumanMessage)]
if query in previous_queries:
previous_queries.remove(query)
# ✅ 전체 중복 제거 (최신 입력을 제외한 나머지에서)
previous_queries = list(dict.fromkeys(previous_queries))
raw = detect(query)
lang_code = raw.lower().split("-")[0] # "EN-us" → "en"
#가격을 이해하는 매핑
pattern = re.compile(r'(\d+)[^\d]*원\s*(이하|미만|이상|초과)')
m = pattern.search(query)
if m:
amount = int(m.group(1))
comp = m.group(2)
# 부등호 매핑
op_map = {"이하":"<=", "미만":"<", "이상":">=", "초과":">"}
price_op = op_map[comp]
price_cond = f"market_price {price_op} {amount}"
else:
# 디폴트: 제한 없음
price_cond = None
# 2) 언어 코드 → 사람말 매핑
lang_map = {
"ko": "한국어",
"en": "English",
"zh-cn": "中文",
"ja": "日本語",
"vi": "Tiếng Việt", # 베트남어
"th": "ไทย", # 태국어
}
target_lang = lang_map.get(lang_code, "한국어")
print("[Debug] Detected language →", target_lang)
# 시즌 판단
# 시즌 관련 상수 정의
SPRING_KEYWORDS = [
# 한국어
"봄","봄맞이","봄소풍","봄나들이","벚꽃","꽃샘추위","춘분","간절기","환절기",
"트렌치코트","스프링코트","바람막이","가디건","플로럴","꽃무늬","파스텔",
# English
"spring","vernal","cherry blossom","blossom","cold snap","windbreaker",
"trench coat","spring coat","cardigan","floral","floral print","pastel","layering"
]
SUMMER_KEYWORDS = [
# 한국어
"여름","썸머","자외선차단","uv차단","썬캡","선바이저","비치","바캉스",
"래시가드","수영복","비키니","아쿠아슈즈","워터레깅스","비치샌들",
"라피아","스트로","스트로우","햇빛가리개","쿨링","냉감","쿨터치",
"흡한속건","속건","통풍","메쉬","린넨","리넨","시어서커","UPF",
# English
"summer","uv","uv protection","uv-cut","upf","sun protection","sun cap","sun visor",
"beach","beachwear","rashguard","rash guard","swimsuit","bikini",
"aqua shoes","water shoes","water leggings","flip-flops","sandals",
"raffia","straw","straw hat","sun shade","neck shade",
"cooling","cool-touch","quick-dry","moisture wicking","breathable","ventilated","mesh","linen","seersucker"
]
AUTUMN_KEYWORDS = [
# 한국어
"가을","오텀","단풍","추석","한가위","가을맞이","수확제","간절기","환절기",
"플란넬","코듀로이","트위드","체크","체커드","셔켓","오버셔츠","울혼방","니트베스트",
# English
"autumn","fall","fall foliage","foliage","chuseok","harvest festival",
"flannel","corduroy","tweed","plaid","checkered","shacket","overshirt","wool blend","layering"
]
WINTER_KEYWORDS = [
# 한국어
"겨울","윈터","방한","보온","발열","기모","기모안감","플리스","보아","보아털","쉐르파",
"다운","패딩","롱패딩","구스다운","덕다운","웰론","충전재",
"스노우부츠","핫팩","핫팩손난로","바라클라바","넥워머","귀마개",
"목도리","스카프","머플러","장갑","내복","롱존","이너웨어",
"방풍","방수","발수",
"비니","니트","울","캐시미어","퍼","두꺼운옷","두툼한","보온성",
# English
"winter","thermal","heat-retaining","fleece","boa","sherpa",
"down","goose down","duck down","synthetic down","insulation","puffer","parka",
"snow boots","hot pack","hand warmer","balaclava","neck warmer","earmuffs",
"scarf","muffler","gloves","mittens","thermal underwear","long johns","base layer",
"windproof","waterproof","water-repellent",
"beanie","wool","cashmere","fur","thick","lined"
]
def detect_season(query: str) -> str:
"""쿼리에서 시즌 정보를 감지하는 함수"""
query_lower = query.lower()
for season, keywords in [
("봄", SPRING_KEYWORDS),
("여름", SUMMER_KEYWORDS),
("가을", AUTUMN_KEYWORDS),
("겨울", WINTER_KEYWORDS)
]:
if any(keyword in query_lower for keyword in keywords):
return season
return "미정"
# 시즌 설정
season = detect_season(query)
print(f"🌞 감지된 시즌: {season}")
# LLM 전처리
llm = OpenAI(
api_key=API_KEY,
model=LLM_MODEL,
temperature=0
)
# 대화 이력 가져오기
history_messages = [msg.content for msg in session_history.messages]
conversation_context = "\n".join([f"이전 대화: {msg}" for msg in history_messages[-3:]]) if history_messages else "이전 대화 없음"
system_prompt = (
f"""System:
당신은 (1) 검색 엔진의 전처리를 담당하는 AI이자, (2) 쇼핑몰 검색 및 분류 전문가입니다.
입력 언어가 무엇이든 먼저 한국어로 의미 보존 번역을 수행합니다.
[대화 컨텍스트]
{conversation_context}
[전처리 목표]
- 오타 교정, 불용어/군더더기 제거, 중복 표현 제거
- 이전 대화 맥락을 고려하여 현재 검색어의 의도 파악
- 핵심 품목명(한 개)과 의미 있는 속성(계절/성별/색상/사이즈/용량/재질 등)만 남김
- 동의어/구어 표준화(남자→남성, 여자→여성, 남녀공용/유니섹스→공용, 여름철→여름 등)
- 숫자+단위 결합(128 GB→128GB, 5000 mAh→5000mAh)
[특별 규칙: ‘용’ 접미사 정규화]
- “봄/여름/가을/겨울/간절기/사계절/남성/여성/공용/유아/아동/키즈/성인 + 용” → 접미사 ‘용’ 제거
예) 여름용 모자→여름 모자, 남성용 등산 바지→남성 등산 바지
- 단, 의미어는 보존: 전용/공용/용량/내용은 그대로 유지 (예: “닌텐도 전용 케이스”에서 ‘전용’ 삭제 금지)
- “~에 쓸 수 있는/쓰기 좋은/사용하기 좋은” 등 군더더기는 삭제
- ‘용도’라는 일반어는 제거
[금지사항]
- 고객 검색어를 임의로 확장/추정하지 말 것(예: “스마트폰” → “스마트폰용 이어폰” 금지)
- 브랜드/모델/카테고리를 새로 만들지 말 것
- 불필요한 형용사·수식 남발 금지
[출력 규칙(반드시 정확히 준수)]
오직 두 줄만 출력, 따옴표 포함. 추가 설명/불릿/번호/코드블록 절대 금지.
Raw Query: "<query>"
Preprocessed Query: "<전처리된_쿼리(핵심 품목 + 유의미 속성만, ‘용’ 제거 후 표준형)>"
"""
)
if price_cond:
system_prompt += f"\n⚠️ 사용자 요청 조건: 가격은 **{amount}원 {comp}** ({price_cond})인 상품만 고려하세요.\n"
resp = client.chat.completions.create(
model=LLM_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query}
]
)
llm_response = resp.choices[0].message.content.strip()
print("[Debug] LLM full response:\n", llm_response) # ← 여기에!
#LLM 응답 파싱
lines = [l.strip() for l in llm_response.splitlines() if l.strip()]
def extract_preprocessed(llm_text: str, fallback: str) -> str:
# 0) 혹시 JSON으로 온 경우 대비
try:
obj = json.loads(llm_text)
v = (obj.get("Preprocessed Query") or
obj.get("preprocessed_query") or
obj.get("final_query") or
obj.get("query_preprocessed"))
if v and isinstance(v, str) and v.strip():
return v.strip()
except Exception:
pass
# 1) 영문 라벨 (권장 형식)
m = re.search(r'(?i)^\s*preprocessed\s*query\s*:\s*["“]?(.+?)["”]?\s*$', llm_text, re.M)
if m:
return m.group(1).strip()
# 2) 한글 라벨(모델이 한국어로 라벨을 바꿔도 커버)
for pat in [
r'^\s*최종\s*검색어\s*[:=]\s*["“]?(.+?)["”]?\s*$',
r'^\s*전처리된_?쿼리\s*[:=]\s*["“]?(.+?)["”]?\s*$',
]:
m = re.search(pat, llm_text, re.M)
if m:
return m.group(1).strip()
# 3) 마지막 폴백: 따옴표 속 가장 그럴듯한 문자열
quotes = re.findall(r'["“]([^"\n”]{2,64})["”]', llm_text)
if quotes:
# 공백 포함/길이 기준 간단 휴리스틱
quotes.sort(key=lambda s: (-(' ' in s), -len(s)))
return quotes[0].strip()
# 4) 최종 폴백: 원문
return fallback
preprocessed_query = extract_preprocessed(llm_response, query)
print("[Debug] Preprocessed Query ->", preprocessed_query)
# --- 쿼리 임베딩 (L2 정규화) ---
q_vec = np.array(embedder.embed_query(preprocessed_query), dtype=np.float32)
n = np.linalg.norm(q_vec)
if np.isfinite(n) and n != 0.0:
q_vec = q_vec / n
print(f"[Debug] q_vec dim: {q_vec.shape}, norm: {np.linalg.norm(q_vec):.4f}")
# --- category_0821에서 L2로 Top5 카테고리 검색 ---
CAT_COLLECTION = "category_0821"
def get_top5_categories_from_embeddings(qv: np.ndarray):
cat_col = Collection(CAT_COLLECTION)
res = cat_col.search(
data=[qv],
anns_field="embedding",
param={"metric_type":"L2","params":{"nprobe":64}},
limit=5,
output_fields=["category_full"]
)
top5 = [(hit.entity.get("category_full"), float(hit.distance)) for hit in res[0]]
print("🔎 카테고리 Top5 (L2, 작을수록 유사):")
for i,(name,dist) in enumerate(top5,1):
print(f" {i}. {name} | L2={dist:.6f}")
return top5
top5_cats = get_top5_categories_from_embeddings(q_vec)
print("\n🔎 (원본) 카테고리 Top5:")
for i,(name,dist) in enumerate(top5_cats,1):
print(f" {i}. {name} | L2={dist:.6f}")
# --- (옵션) 시즌 보정만 유지: 여름/겨울이면 살짝 정렬 보정 ---
# 시즌 보정을 위한 긍정/부정 세트 정의
_SEASON_POS = {
"봄": tuple(SPRING_KEYWORDS),
"여름": tuple(SUMMER_KEYWORDS),
"가을": tuple(AUTUMN_KEYWORDS),
"겨울": tuple(WINTER_KEYWORDS),
}
# 봄/가을엔 극여름·극겨울 단어 감점, 여름/겨울엔 서로 반대 시즌만 감점
_SEASON_NEG = {
"봄": tuple(SUMMER_KEYWORDS + WINTER_KEYWORDS),
"가을": tuple(SUMMER_KEYWORDS + WINTER_KEYWORDS),
"여름": tuple(WINTER_KEYWORDS),
"겨울": tuple(SUMMER_KEYWORDS),
}
def _season_adjust(name: str, season_hint: str) -> float:
"""
카테고리명(name)에 시즌 강 키워드가 있으면 L2 거리를 미세 조정.
- 보너스(거리↓): 해당 시즌의 강 키워드 포함
- 페널티(거리↑): 반대(혹은 극단) 시즌 강 키워드 포함
"""
if season_hint not in _SEASON_POS:
return 0.0
n = name.lower()
pos_hit = any(w.lower() in n for w in _SEASON_POS[season_hint])
neg_hit = any(w.lower() in n for w in _SEASON_NEG[season_hint])
POS_BONUS = 0.04 # 거리 감소 → 순위 소폭 상승
NEG_PENALTY = 0.12 # 거리 증가 → 순위 소폭 하향
adj = 0.0
if pos_hit: adj -= POS_BONUS
if neg_hit: adj += NEG_PENALTY
return adj
def season_filter_items(items: list, season_hint: str):
"""시즌에 맞는 상품만 필터링하여 반환"""
if not season_hint or season_hint == "미정" or not items:
return items
def matches_season(item_name: str, season: str) -> bool:
name_lower = item_name.lower()
# 해당 시즌의 키워드가 있으면 True
if season == "봄" and any(kw.lower() in name_lower for kw in SPRING_KEYWORDS):
return True
elif season == "여름" and any(kw.lower() in name_lower for kw in SUMMER_KEYWORDS):
return True
elif season == "가을" and any(kw.lower() in name_lower for kw in AUTUMN_KEYWORDS):
return True
elif season == "겨울" and any(kw.lower() in name_lower for kw in WINTER_KEYWORDS):
return True
# 반대 시즌 키워드가 있으면 False
if season == "여름" and any(kw.lower() in name_lower for kw in WINTER_KEYWORDS):
return False
elif season == "겨울" and any(kw.lower() in name_lower for kw in SUMMER_KEYWORDS):
return False
# 아무 키워드도 없으면 True (중립)
return True
# 필터링 적용
filtered = [
item for item in items
if matches_season(item.get("제목", ""), season_hint) and
matches_season(item.get("카테고리", ""), season_hint)
]
return filtered if filtered else items # 필터링 결과가 없으면 원본 반환
# season 기본값 보장 (이미 위에서 세팅되어 있으면 이 부분은 그대로 둬도 됨)
try:
season
except NameError:
season = "미정"
# 적용: 4계절 모두
if season in ("봄","여름","가을","겨울"):
top5_cats = sorted(
[(n, d + _season_adjust(n, season)) for (n, d) in top5_cats],
key=lambda x: x[1]
)
print("🛠 시즌 보정 후 Top5:")
for i,(name,dist) in enumerate(top5_cats,1):
print(f" {i}. {name} | adj_L2={dist:.6f}")
# 상위 3개 카테고리에 대해 각각 상품 검색 (시즌 보정 적용)
def get_adjusted_score(category_name: str, score: float, season: str) -> float:
"""시즌에 따른 점수 보정"""
season_adj = _season_adjust(category_name, season)
return score + season_adj
top3_products = []
sorted_cats = sorted(
top5_cats[:3],
key=lambda x: get_adjusted_score(x[0], x[1], season)
)
# 카테고리별 검색 수량 설정
CATEGORY_QUOTAS = {
"Top1": {"direct": 25, "vector": 25}, # 총 50개
"Top2": {"direct": 15, "vector": 15}, # 총 30개
"Top3": {"direct": 10, "vector": 10} # 총 20개
}
def search_products_by_category(cat_name: str, cat_rank: str, query_tokens: List[str], query_vec: np.ndarray, vector_limit: Optional[int] = None):
"""
카테고리별 직접 검색과 벡터 검색을 수행하는 함수
Args:
cat_name: 카테고리 이름
cat_rank: "Top1", "Top2", "Top3" 등 카테고리 순위
query_tokens: 검색어 토큰
query_vec: 쿼리 벡터
vector_limit: 벡터 검색 제한 수 (선택적, None이면 기본 할당량 사용)
Returns:
direct_hits, vector_hits
"""
quota = CATEGORY_QUOTAS.get(cat_rank, {"direct": 10, "vector": 10})
# 1. 직접 검색
direct_expr = f"category_name like '%{cat_name}%' && " + " && ".join(
f'market_product_name like "%{tok}%"' for tok in query_tokens
)
output_fields = [
"product_code", "category_code", "category_name",
"market_product_name", "market_price", "shipping_fee",
"shipping_type", "max_quantity", "composite_options",
"image_url", "manufacturer", "model_name", "origin",
"keywords", "description", "return_shipping_fee"
]
direct_hits = collection.query(
expr=direct_expr,
limit=quota["direct"],
output_fields=output_fields
)
# 2. 벡터 검색 (동적 limit 적용)
actual_limit = vector_limit if vector_limit is not None else quota["vector"]
vector_hits = collection.search(
data=[query_vec],
anns_field="emb",
param={"metric_type": "L2", "params": {"nprobe": 64}},
limit=actual_limit,
expr=f"category_name like '%{cat_name}%'",
output_fields=output_fields
)
return direct_hits, vector_hits[0]
# 카테고리별 검색 실행
tokens = [t for t in re.sub(r"[용\s]+", " ", preprocessed_query).split() if t]
for idx, (cat_name, base_score) in enumerate(sorted_cats, 1):
cat_rank = f"Top{idx}"
adj_score = get_adjusted_score(cat_name, base_score, season)
print(f"\n🔍 카테고리 '{cat_name}' 검색 시작... (시즌 보정 점수: {adj_score:.6f})")
# 카테고리별 검색 실행 - 처음에는 직접 검색
direct_hits, vector_hits = search_products_by_category(cat_name, cat_rank, tokens, q_vec)
direct_target = CATEGORY_QUOTAS[cat_rank]['direct']
vector_target = CATEGORY_QUOTAS[cat_rank]['vector']
# 직접 검색 결과가 목표에 미달인 경우 벡터 검색 쿼터 증가
if len(direct_hits) < direct_target:
shortage = direct_target - len(direct_hits)
vector_target += shortage
print(f" ⚠️ 직접 검색 부족분 {shortage}개를 벡터 검색으로 보충 시도")
# 벡터 검색 재시도 (증가된 쿼터로)
_, additional_hits = search_products_by_category(cat_name, cat_rank, tokens, q_vec, vector_limit=vector_target)
vector_hits = additional_hits
print(f" ┣ 직접 검색 결과: {len(direct_hits)}개 (목표: {direct_target}개)")
print(f" ┗ 벡터 검색 결과: {len(vector_hits)}개 (목표: {vector_target}개)")
# 결과 통합 및 가공
cat_products = []
def process_hit(hit, is_vector=False):
try:
if is_vector:
hit = hit.entity
html_raw = hit.get("description", "") or ""
html_cleaned = clean_html_content(html_raw)
if isinstance(html_raw, bytes):
html_raw = html_raw.decode("cp949")
encoded_html = base64.b64encode(html_cleaned.encode("utf-8", errors="ignore")).decode("utf-8")
preview_url = f"{API_URL}/preview?html={urllib.parse.quote_plus(encoded_html)}"
# 최대구매수량 처리 (기본값 999)
max_quantity = hit.get("max_quantity", 999)
try:
max_quantity = convert_to_serializable(max_quantity)
if max_quantity is None or not isinstance(max_quantity, (int, float)) or max_quantity < 0:
max_quantity = 999
except:
max_quantity = 999
return {
"상품코드": str(hit.get("product_code", "없음")),
"제목": hit.get("market_product_name", "제목 없음"),
"가격": convert_to_serializable(hit.get("market_price", 0)),
"배송비": convert_to_serializable(hit.get("shipping_fee", 0)),
"이미지": hit.get("image_url", "이미지 없음"),
"원산지": hit.get("origin", "정보 없음"),
"상품링크": preview_url,
"카테고리": hit.get("category_name", "카테고리 없음"),
"검색방식": "벡터검색" if is_vector else "직접검색",
"순위점수": idx, # 카테고리 순위 정보 추가
"최대구매수량": max_quantity
}
except Exception as e:
print(f" ⚠️ 상품 정보 처리 오류: {e}")
return None
# 직접 검색 결과 처리
for hit in direct_hits:
product = process_hit(hit)
if product:
cat_products.append(product)
# 벡터 검색 결과 처리
for hit in vector_hits:
product = process_hit(hit, is_vector=True)
if product:
cat_products.append(product)
# 중복 제거 (상품코드 기준) 및 카테고리 순위 유지
seen_codes = set()
unique_products = []
for p in cat_products:
if p["상품코드"] not in seen_codes:
seen_codes.add(p["상품코드"])
unique_products.append(p)
# 시즌 필터링 적용
unique_products = season_filter_items(unique_products, season)
quota = CATEGORY_QUOTAS[f"Top{idx}"]
target_count = quota["direct"] + quota["vector"]
print(f" ✅ 최종 상품 수: {len(unique_products)}개 / 목표: {target_count}개")
top3_products.extend(unique_products)
# 무한 스크롤을 위한 함수 - 방법 2: 카테고리 검색 5:3:2
def get_next_products(products: List[Dict], top5_cats: List[Tuple[str, float]], offset: int = 0) -> Tuple[List[Dict], bool]: