#!/usr/bin/env python3 """⑧ 인터넷 최저가 탐색 파이프라인 — 검색 + 텍스트·이미지 판정 + 최저가 선택 (`capture`). 측정 코어는 prism_core/ (PRISM backend 발췌본 — 출처: prism_core/PROVENANCE.md). prism 저장소·DB·큐·브라우저 인프라에 종속되지 않는다. 검색 범위: 무차단 HTTP 몰 (danawa·enuri·gsshop — 카탈로그형이라 실질 종합 소스). 브라우저 5몰(naver·coupang·gmarket·auction·st11) 포함 측정은 PRISM 서비스 기동 후 capture_snapshots.py 를 사용한다. 검증 2축 (계획서 도해 3·4단계): 텍스트 similarity(LLM) 또는 local_judge(룰) → identity.veto(결정적 식별 게이트) 이미지 image_judge(VLM 사진 판정) + image_store.consensus(pHash 후보 합의) 후보는 두 축을 모두 통과해야 채택된다. 사진을 못 본 후보는 기각하지 않고 통과시키되 상태를 남긴다(fail-open) — 최종 판정은 사람이 한다. 필요: OPENAI_API_KEY (../.env 자동 로드 — AI 동일상품 판정), 인터넷. Pillow(pHash·선택). 사용: python capture.py [--golden data/golden.json] [--out data/snapshots] [--sources danawa,enuri,gsshop] [--limit N] [--image ai|off] 출력: /.json — run.py 가 재생하는 몰별 가격표 스냅샷 (PRISM 응답과 동일 골격) """ import argparse import asyncio import json import os import sys import time from pathlib import Path from common.paths import DATA_DIR, SERVER_ROOT # noqa: E402 HERE = Path(__file__).parent # OPENAI_API_KEY: 환경변수 → server/config.toml 순 (NEGO_AGENT 공통 규약) _server_config = SERVER_ROOT / "config.toml" if "OPENAI_API_KEY" not in os.environ and _server_config.exists(): import re as _re _m = _re.search(r'^api_key\s*=\s*"([^"]+)"', _server_config.read_text(encoding="utf-8"), _re.MULTILINE) if _m and _m.group(1): os.environ["OPENAI_API_KEY"] = _m.group(1) from services.price_search.prism_core.contract import AdapterError # noqa: E402 from services.price_search.prism_core.core import apply_filters # noqa: E402 from services.price_search.prism_core.danawa import DanawaAdapter # noqa: E402 from services.price_search.prism_core.enuri import EnuriAdapter # noqa: E402 from services.price_search.prism_core.enums import SourceState # noqa: E402 from services.price_search.prism_core.gsshop import GsshopAdapter # noqa: E402 from services.price_search.prism_core.identity import same_group # noqa: E402 from services.price_search.prism_core.identity import veto as identity_veto # noqa: E402 from services.price_search.prism_core import image_store # noqa: E402 from services.price_search.prism_core.similarity import SimilarityJudge # noqa: E402 from services.price_search.prism_core.util import build_search_query, norm_token # noqa: E402 ADAPTERS = {"danawa": DanawaAdapter, "enuri": EnuriAdapter, "gsshop": GsshopAdapter} CONFIRMED = {SourceState.MATCHED, SourceState.NO_MATCH, SourceState.EMPTY} # 썸네일 캐시 기본 위치 — sha256 이름이라 품목·회차가 섞여도 충돌하지 않는다. IMAGE_DIR = DATA_DIR / "price_search_images" async def search_one(source: str, adapter, query: str): """한 몰 검색 → (state, products). 차단/실패도 상태로 정직하게 남긴다.""" try: items = await adapter.search(query) return (SourceState.EMPTY if not items else SourceState.MATCHED), items except AdapterError as e: state = getattr(e, "state", None) or ( SourceState.BLOCKED if getattr(e, "blocked", False) else SourceState.UNAVAILABLE) print(f" [{source}] {state.name}: {e}") return state, [] def refine_queries(primary: str, company: str = "") -> list: """검색어 재정제 라운드 (룰 기반) — 원본 PRISM의 '원본 → 정밀 → 광역' 설계 계승. 긴 조달형 품명은 몰 검색에서 0건이 나기 쉽다. 0매칭이면 순서대로 재시도: 1) 원본 그대로 2) 부연(괄호·슬래시)·수식어(불용어) 제거 전체 3) 브랜드 + **꼬리명사 2개** + 모델 — 상품 종류를 지킨 채 좁힌다 4) 브랜드 + 모델 — 몰이 종류명을 달리 쓸 때 5) **모델 단독** — 브랜드 추정이 틀렸을 때의 최후 앵커 6) 브랜드 + 꼬리명사 2개 — 광역, 그래도 상품 종류는 남긴다 **순서 재배열 (2026-09-07)**. 이전엔 3)이 '브랜드 + 모델', 5)가 '앞 2토큰'이라 상품 종류를 잃은 쿼리가 먼저 나갔다. 모집단 1,000건 실측: 97.8% 가 종류 명사를 잃은 쿼리를 하나 이상 만들었고(품목당 평균 1.80개), '모제림 엘릭서'·'레드빈 퀀텀스크롤' 처럼 브랜드+수식어만 남아 그 브랜드의 아무 상품이나 끌어왔다. 한 품목 실측에서는 그런 라운드 하나가 OpenAI 호출의 25% 를 먹었다. 종류를 잃은 쿼리(4)를 아예 빼지 않는 이유: 몰이 종류명을 다르게 표기하면 ('멀티탭' vs '전원탭') 종류 토큰이 오히려 0건을 만든다. 뒤로 미루되 남긴다. 꼬리 명사를 **2개** 잡는 이유: 마지막 1개만 쓰면 종류 뒤에 수식어가 붙은 이름 ('탐사 고평량 종이컵 무인쇄')에서 '무인쇄'를 종류로 오인해 '종이컵'을 잃는다. 수집 키워드를 정답으로 놓고 1,000건 채점(기준선 87.1%): 광역 쿼리의 종류 소실이 꼬리1 = 55.6% → 꼬리2 = 37.3% 로 줄었다. 모델 단독 쿼리(5)를 넣은 이유 (2026-09-08): 이전엔 **모든 쿼리가 첫 토큰으로 시작**해, 첫 토큰이 브랜드가 아니면 어떤 쿼리도 상품에 닿지 못했다. 쿠팡 판매명은 셀러명이 앞에 온다 — '토너피아 삼성 호환토너 MLT-D111S' 는 '토너피아'(다나와에 없음)에 묶여 전멸했지만, 'MLT-D111S' 단독 검색은 다나와에서 11건을 낸다. 실측 3건 모두 같았다 (HDC-WM200 → 2건, H1001C5 → 2건). 브랜드 추정이 틀려도 모델코드는 정확하다. """ import re as _re from services.price_search.prism_core.identity import model_surface_tokens from services.price_search.prism_core.local_judge import _STOPWORDS stripped = _re.sub(r"\([^)]*\)|\[[^\]]*\]|[/|]", " ", primary) toks = [t for t in stripped.split() if t and norm_token(t) not in _STOPWORDS] queries = [primary] def add(q: str): q = q.strip() if q and q not in queries: queries.append(q) add(" ".join(toks)) # 제조사란이 있으면 그 토큰은 숫자가 있어도 모델이 아니라 브랜드다 ('K2코리아' — 2026-09-08 # 파일럿에서 모델 토큰으로 잡혀 '안전벨트'가 브랜드 자리에 앉고 'KB-9501' 단독 질의가 사라졌다) brand_norm = {norm_token(t) for t in (company or "").split()} model_toks = [t for t in toks if _re.search(r"\d", t) and norm_token(t) not in brand_norm] nouns = [t for t in toks if t not in model_toks] # 꼬리 명사 = 마지막 비수치 토큰 2개. 한국어 상품명은 종류를 뒤쪽에 둔다. tail = [t for t in nouns[-2:] if t != nouns[0]] if len(nouns) >= 2 else [] if nouns: if tail and model_toks: add(" ".join([nouns[0]] + tail + model_toks)) # 3) 종류 보존 + 모델 if model_toks: add(" ".join([nouns[0]] + model_toks)) # 4) 브랜드 + 모델 # 5) 모델 단독 — 규격(4구·3m)은 빼고 진짜 모델코드만. 브랜드 앵커에서 자유로운 유일한 쿼리다. strong = [t for t in model_surface_tokens(primary) if norm_token(t) not in brand_norm] if strong: add(" ".join(strong)) if nouns and tail: add(" ".join([nouns[0]] + tail)) # 6) 종류 보존 광역 # 7)·8) 브랜드 없는 질의 (2026-09-08): 몰 상품명이 제조사를 안 쓰는 경우가 있다 — # '네슬레 캡슐커피 네스프레소 이스피라치오네 …' 는 다나와에서 '네슬레' 때문에 0건이고 # '네스프레소 이스피라치오네 리스트레토' 로는 나온다. 브랜드 앵커를 뺀 질의를 뒤에 둔다 # (브랜드 없는 질의는 후보가 넓어져 AI 부담이 크므로 마지막 순서). if len(nouns) >= 2: rest = nouns[1:] if model_toks: add(" ".join(rest + model_toks)) # 7) 상품명·모델 (브랜드 제외) if len(rest) >= 2: # 8) 꼬리 명사 3개 (브랜드 제외) add(" ".join(rest[-3:])) # 종류 명사 하나('정품토너')뿐이면 너무 넓어 생략 return queries[:8] async def _round_queries(primary: str, payload: dict, keyword_gen=None): """라운드 쿼리 지연 생성: 룰 재정제 → (전부 0매칭일 때만 LLM 호출로) 정밀·광역. PRISM worker/handlers._round_queries 의 lazy 설계 계승.""" seen = [] for q in refine_queries(primary, payload.get("company") or ""): seen.append(q) yield q if keyword_gen is not None: try: kw = await keyword_gen.generate(payload) print(f" [keyword] LLM 재정제: precise={kw.precise!r} broad={kw.broad!r}") except Exception as e: print(f" [keyword] LLM 재정제 실패(무시): {e}") return for q in (kw.precise, kw.broad): q = (q or "").strip() if q and q not in seen: seen.append(q) yield q async def _image_gate(payload: dict, gated: list, image_judge, image_dir: Path, row_of: dict, ref_cache: dict, judge_cache: dict, target_img=None) -> list: """텍스트 게이트 통과분의 썸네일을 받아 VLM 판정 + pHash 합의로 한 번 더 거른다. 계획서 도해 3단계('이미지 유사도 AI 측정')의 결합 지점. 두 신호를 함께 쓴다: image-ai: VLM 이 '다른 상품 사진'이라고 판정 (본체 — 단독 기각 가능) image-outlier:<거리> 후보 사진 다수 합의에서 이탈 (보조 — VLM 판단불가 시에만 적용) 사유 형식은 identity.veto 와 같은 규약이라 pool_log 에서 한 목록으로 읽힌다. **fail-open 원칙**: 썸네일이 없거나(gsshop 셀러 자유기재) 획득에 실패했거나 모델이 undecidable 이면 통과시키고 상태만 남긴다. '사진이 다르다'와 '사진을 못 봤다'는 다른 사실이고(SourceState 의 확인함/못 봄 경계와 같은 이유), 최종 판정은 사람이 한다. target_img (2026-09-08): 찾는 상품의 레퍼런스 사진(ImageRef). 있으면 ① VLM 프롬프트 첫 장에 넣어 사진↔사진 판정이 되고 ② 레퍼런스↔후보 dHash 거리(image-ref:<거리>)가 합의 이탈과 같은 자리의 보조 근거가 된다. 레퍼런스를 못 받았으면 종전 경로(사진↔상품명)로 그대로 돈다. """ products = [p for p, _ in gated] # 라운드가 바뀌어도 같은 후보가 다시 올라온다 — 이미 받아 둔 썸네일은 다시 받지 않는다. # (디스크 캐시는 sha256 기준이라 재다운로드 자체는 막지 못한다 — 여기서 URL 로 막는다) need_url = list(dict.fromkeys(p.image_url for p in products if p.image_url not in ref_cache)) if need_url: for u, ref in zip(need_url, await image_store.fetch_many(need_url, image_dir)): ref_cache[u] = ref refs = [ref_cache[p.image_url] for p in products] cons_reasons, cons_scores = image_store.consensus(refs) ref_reasons, ref_scores = image_store.reference_similarity(target_img, refs) ref_path = target_img.path if (target_img is not None and target_img.ok) else None # VLM 판정도 같은 이유로 캐시한다 — 사진 1장당 판정은 한 번이면 족하다. need, seen = [], set() for i, p in enumerate(products): if p.name not in judge_cache and p.name not in seen: seen.add(p.name) need.append(i) if need: fresh = await image_judge.judge( payload, [products[i] for i in need], [refs[i].path if refs[i].ok else None for i in need], ref_path) for i, j in zip(need, fresh): judge_cache[products[i].name] = j judgments = [judge_cache[p.name] for p in products] survivors = [] for (p, j), ref, ij, c_reasons, c_score, r_reasons, r_score in zip( gated, refs, judgments, cons_reasons, cons_scores, ref_reasons, ref_scores): reasons = [] if ref.ok and not ij.undecidable and not ij.is_match: reasons.append(f"image-ai:{ij.score}") # 합의 이탈은 **단독으로 기각하지 않는다**. VLM 이 '이 사진 맞다'고 확인한 후보를 # 해시 거리만으로 죽이면 같은 상품의 다른 촬영본(각도·판매자 자체 촬영)이 잘려 # 기권만 늘어난다. 모델이 판별을 포기한(undecidable) 후보에 한해, '다른 몰이 모두 # 보여주는 그림과 확연히 다르다'는 사실을 결정 근거로 쓴다. if ij.undecidable: reasons.extend(c_reasons) reasons.extend(r_reasons) # 레퍼런스 이탈도 VLM 판단불가일 때만 (같은 이유) row = row_of.get(id(p)) if row is not None: row["image"] = ref.as_log() row["image_ai_match"] = None if ij.undecidable else ij.is_match row["image_ai_score"] = None if ij.undecidable else ij.score row["image_consensus"] = c_score row["image_ref_similarity"] = r_score row["image_veto"] = reasons row["accepted"] = not reasons # 최종 수락 = 텍스트·이미지 게이트 모두 통과 if not reasons: survivors.append((p, j)) return survivors async def capture(g: dict, sources: list[str], judge: SimilarityJudge, keyword_gen=None, image_judge=None, image_dir: Path | None = None) -> dict: t0 = time.perf_counter() payload = {k: g.get(k, "") for k in ("product_name", "company", "model", "specification")} # 검색어와 정답을 분리 (2026-08-29): 질의는 실사용자형 키워드(search_name), # 동일상품 판정 기준은 전체 상품명(payload) — 자기 자신 검색의 자명성 제거. primary = (g.get("search_name") or "").strip() or build_search_query(payload) # 식별 게이트 기준 텍스트 — 제조사·상품명·모델명. 규격은 veto 의 spec_text 로 따로 넘긴다 # (모델 토큰 원천에서 제외 — identity.veto 주석 참고. 2026-09-08 파일럿에서 규격란의 # 호환 기종 코드가 모델 토큰이 되어 정답을 전멸시켰다) target_text = " ".join(str(payload.get(k) or "") for k in ("company", "product_name", "model")) spec_text = str(payload.get("specification") or "") # 품목 1건 안에서만 사는 판정 캐시. 라운드가 넓어질수록 앞 라운드 후보가 그대로 다시 # 올라온다 — 실측(2026-09-07) 라운드 간 중복 판정 27.8%, 최악 55.2%(필립스 멀티탭: # 4라운드 192건 판정 중 고유는 86건). 상품명이 같으면 판정도 같으므로 다시 묻지 않는다. # 캐시를 품목 밖으로 넓히지 않는 이유: 판정은 '이 타겟과 동일한가'라 타겟이 바뀌면 무효다. judge_cache: dict = {} img_ref_cache: dict = {} img_judge_cache: dict = {} # 레퍼런스 사진 — 시트의 참조이미지(운용 마스터 메인이미지). 품목당 1회 획득·캐시(sha256). # 못 받으면 None 으로 두고 종전 경로(사진↔상품명)로 돈다 — 상태는 스냅샷에 남긴다. target_img = None ref_url = (g.get("ref_image_url") or "").strip() if ref_url and image_judge is not None: target_img = (await image_store.fetch_many([ref_url], image_dir or IMAGE_DIR))[0] if not target_img.ok: print(f" [ref-image] 레퍼런스 획득 실패: {target_img.state} {target_img.reason}") # 재정제 라운드: 게이트 통과 매칭이 나올 때까지 좁은 검색어 → 넓은 검색어 순으로 시도 attempt = 0 pool_log: list[dict] = [] async for query in _round_queries(primary, payload, keyword_gen): attempt += 1 results = await asyncio.gather(*( search_one(s, ADAPTERS[s](use_proxy=False), query) for s in sources)) per_source = dict(zip(sources, results)) pool = [p for _, items in results for p in items] # 이상치(IQR) 제거 비활성 (2026-08-28 결정): 후보 풀이 대부분 '다른 상품'인 검색 # 정확도 측정에서는 가격 IQR이 정답 상품을 잘라낼 수 있다 — 동일상품 판정에 집중. kept, stages = apply_filters(pool, base_price=g.get("base_price"), company=g.get("company"), remove_outliers=False) # 같은 라운드 안에서도 몰이 달라 같은 상품명이 겹친다 — 이름 기준으로 한 번만 묻는다 need, seen = [], set() for p in kept: if p.name not in judge_cache and p.name not in seen: seen.add(p.name) need.append(p) if need: for p, j in zip(need, await judge.judge(payload, need)): judge_cache[p.name] = j judgments = [judge_cache[p.name] for p in kept] # 식별 게이트: AI 수락 + 결정적 veto 없음 — AI 는 판별, 존재 검증은 코드가 한다. # 이전엔 min(price)만 봐서 점수 90 저가 오탐이 점수 100 정답을 밀어냈다(회귀 8건). gated = [] pool_log = [] row_of = {} for p, j in zip(kept, judgments): reasons = identity_veto(target_text, p.name, spec_text, payload.get("company") or "") accepted = j.is_match and not reasons row = {"source": p.source, "name": p.name, "price": p.price, "image_url": p.image_url, "ai_match": j.is_match, "ai_score": j.score, "veto": reasons, "accepted": accepted} pool_log.append(row) row_of[id(p)] = row if accepted: gated.append((p, j)) # 이미지 검증 — 텍스트 게이트 통과분에만 태운다 (2026-09-07). # 계획서 도해는 이미지 → 텍스트 순서지만, 후보 전량에 VLM 을 태우면 1,000건 측정에서 # 호출이 수만 회로 터진다. 요건은 '두 검증을 모두 통과'이지 순서가 아니므로 통과분 # (품목당 3~5건)으로 좁혀 붙인다 — 성적서에 순서 변경을 명기할 것. if gated and image_judge is not None: gated = await _image_gate(payload, gated, image_judge, image_dir or IMAGE_DIR, row_of, img_ref_cache, img_judge_cache, target_img) if gated: # canonical = 게이트 통과분 중 최고 확신 → 같은 정체성 그룹만 최저가 경쟁. # '싼 정답'(해외구매 등 동일 SKU)은 그룹에 남고 '싼 오탐'은 이미 게이트 밖. canon, _ = max(gated, key=lambda pj: (pj[1].score, -(pj[0].price or 0))) matched = [p for p, _ in gated if same_group(canon.name, p.name)] break matched = [] score_of = {id(p): j.score for p, j in zip(kept, judgments)} malls = [] for src in sources: state, items = per_source[src] m_src = [p for p in matched if p.source == src] if m_src: best = min(m_src, key=lambda p: p.price) row_state = SourceState.MATCHED price, name, url = best.price, best.name, getattr(best, "detail_url", None) ship, score = getattr(best, "shipping_fee", None), score_of.get(id(best)) # 반환 상품의 이미지 증빙 — 검수 시트가 썸네일을 붙이고, 성적서가 사진을 지목한다 info = row_of.get(id(best), {}) img = info.get("image") or {} image_url = img.get("url") or getattr(best, "image_url", None) image_sha = img.get("sha256") image_ai = info.get("image_ai_score") image_cons = info.get("image_consensus") image_ref = info.get("image_ref_similarity") else: row_state = SourceState.NO_MATCH if items else state price = name = url = ship = score = None image_url = image_sha = image_ai = image_cons = image_ref = None malls.append({"source": src, "state": row_state.value, "state_name": row_state.name, "confirmed": row_state in CONFIRMED, "price": price, "name": name, "detail_url": url, "shipping_fee": ship, "ai_score": score, "image_url": image_url, "image_sha256": image_sha, "image_ai_score": image_ai, "image_consensus": image_cons, "image_ref_similarity": image_ref}) # 이미지 검증 커버리지 — 성적서에 "후보 몇 건을 사진으로 검증했나"를 병기하기 위한 집계. # fail-open 이라 '획득 실패'가 통과로 흡수되므로, 이 숫자 없이는 게이트가 실제로 # 일했는지 사후에 알 수 없다. img_rows = [r for r in pool_log if r.get("image")] image_stats = { "판정대상": len(img_rows), "획득성공": sum(1 for r in img_rows if (r["image"] or {}).get("state") == "ok"), "AI판정": sum(1 for r in img_rows if r.get("image_ai_match") is not None), "AI기각": sum(1 for r in img_rows if any(v.startswith("image-ai") for v in r.get("image_veto", []))), "합의이탈": sum(1 for r in img_rows if any(v.startswith("image-outlier") for v in r.get("image_veto", []))), "참조사진": 1 if (target_img is not None and target_img.ok) else 0, "참조이탈": sum(1 for r in img_rows if any(v.startswith("image-ref") for v in r.get("image_veto", []))), } priced = [m for m in malls if m["price"] is not None] lowest = min(priced, key=lambda m: m["price"]) if priced else None snap = {"product_code": g["product_code"], "run_id": f"LOCAL-{int(time.time())}", "triggered_at": time.strftime("%Y-%m-%dT%H:%M:%S"), "query": query, "outcome": "found" if lowest else "not_found", "malls_total": len(malls), "malls_confirmed": sum(m["confirmed"] for m in malls), "partial": any(not m["confirmed"] for m in malls), "lowest_price": lowest["price"] if lowest else None, "lowest_source": lowest["source"] if lowest else None, "malls": malls, "elapsed_sec": round(time.perf_counter() - t0, 2), "stages": stages, "candidates": len(pool), "ai_matched": len(matched), "judge": judge.__class__.__name__, "attempts": attempt, "image_judge": image_judge.__class__.__name__ if image_judge else None, "image_stats": image_stats, # 레퍼런스 사진 획득 상태·sha256 — 성적서가 "비교 기준 사진"을 지목할 수 있게 "reference_image": target_img.as_log() if target_img is not None else None, # 오프라인 백테스트용 후보 전량 (이름·가격·AI점수·veto 사유·수락 여부) — # 이게 없으면 게이트 튜닝 1회당 100품목 재크롤링이 필요하다. "pool": pool_log, # 기권 사유: AI 는 매칭했지만 식별 게이트가 전부 기각 — 오탐 채택보다 정직한 상태 # 기권 사유는 어느 게이트가 막았는지까지 남긴다 — 이미지 게이트를 새로 넣은 뒤 # 기권이 늘면 원인이 텍스트인지 사진인지 이 값으로 갈린다. "abstain_reason": ( "image_vetoed" if lowest is None and any(r.get("image_veto") for r in pool_log) else "ai_match_vetoed" if lowest is None and any(r["ai_match"] for r in pool_log) else None)} return snap async def main(): ap = argparse.ArgumentParser() ap.add_argument("--golden", default=str(DATA_DIR / "price_search" / "golden.json")) ap.add_argument("--out", default=str(DATA_DIR / "price_search" / "snapshots")) ap.add_argument("--sources", default="danawa,enuri,gsshop") ap.add_argument("--limit", type=int, help="앞에서 N건만 수집") ap.add_argument("--judge", default="local", choices=["local", "ai"], help="동일상품 판정기 — local: 텍스트 검증(기본, LLM 불필요) / ai: OpenAI") ap.add_argument("--keyword", default="none", choices=["none", "ai"], help="룰 재정제가 전부 0매칭일 때 LLM 검색어 생성(정밀·광역) 사용 여부") ap.add_argument("--image", default="ai", choices=["ai", "off"], help="이미지 검증 — ai: VLM 사진 판정 + pHash 합의(기본) / off: 텍스트 축만") ap.add_argument("--image-dir", default=str(IMAGE_DIR), help="썸네일 캐시 경로 (sha256 이름 — 재판정 시 재크롤링 불필요)") ap.add_argument("--offset", type=int, default=0, help="골든셋 시작 오프셋") ap.add_argument("--retry-notfound", action="store_true", help="스냅샷이 없거나 not_found 인 품목만 재수집") args = ap.parse_args() sources = [s.strip() for s in args.sources.split(",") if s.strip() in ADAPTERS] golden = json.loads(Path(args.golden).read_text(encoding="utf-8")) golden = golden[args.offset: (args.offset + args.limit) if args.limit else None] out_dir = Path(args.out) out_dir.mkdir(parents=True, exist_ok=True) if args.retry_notfound: def _needs(g): p = out_dir / f"{g['product_code']}.json" if not p.exists(): return True return json.loads(p.read_text(encoding="utf-8")).get("outcome") != "found" before = len(golden) golden = [g for g in golden if _needs(g)] print(f"[재수집] 대상 {len(golden)}건 (전체 {before}건 중 found 제외)") if args.judge == "ai": if not os.getenv("OPENAI_API_KEY"): raise SystemExit("OPENAI_API_KEY 필요 (--judge ai)") judge = SimilarityJudge() else: from services.price_search.prism_core.local_judge import LocalJudge judge = LocalJudge() keyword_gen = None if args.keyword == "ai": if not os.getenv("OPENAI_API_KEY"): raise SystemExit("OPENAI_API_KEY 필요 (--keyword ai)") from services.price_search.prism_core.keyword import KeywordGenerator keyword_gen = KeywordGenerator(api_key=os.environ["OPENAI_API_KEY"]) image_judge = None if args.image == "ai": if not os.getenv("OPENAI_API_KEY"): raise SystemExit("OPENAI_API_KEY 필요 (--image ai)") from services.price_search.prism_core.image_judge import ImageJudge image_judge = ImageJudge() image_dir = Path(args.image_dir) for i, g in enumerate(golden, 1): print(f"[{i}/{len(golden)}] {g['product_code']} — {g.get('product_name', '')}") snap = await capture(g, sources, judge, keyword_gen, image_judge, image_dir) (out_dir / f"{g['product_code']}.json").write_text( json.dumps(snap, ensure_ascii=False, indent=1), encoding="utf-8") st = snap["image_stats"] print(f" → 후보 {snap['candidates']} / AI매칭 {snap['ai_matched']} / " f"이미지 {st['획득성공']}/{st['판정대상']}장 기각 {st['AI기각'] + st['합의이탈']} / " f"최저 {snap['lowest_price']}({snap['lowest_source']}) / partial={snap['partial']}") if __name__ == "__main__": asyncio.run(main())