Files
Negotiation_daegu/eval/08_search_accuracy/run_excel.py
T
민헌andClaude Fable 5 dfb9ad6e66 초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117)
- frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시)
- eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋
- results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256)
  ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99
- docker-compose.yml + run.sh: backend+frontend 일괄 기동

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
2026-08-31 13:09:52 +09:00

119 lines
5.2 KiB
Python

#!/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())