feat(lps): 오픈마켓 폴백 오케스트레이션 + 몰 dedup

사용자 규칙 '네이버로 그 몰 값 확보 성공→그 값, 실패(몰 없음)→실사이트 크롤' 구현.

- handler: found 라운드 뒤 _enrich_with_fallback — 네이버 매칭이 커버 못 한 타깃 몰만
  (canonical_mall 로 판정) 크롤 어댑터로 검색→같은상품 판정→병합. 크롤 실패는 격리(무시).
  fallback_crawl STAGE 기록.
- summarize_by_mall: 키를 (source,mall)→몰명(canonical)으로 — 네이버노출 vs 직접크롤 같은 몰
  중복을 최저가 1건으로 병합(dedup).
- card_parser: MALL_BY_SOURCE + canonical_mall() 추가.
- worker_main: gmarket/auction/st11 폴백 어댑터 등록(lazy 기동, 리소스차단 OFF).
- 테스트: 커버몰 크롤생략·미커버 크롤·실패격리·몰 dedup 4종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Fable 5 committed 2026-07-09 14:45:39 +09:00
1 parent e365e5c6e0
commit f9714c3f06
5 files changed
+108 -11

No files matched your search

+39 -2
View File
@@ -18,6 +18,7 @@ import asyncio
from common.enums import JobType
from common.logger import LOG
from services.search.contract import SearchAdapter, NormalizedProduct
from services.search.card_parser import canonical_mall, MALL_BY_SOURCE
from services.search.util import parse_price
from services.pipeline.core import apply_filters, rank_result, summarize_by_mall
@@ -50,12 +51,15 @@ def build_search_handler(
max_rounds: int = 3,
neg_cache=None,
history=None,
fallback_adapters: dict[str, SearchAdapter] | None = None,
):
"""검색 핸들러 생성.
judge: SimilarityJudge(같은 상품 판정) / keyword_gen: KeywordGenerator(정밀·광역 재검색어) /
neg_cache: NegativeCache(TTL not_found 캐시) / history: PriceHistory(최저가 스냅샷).
neg_cache: NegativeCache(TTL not_found 캐시) / history: PriceHistory(최저가 스냅샷) /
fallback_adapters: 오픈마켓 크롤(gmarket/auction/st11) — 네이버가 그 몰을 커버 못 했을 때만 크롤(폴백).
모두 선택 — 없으면 해당 단계 생략."""
use = list(sources) if sources else list(adapters.keys())
fallbacks = fallback_adapters or {}
async def _record_history(product_code: str, job_id, outcome: str, matched: list):
if history is None:
@@ -80,6 +84,35 @@ def build_search_handler(
per_source[src] = {"count": len(res)}
return products, per_source, tech_failed
async def _match(target: dict, products: list, base_price):
"""필터 → (있으면) AI 같은상품 판정 → 매칭 후보. 폴백 크롤 결과 판정에도 재사용."""
candidates, _ = apply_filters(products, base_price=base_price)
if judge is not None and candidates:
verdicts = await judge.judge(target, candidates)
candidates = [c for c, v in zip(candidates, verdicts) if v.is_match]
return candidates
async def _enrich_with_fallback(target: dict, query: str, matched: list, base_price):
"""네이버가 커버 못 한 오픈마켓만 직접 크롤(폴백) → 같은상품 판정 후 병합.
사용자 규칙: '네이버로 그 몰 값 확보 성공 → 그 값, 실패(몰 없음) → 실사이트 크롤'."""
if not fallbacks:
return matched
covered = {canonical_mall(p) for p in matched}
for src, adapter in fallbacks.items():
mall = MALL_BY_SOURCE.get(src, src)
if mall in covered: # 네이버가 이미 그 몰 최저가 확보 → 크롤 생략
continue
try:
crawled = await adapter.search(query, limit=limit)
except Exception as ex:
LOG.w(f"[fallback:{src}] 크롤 실패(무시): {type(ex).__name__}: {ex}")
continue
hits = await _match(target, crawled, base_price)
if hits:
LOG.d(f"[fallback:{src}] 크롤 {len(crawled)}건 중 같은상품 {len(hits)}건 병합")
matched = matched + hits
return matched
async def _round_queries(base_query: str, target: dict):
"""라운드 쿼리 지연 생성: 원본 → (0매칭 시에만 LLM 호출로) 정밀 → 광역."""
yield ("original", base_query)
@@ -125,7 +158,11 @@ def build_search_handler(
candidates = matched
last_stages, last_sources = stages, per_source
if candidates: # 찾음 → 조기 종료
if candidates: # 찾음 → 오픈마켓 폴백 보강 후 종료
before = len(candidates)
candidates = await _enrich_with_fallback(target, query, candidates, base_price)
if len(candidates) > before:
stages.append({"stage": "fallback_crawl", "in": before, "out": len(candidates)})
result = rank_result(candidates, len(products), stages, top_n)
result.update(outcome="found", query=query, round=label, rounds_tried=rounds_done, sources=per_source)
await _record_history(cache_key, job.get("job_id"), "found", candidates)