"""인터넷 최저가 탐색 테스트 API — 탐색 엔진(services.price_search)을 데모 콘솔에 노출. selectolax 등 의존성이 없으면 import 가 실패하고, router.py 의 가드가 등록을 생략한다 — 협상 API 에는 영향 없다. 측정 하네스(eval/08_search_accuracy/run_excel.py)와 같은 엔진이다. """ import os import time from fastapi import APIRouter from pydantic import BaseModel, Field from services.price_search import capture as _capture_mod # noqa: E402,F401 — 부수효과: OPENAI_API_KEY env ← server/config.toml from services.price_search.capture import capture # noqa: E402 from services.price_search.prism_core.local_judge import LocalJudge # noqa: E402 from services.price_search.prism_core.similarity import SimilarityJudge # noqa: E402 router = APIRouter(tags=["price-search"]) class PriceSearchBody(BaseModel): product_name: str = Field(min_length=2, max_length=200) judge: str = Field(default="ai", pattern="^(ai|local)$") # 룰 재정제 라운드가 전부 0매칭일 때만 LLM 검색어 재정제를 추가 시도 (OpenAI 호출) keyword_refine: bool = False # 이미지 축(VLM 사진 판정 + pHash 합의). 측정 경로(run_excel)의 기본값과 맞춘다 — # 데모가 측정과 다른 파이프라인을 보여주면 콘솔로 확인한 결과를 성적서에 못 쓴다. image_verify: bool = True def _valid_key() -> bool: """실키 판별 — config.toml.example 의 'sk-여기에…' 플레이스홀더(비ASCII)로 OpenAI 클라이언트를 만들면 헤더 인코딩에서 500 이 난다. 로컬 폴백이 맞다.""" k = os.getenv("OPENAI_API_KEY", "") return k.startswith("sk-") and k.isascii() and len(k) >= 20 @router.post("/v1/price/search") async def price_search(body: PriceSearchBody): has_key = _valid_key() use_ai = body.judge == "ai" and has_key judge = SimilarityJudge() if use_ai else LocalJudge() keyword_gen = None if body.keyword_refine and has_key: from services.price_search.prism_core.keyword import KeywordGenerator keyword_gen = KeywordGenerator(api_key=os.environ["OPENAI_API_KEY"]) # 이미지 판정은 VLM 이라 실키가 없으면 아예 켜지지 않는다(로컬 폴백이 없는 축이다) image_judge = None if body.image_verify and has_key: from services.price_search.prism_core.image_judge import ImageJudge image_judge = ImageJudge() g = {"product_code": f"UI-{int(time.time())}", "product_name": body.product_name.strip()} snap = await capture(g, ["danawa", "enuri", "gsshop"], judge, keyword_gen, image_judge) # 요청과 실제 사용 판정기가 다를 수 있다(키 부재 폴백) — 정직하게 알린다 snap["judge_used"] = "ai" if use_ai else "local" snap["judge_fallback"] = body.judge == "ai" and not use_ai snap["keyword_refine_used"] = keyword_gen is not None snap["image_verify_used"] = image_judge is not None return snap