#!/usr/bin/env python3 """엑셀 품목 목록 → 인터넷 최저가 탐색 → 같은 엑셀에 결과 기입. 입력 엑셀(시트 첫 행 = 헤더): #, 상품코드, 상품명, 검색어, 탐색한_상품명, 가격, 배송비, URL, AI유사도, 검색일시, 소요초, 일치여부 — 앞 3열만 채워져 있으면 된다. 측정 코어는 capture_local.capture() 재사용 (danawa·enuri·gsshop + 재정제 라운드). 판정기는 AI(SimilarityJudge) 기본 — AI유사도 컬럼에 매칭 점수를 기록한다. 사용: python run_excel.py --xlsx RESULTS/08_search_accuracy_items100.xlsx [--judge ai|local] [--keyword ai] [--limit N] [--resume] --resume: 일치여부가 이미 채워진 행은 건너뛴다 (중단 재개). 스냅샷 원본은 data/snapshots_excel/<상품코드>.json 에도 남긴다. """ import argparse import asyncio import json import os import sys import time from pathlib import Path HERE = Path(__file__).parent sys.path.insert(0, str(HERE)) import capture_local # noqa: E402 — OPENAI_API_KEY 로딩 부수효과 포함 from capture_local import ADAPTERS, capture # noqa: E402 from prism_core.similarity import SimilarityJudge # noqa: E402 HEADERS = ["#", "상품코드", "상품명", "검색어", "탐색한_상품명", "가격", "배송비", "URL", "AI유사도", "검색일시", "소요초", "일치여부"] async def main(): ap = argparse.ArgumentParser() ap.add_argument("--xlsx", default=str(HERE.parent.parent / "results" / "08_search_accuracy_items100.xlsx")) ap.add_argument("--sources", default="danawa,enuri,gsshop") ap.add_argument("--judge", default="ai", choices=["ai", "local"]) ap.add_argument("--keyword", default="none", choices=["none", "ai"]) ap.add_argument("--limit", type=int) ap.add_argument("--resume", action="store_true") args = ap.parse_args() import openpyxl wb = openpyxl.load_workbook(args.xlsx) ws = wb.worksheets[0] header = [c.value for c in ws[1]] col = {name: i + 1 for i, name in enumerate(header)} missing = [h for h in HEADERS if h not in col] if missing: raise SystemExit(f"엑셀 헤더 누락: {missing}") sources = [s.strip() for s in args.sources.split(",") if s.strip() in ADAPTERS] if args.judge == "ai": if not os.getenv("OPENAI_API_KEY"): raise SystemExit("OPENAI_API_KEY 필요 (--judge ai)") judge = SimilarityJudge() else: from prism_core.local_judge import LocalJudge judge = LocalJudge() keyword_gen = None if args.keyword == "ai": from prism_core.keyword import KeywordGenerator keyword_gen = KeywordGenerator(api_key=os.environ["OPENAI_API_KEY"]) snap_dir = HERE / "data" / "snapshots_excel" snap_dir.mkdir(parents=True, exist_ok=True) rows = [r for r in range(2, ws.max_row + 1) if ws.cell(r, col["상품명"]).value] if args.limit: rows = rows[: args.limit] done = found = 0 for n, r in enumerate(rows, 1): code = str(ws.cell(r, col["상품코드"]).value or f"ROW{r}") name = str(ws.cell(r, col["상품명"]).value).strip() if args.resume and ws.cell(r, col["일치여부"]).value not in (None, ""): continue print(f"[{n}/{len(rows)}] {code} — {name}", flush=True) g = {"product_code": code, "product_name": name} try: snap = await capture(g, sources, judge, keyword_gen) except Exception as e: print(f" [오류] {e}", flush=True) ws.cell(r, col["일치여부"]).value = "오류" ws.cell(r, col["검색일시"]).value = time.strftime("%Y-%m-%d %H:%M:%S") wb.save(args.xlsx) continue (snap_dir / f"{code}.json").write_text( json.dumps(snap, ensure_ascii=False, indent=1), encoding="utf-8") lowest = None if snap["lowest_price"] is not None: lowest = next(m for m in snap["malls"] if m["source"] == snap["lowest_source"] and m["price"] == snap["lowest_price"]) ws.cell(r, col["검색어"]).value = snap["query"] ws.cell(r, col["탐색한_상품명"]).value = lowest["name"] if lowest else None ws.cell(r, col["가격"]).value = lowest["price"] if lowest else None ws.cell(r, col["배송비"]).value = lowest["shipping_fee"] if lowest else None ws.cell(r, col["URL"]).value = lowest["detail_url"] if lowest else None ws.cell(r, col["AI유사도"]).value = lowest["ai_score"] if lowest else None ws.cell(r, col["검색일시"]).value = snap["triggered_at"].replace("T", " ") ws.cell(r, col["소요초"]).value = snap["elapsed_sec"] ws.cell(r, col["일치여부"]).value = "O" if lowest else "X" done += 1 found += bool(lowest) wb.save(args.xlsx) # 행마다 저장 — 중단 안전 print(f" → {'O' if lowest else 'X'} 최저 {snap['lowest_price']}" f"({snap['lowest_source']}) {snap['elapsed_sec']}s", flush=True) print(f"\n완료: {done}건 처리, 탐색 성공 {found}건 ({found / done * 100:.1f}%)" if done else "\n처리할 행 없음", flush=True) if __name__ == "__main__": asyncio.run(main())