#!/usr/bin/env python3 """엑셀 품목 목록 → 인터넷 최저가 탐색 → 같은 엑셀에 **기계 판정만** 기입. 탐색 엔진은 server/services/price_search.capture() 재사용 (danawa·enuri·gsshop + 재정제 라운드). 검증은 2축이다 — 텍스트(SimilarityJudge + identity.veto), 이미지(ImageJudge + pHash 합의). 컬럼 분리 규약 (2026-09-07 확정 — 최종 판정은 사람이 한다): 기계 기입 검색어·탐색한_상품명·가격·배송비·URL·썸네일·AI유사도·이미지유사도·이미지합의 ·AI판정·기권사유·검색일시·소요초 사람 전용 일치여부(O/X/기권)·검수자·검수일시·검수메모 — 이 스크립트는 **절대 쓰지 않는다** 이전 판은 기계가 `일치여부`에 O/X 를 써서 사람 판정 자리를 덮었다. 그래서 기계의 결론은 `AI판정`으로 옮기고, `일치여부`는 빈 칸으로 남겨 검수자가 채운다. 집계는 run.py 가 한다. --resume 기준도 `일치여부`(사람) 대신 `검색일시`(기계)를 본다 — 사람 검수가 안 끝난 행을 미처리로 오인해 재크롤링하면 안 된다. 입력 열 (2026-09-08, 운용 상품 마스터 전환): 상품명·검색명 외에 제조사·모델명·규격·판매가를 capture() 의 payload 로 **따로** 넘긴다 — 브랜드 필터(company)·가격밴드(base_price)·identity.veto· VLM 프롬프트가 구조화 값을 쓴다. 이전 쿠팡 모집단은 상품명 한 줄뿐이라 이 경로가 비어 있었다. 가격밴드는 **기본 꺼짐** (2026-09-08 파일럿 20건 실측). 운용 마스터의 판매가는 B2B 계약가라 소비자 몰 가격보다 체계적으로 낮다 — HP 잉크 +30%, 캐리어 냉장고 +48%, LG 노트북 +75% — 그래서 ±70% 밴드가 LG 노트북 정답(1,910,400원 vs 판매가 1,090,000원)을 잘랐다(밴드 ON 60% / OFF 65%). 브랜드 필터·identity.veto·이미지 게이트가 오탐을 막고 있어 밴드 없이도 최종 수락은 27→32 건에 그쳤다. 밴드가 필요한 모집단이면 --price-band 로 켠다. 사용: python run_excel.py --xlsx items1000.xlsx [--judge ai|local] [--keyword ai] [--image ai|off] [--limit N] [--offset N] [--resume] [--price-band] 스냅샷 원본은 data/snapshots_excel/<상품코드>.json, 썸네일은 data/images/ 에 남긴다. """ 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)) # 탐색 엔진은 서버 패키지(server/services/price_search). 컨테이너는 /app, 로컬은 ../../server. _SERVER_ROOT = next((d for d in (HERE.parents[1] / "server", Path("/app")) if (d / "services").exists()), None) if _SERVER_ROOT is None: raise SystemExit("탐색 엔진을 찾지 못함 — server/services/price_search 가 필요하다") sys.path.insert(0, str(_SERVER_ROOT)) from services.price_search import capture as capture_mod # noqa: E402,F401 — OPENAI_API_KEY 로딩 부수효과 포함 from services.price_search.capture import ADAPTERS, IMAGE_DIR, capture # 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 sheet import HEADERS, HUMAN_COLS # noqa: E402 — 열 정의 단일 출처 # 썸네일 셀 크기 — 검수자가 상품명과 사진을 나란히 보고 O/X 를 찍는 화면이다. # 1,000건을 눈으로 넘겨야 하므로 작게(96px) 잡되 제품 형태는 알아볼 수 있어야 한다. _THUMB_PX = 96 _THUMB_ROW_PT = 74 # 96px ≈ 72pt + 여백 _THUMB_COL_WIDTH = 15 def _thumbnail(sha: str | None, image_dir: Path): """캐시된 원본 → 엑셀에 박을 PNG 썸네일(openpyxl Image). 실패는 None. 원본을 그대로 넣지 않는 이유: 몰 CDN 이 webp 로 주는 일이 잦은데 엑셀은 webp 를 못 그린다. 또 원본 크기 그대로면 1,000행 시트가 수백 MB 로 부푼다. BytesIO 가 아니라 **파일 경로**로 넘기는 이유(2026-09-07 실측): 이 스크립트는 행마다 wb.save() 를 한다(중단 안전). openpyxl 은 저장할 때마다 이미 붙은 이미지를 전부 다시 직렬화하는데, BytesIO 를 넘기면 첫 저장에서 버퍼가 닫혀 두 번째 저장이 'ValueError: I/O operation on closed file' 로 죽는다. 경로는 매번 새로 열려 안전하다. """ if not sha: return None src = image_store.cache_path(image_dir, sha) if not src.exists(): return None thumb_path = image_dir / "thumbs" / f"{sha}.png" try: from openpyxl.drawing.image import Image as XLImage from PIL import Image as PILImage if not thumb_path.exists(): thumb_path.parent.mkdir(parents=True, exist_ok=True) with PILImage.open(src) as im: im = im.convert("RGB") im.thumbnail((_THUMB_PX, _THUMB_PX)) im.save(thumb_path, format="PNG") return XLImage(str(thumb_path)) except Exception: # Pillow 미설치·디코드 실패 — 썸네일은 검수 편의일 뿐 증빙이 아니다 return None def _rematerialize_images(ws, image_dir: Path) -> int: """이미 저장된 시트를 다시 열어 행마다 저장할 때의 함정 (2026-09-09 실측). openpyxl 은 기존 파일의 이미지를 BytesIO 로 들고 있다가 첫 save 에서 그 버퍼를 닫는다 — 두 번째 save 가 'I/O operation on closed file' 로 죽고, 죽는 시점에 xlsx 가 반쯤 써져 **파일이 깨진다**(--codes 재실행에서 본측정 시트가 통째로 손상됐다). 그래서 열자마자 기존 이미지를 전부 디스크 파일로 내려 경로 참조로 바꿔 둔다 — 경로는 save 마다 새로 열린다.""" from openpyxl.drawing.image import Image as XLImage out_dir = image_dir / "thumbs" / "loaded" out_dir.mkdir(parents=True, exist_ok=True) fixed = [] for i, im in enumerate(ws._images): try: data = im._data() except Exception: continue # 이미 닫힌 버퍼 — 건너뛴다(그 행이 재실행되면 새 썸네일이 붙는다) path = out_dir / f"{id(ws)}_{i}.{(im.format or 'png').lower()}" path.write_bytes(data) new = XLImage(str(path)) new.anchor = im.anchor new.width, new.height = im.width, im.height fixed.append(new) ws._images = fixed return len(fixed) def _machine_cell(ws, col: dict, row: int, name: str): """기계가 쓸 수 있는 칸만 돌려준다 — HUMAN_COLS 로 새면 사람 판정이 덮인다.""" if name in HUMAN_COLS: raise AssertionError(f"기계는 사람 검수 열을 쓰지 않는다: {name}") return ws.cell(row, col[name]) def _ensure_headers(ws, col: dict): """사람 검수 열이 없는 구판 시트를 만나면 뒤에 덧붙인다 (기존 데이터 보존).""" added = [] for name in HEADERS: if name not in col: idx = ws.max_column + 1 ws.cell(1, idx).value = name col[name] = idx added.append(name) return added async def main(): ap = argparse.ArgumentParser() ap.add_argument("--xlsx", default=str(HERE / "items1000.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("--image", default="ai", choices=["ai", "off"], help="이미지 검증 — ai: VLM 사진 판정 + pHash 합의(기본) / off: 텍스트 축만") ap.add_argument("--image-dir", default=str(IMAGE_DIR)) ap.add_argument("--limit", type=int) ap.add_argument("--offset", type=int, default=0) ap.add_argument("--resume", action="store_true", help="검색일시가 이미 찍힌 행은 건너뛴다 (중단 재개 — 사람 검수 여부와 무관)") ap.add_argument("--retry-errors", action="store_true", help="AI판정이 '오류'인 행만 다시 돈다 (다른 행은 건너뜀)") ap.add_argument("--codes", default="", help="이 상품코드들만 다시 돈다 (쉼표 구분) — 게이트 수정의 영향 품목만 재실행할 때") ap.add_argument("--no-ref-image", action="store_true", help="참조이미지를 넘기지 않는다 — 레퍼런스 사진 비교의 효과를 재는 대조 실행용") ap.add_argument("--price-band", action="store_true", help="판매가 기준 가격밴드 필터(±70%%)를 켠다 — 기본 꺼짐(B2B 판매가는 몰 가격과 체계적으로 어긋난다)") 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) if name} added = _ensure_headers(ws, col) if added: print(f"[헤더 보강] {added}", flush=True) 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 services.price_search.prism_core.local_judge import LocalJudge judge = LocalJudge() keyword_gen = None if args.keyword == "ai": keyword_gen_key = os.getenv("OPENAI_API_KEY") if not keyword_gen_key: raise SystemExit("OPENAI_API_KEY 필요 (--keyword ai)") from services.price_search.prism_core.keyword import KeywordGenerator keyword_gen = KeywordGenerator(api_key=keyword_gen_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) snap_dir = HERE / "data" / "snapshots_excel" snap_dir.mkdir(parents=True, exist_ok=True) if ws._images: print(f"[이미지] 기존 썸네일 {_rematerialize_images(ws, image_dir)}장을 파일 참조로 전환", flush=True) ws.column_dimensions[ws.cell(1, col["썸네일"]).column_letter].width = _THUMB_COL_WIDTH ws.column_dimensions[ws.cell(1, col["참조썸네일"]).column_letter].width = _THUMB_COL_WIDTH rows = [r for r in range(2, ws.max_row + 1) if ws.cell(r, col["상품명"]).value] rows = rows[args.offset: (args.offset + args.limit) if args.limit else None] done = found = img_ok = img_seen = 0 only = {c.strip() for c in args.codes.split(",") if c.strip()} 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 only: if code not in only: continue elif args.retry_errors: if ws.cell(r, col["AI판정"]).value != "오류": continue elif args.resume and ws.cell(r, col["검색일시"]).value not in (None, ""): continue # 재실행 행에 이미 박힌 썸네일은 떼어낸다 — add_image 는 겹쳐 쌓이기만 한다 ws._images = [im for im in ws._images if getattr(getattr(im.anchor, "_from", None), "row", -1) != r - 1] print(f"[{n}/{len(rows)}] {code} — {name}", flush=True) # 질의(search_name)와 판정 기준(product_name)을 나눠 넘긴다 — capture 가 그렇게 받도록 # 설계돼 있다(2026-08-29). 검색명이 비어 있으면 capture 가 상품명으로 폴백한다. query = ws.cell(r, col["검색명"]).value if "검색명" in col else None g = {"product_code": code, "product_name": name, "search_name": str(query).strip() if query else ""} # 구조화 입력 열 — 열이 없는 구판 시트는 그대로 상품명 한 줄로 돈다 for src, key in (("제조사", "company"), ("모델명", "model"), ("규격", "specification")): v = ws.cell(r, col[src]).value if src in col else None g[key] = str(v).strip() if v not in (None, "") else "" price = ws.cell(r, col["판매가"]).value if "판매가" in col else None if args.price_band and isinstance(price, (int, float)) and price > 0: g["base_price"] = int(price) # 레퍼런스 사진 — 있으면 이미지 게이트가 사진↔사진 판정을 한다 ref = ws.cell(r, col["참조이미지"]).value if ("참조이미지" in col and not args.no_ref_image) else None g["ref_image_url"] = str(ref).strip() if ref not in (None, "") else "" try: snap = await capture(g, sources, judge, keyword_gen, image_judge, image_dir) except Exception as e: print(f" [오류] {e}", flush=True) _machine_cell(ws, col, r, "AI판정").value = "오류" _machine_cell(ws, col, r, "검색일시").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"]) _machine_cell(ws, col, r, "검색어").value = snap["query"] _machine_cell(ws, col, r, "탐색한_상품명").value = lowest["name"] if lowest else None _machine_cell(ws, col, r, "가격").value = lowest["price"] if lowest else None _machine_cell(ws, col, r, "배송비").value = lowest["shipping_fee"] if lowest else None _machine_cell(ws, col, r, "URL").value = lowest["detail_url"] if lowest else None _machine_cell(ws, col, r, "AI유사도").value = lowest["ai_score"] if lowest else None _machine_cell(ws, col, r, "이미지유사도").value = lowest["image_ai_score"] if lowest else None _machine_cell(ws, col, r, "이미지합의").value = lowest["image_consensus"] if lowest else None _machine_cell(ws, col, r, "참조사진유사도").value = lowest.get("image_ref_similarity") if lowest else None _machine_cell(ws, col, r, "기권사유").value = snap["abstain_reason"] _machine_cell(ws, col, r, "검색일시").value = snap["triggered_at"].replace("T", " ") _machine_cell(ws, col, r, "소요초").value = snap["elapsed_sec"] # AI판정 = 시스템이 상품을 반환했는가(기계). 동일상품 여부의 최종 결론이 아니다. _machine_cell(ws, col, r, "AI판정").value = "O" if lowest else "X" thumb = _thumbnail(lowest["image_sha256"] if lowest else None, image_dir) ref_img = snap.get("reference_image") or {} ref_thumb = _thumbnail(ref_img.get("sha256"), image_dir) if thumb is not None or ref_thumb is not None: ws.row_dimensions[r].height = _THUMB_ROW_PT if thumb is not None: ws.add_image(thumb, f"{ws.cell(r, col['썸네일']).column_letter}{r}") if ref_thumb is not None: ws.add_image(ref_thumb, f"{ws.cell(r, col['참조썸네일']).column_letter}{r}") done += 1 found += bool(lowest) img_seen += snap["image_stats"]["판정대상"] img_ok += snap["image_stats"]["획득성공"] wb.save(args.xlsx) # 행마다 저장 — 중단 안전 st = snap["image_stats"] print(f" → {'O' if lowest else 'X'} 최저 {snap['lowest_price']}" f"({snap['lowest_source']}) 사진 {st['획득성공']}/{st['판정대상']}장" f" 기각 {st['AI기각'] + st['합의이탈']} {snap['elapsed_sec']}s", flush=True) if not done: print("\n처리할 행 없음", flush=True) return print(f"\n완료: {done}건 처리, 탐색 성공 {found}건 ({found / done * 100:.1f}%) · " f"이미지 획득 {img_ok}/{img_seen}장", flush=True) print("→ '일치여부' 열에 O(동일 상품)/X(다른 상품)/기권 기입 후 python run.py --xlsx ...", flush=True) if __name__ == "__main__": asyncio.run(main())