초기 커밋 — 협상 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
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
@@ -0,0 +1,435 @@
|
||||
#!/usr/bin/env python3
|
||||
"""①③ 협상 성공률 · 평균 가격 협상률 — 독립 실행 평가기.
|
||||
|
||||
NEGO_AGENT 서버(:53117 /v1/nego/chat)를 상대로, 공급사 역할 에이전트가 자동 협상을 수행한다.
|
||||
|
||||
구성:
|
||||
../../testdata/testset_*.json 합성 케이스셋 (generate_testset.py 산출)
|
||||
run.py 공급사 에이전트(scripted|llm) + 협상 루프 + 집계
|
||||
|
||||
사용:
|
||||
python run.py --testset testset_100.json --limit 3 # scripted (결정적, API 키 불필요)
|
||||
python run.py --testset testset_1000.json --opponent llm # GPT-4o 상대 (OPENAI_API_KEY, seed 고정)
|
||||
|
||||
출력:
|
||||
detail.jsonl 건별 상세 (라운드별 step/가격 흐름 포함)
|
||||
result.json 집계 — ① 성공률(목표 70%) + ③ 평균 가격 협상률(목표 3%)
|
||||
|
||||
판정:
|
||||
① 주판정 = 목표가 이하 제안 확보 (협상 과정에서 target 이하 제안을 받아냄)
|
||||
참고: 상품가 이하 확보(손해 없는 협상) / 앵커가 도달 협상완료(엔진 룰)
|
||||
③ = 성공(협상완료) 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균 (%)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
TESTDATA_DIR = HERE.parent.parent / "testdata"
|
||||
SERVER_CONFIG = HERE.parent.parent / "server" / "config.toml"
|
||||
MAX_MESSAGES = 40
|
||||
|
||||
# OPENAI_API_KEY: 환경변수 → server/config.toml 순
|
||||
if "OPENAI_API_KEY" not in os.environ and SERVER_CONFIG.exists():
|
||||
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)
|
||||
|
||||
|
||||
def post(url: str, body: dict, headers: dict | None = None) -> dict:
|
||||
req = urllib.request.Request(url, json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json", **(headers or {})})
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
class QuotaExhausted(RuntimeError):
|
||||
"""OpenAI 크레딧 소진 — 재시도 무의미, 측정 전체를 중단해야 한다."""
|
||||
|
||||
|
||||
# ---- 공급사 역할 상대 에이전트 --------------------------------------------
|
||||
|
||||
class ScriptedOpponent:
|
||||
"""결정적 양보 스케줄 (앵커 기준): anchor×1.10 에서 시작, 매 라운드 하한선(anchor×0.99)
|
||||
방향으로 90% 양보 → 3번째 제안에서 anchor 이하 도달."""
|
||||
|
||||
def __init__(self, start_ratio: float = 1.10, concession: float = 0.90,
|
||||
reserve_ratio: float = 0.99):
|
||||
self.start_ratio, self.concession, self.reserve_ratio = \
|
||||
start_ratio, concession, reserve_ratio
|
||||
|
||||
def next_price(self, case: dict, prev_offer, script: str = "") -> int:
|
||||
anchor = float(case["anchor"])
|
||||
reserve = anchor * self.reserve_ratio
|
||||
if prev_offer is None:
|
||||
return int(anchor * self.start_ratio)
|
||||
return int(max(prev_offer - (prev_offer - reserve) * self.concession, reserve))
|
||||
|
||||
def decide_accept(self, case: dict, prev_offer, script: str = "") -> bool:
|
||||
"""1% 추가 인하 제안 수락 여부: 인하가가 하한선 이상이면 수락 (결정적)."""
|
||||
if prev_offer is None:
|
||||
return False
|
||||
reserve = float(case["anchor"]) * self.reserve_ratio
|
||||
return int(prev_offer) * 0.99 >= reserve
|
||||
|
||||
|
||||
class LLMOpponent:
|
||||
"""GPT-4o 공급사 역할. 정보 비대칭 현실화: 구매측 내부가(target/anchor)는 비공개.
|
||||
상대 하한(원가) = 기존 공급가 × reserve_ratio (기본 0.90 — 공급사 마진 여유 가정)."""
|
||||
|
||||
TEMP, SEED = 0.0, 20260828
|
||||
PROMPT = ("당신은 B2B 공급사 영업 담당자다. 이 품목의 작년 공급가는 {base}원이고, "
|
||||
"당신의 원가 하한선은 {reserve}원이다 (이 아래로 팔면 손해).\n"
|
||||
"구매사(MD 챗봇)의 마지막 발화: {script}\n"
|
||||
"규칙: 하한선 위에서 가능한 높은 공급가를 제시하되, 상대가 계속 인하를 요구하면 "
|
||||
"라운드마다 단계적으로 양보하라. 합의가 안 되면 거래가 무산되므로 3라운드 이후에는 "
|
||||
"하한선 근처까지 양보를 검토하라. 직전 제안보다 높은 가격은 제시하지 마라.\n"
|
||||
"JSON만: {{\"price\": <정수>}}")
|
||||
ACCEPT_PROMPT = ("당신은 B2B 공급사 영업 담당자다. 이 품목의 작년 공급가는 {base}원이고, "
|
||||
"당신의 원가 하한선은 {reserve}원이다 (이 아래로 팔면 손해).\n"
|
||||
"당신의 현재 제안가는 {offer}원이다.\n"
|
||||
"구매사(MD 챗봇)의 마지막 발화: {script}\n"
|
||||
"구매사가 위 발화에서 제시한 조건(추가 인하 등)을 수락할지 결정하라. "
|
||||
"수락하면 즉시 계약이 확정되고, 거절하면 협상이 이대로 종료될 수 있다. "
|
||||
"하한선 아래로 손해를 보면서 수락하지는 마라.\n"
|
||||
"JSON만: {{\"accept\": true|false}}")
|
||||
|
||||
def __init__(self, reserve_ratio: float = 0.90, model: str = "gpt-4o"):
|
||||
self.reserve_ratio = reserve_ratio
|
||||
self.MODEL = model
|
||||
|
||||
def _ask(self, prompt: str) -> dict:
|
||||
"""LLM 호출 — 일시 오류(429/5xx·말포맷 JSON)는 지수 백오프 재시도,
|
||||
크레딧 소진(insufficient_quota)은 QuotaExhausted로 즉시 중단."""
|
||||
import time
|
||||
import urllib.error
|
||||
|
||||
body = {"model": self.MODEL, "temperature": self.TEMP, "seed": self.SEED,
|
||||
"response_format": {"type": "json_object"},
|
||||
"messages": [{"role": "user", "content": prompt}]}
|
||||
last_err = None
|
||||
for attempt in range(5):
|
||||
try:
|
||||
r = post("https://api.openai.com/v1/chat/completions", body,
|
||||
{"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"})
|
||||
return json.loads(r["choices"][0]["message"]["content"])
|
||||
except urllib.error.HTTPError as e:
|
||||
err_body = e.read().decode(errors="replace")
|
||||
if "insufficient_quota" in err_body or "credit_balance_exhausted" in err_body:
|
||||
raise QuotaExhausted("OpenAI 크레딧 소진 — 충전 후 --resume으로 재개")
|
||||
if e.code in (429, 500, 502, 503):
|
||||
wait = min(2 ** attempt * 2, 30)
|
||||
print(f" [재시도 {attempt + 1}/5] HTTP {e.code} — {wait}초 대기", flush=True)
|
||||
time.sleep(wait)
|
||||
last_err = e
|
||||
continue
|
||||
raise
|
||||
except (json.JSONDecodeError, KeyError, ValueError) as e:
|
||||
# 모델이 말포맷 JSON을 낸 경우 — 재시도
|
||||
print(f" [재시도 {attempt + 1}/5] 응답 파싱 실패: {str(e)[:60]}", flush=True)
|
||||
last_err = e
|
||||
continue
|
||||
raise last_err
|
||||
|
||||
def next_price(self, case: dict, prev_offer, script: str = "") -> int:
|
||||
base = case.get("item_price") or case.get("revenue")
|
||||
reserve = int(float(base) * self.reserve_ratio)
|
||||
out = self._ask(self.PROMPT.format(base=int(float(base)), reserve=reserve,
|
||||
script=script[:500]))
|
||||
price = int(out["price"])
|
||||
if prev_offer is not None:
|
||||
price = min(price, int(prev_offer)) # 비단조(가격 인상) 방지
|
||||
return max(price, reserve)
|
||||
|
||||
def decide_accept(self, case: dict, prev_offer, script: str = "") -> bool:
|
||||
"""와일드카드(1% 추가 인하 등) 수락 여부를 GPT-4o가 공급사 입장에서 판단."""
|
||||
base = case.get("item_price") or case.get("revenue")
|
||||
reserve = int(float(base) * self.reserve_ratio)
|
||||
out = self._ask(self.ACCEPT_PROMPT.format(
|
||||
base=int(float(base)), reserve=reserve,
|
||||
offer=int(prev_offer) if prev_offer else 0, script=script[:500]))
|
||||
return bool(out.get("accept"))
|
||||
|
||||
|
||||
# ---- 협상 루프 -------------------------------------------------------------
|
||||
|
||||
def build_card_data(case: dict, price, anchor_v) -> dict:
|
||||
"""케이스 합성 card_data + 기능정의서 산식의 동적 값.
|
||||
- 경쟁사가격반영 = 100(1 − 앵커/입력가), 최소 1
|
||||
- 인터넷최저가: 케이스 값 우선, 없으면 목표가 대체"""
|
||||
card_data = dict(case.get("card_data") or {})
|
||||
card_data["anchoring_price"] = int(anchor_v) if anchor_v else None
|
||||
card_data.setdefault("internet_min_price",
|
||||
int(case["target"]) if case.get("target") else None)
|
||||
card_data.setdefault("alternative_supplier_count", 2)
|
||||
if price and anchor_v and float(price) > 0:
|
||||
card_data["competitor_price_diff"] = round(
|
||||
max(100 * (1 - float(anchor_v) / float(price)), 1), 1)
|
||||
return card_data
|
||||
|
||||
|
||||
def negotiate(url: str, case: dict, opponent, profiling: bool = False) -> dict:
|
||||
session_id = f"EVAL-{case['id']}"
|
||||
base = {
|
||||
"rq_type": "재협상", "session_id": session_id,
|
||||
"item_price": case.get("item_price") or case.get("revenue"),
|
||||
"revenue": case.get("revenue"), "dist": case.get("dist"),
|
||||
"partners_yn": case.get("partners_yn"), "partners": case.get("partners", 0),
|
||||
"anchor": case.get("anchor"), "target": case.get("target"),
|
||||
"profiling": profiling,
|
||||
}
|
||||
index, step = 0, "시작"
|
||||
user_input = price = initial = None
|
||||
iteration, offer = 0, None
|
||||
rounds, final_price, reached_done = [], None, False
|
||||
accepted_1pct = False
|
||||
|
||||
anchor_v = case.get("anchor")
|
||||
for _ in range(MAX_MESSAGES):
|
||||
body = {**base, "index": index, "step": step, "user_input": user_input,
|
||||
"input": price, "initial": initial, "iteration": iteration,
|
||||
"card_data": build_card_data(case, price, anchor_v)}
|
||||
res = post(url, body)
|
||||
meta = res.get("chat_metadata") or {}
|
||||
rounds.append({"req_step": step, "req_input": user_input, "req_price": price,
|
||||
"res_step": res["step"], "input_mode": res["next_input_mode"],
|
||||
"res_price": meta.get("price"),
|
||||
"script_head": res["script"][:80].replace("\n", " ")})
|
||||
if res["step"] == "협상완료":
|
||||
reached_done, final_price = True, meta.get("price") or price
|
||||
if res["chat_end"]:
|
||||
break
|
||||
step, index = res["step"], res["index"]
|
||||
mode = res["next_input_mode"]
|
||||
user_input = None
|
||||
if mode == "confirm":
|
||||
user_input = "확인"
|
||||
elif mode == "yes_no":
|
||||
if step == "wild_card_1pct":
|
||||
# 1% 추가 인하 제안: 수락 여부는 공급사(상대)가 결정
|
||||
ok = opponent.decide_accept(case, offer, res["script"])
|
||||
user_input = "예" if ok else "아니오"
|
||||
accepted_1pct = accepted_1pct or ok
|
||||
else:
|
||||
user_input = "예"
|
||||
elif mode == "price":
|
||||
offer = opponent.next_price(case, offer, res["script"])
|
||||
if initial is None:
|
||||
initial = offer
|
||||
else:
|
||||
iteration += 1
|
||||
price = offer
|
||||
|
||||
# 세션 종료 — UCB 에피소드 초기화 (다음 케이스와 격리)
|
||||
try:
|
||||
post(url.replace("/chat", "/session/invalidate"),
|
||||
{"session_id": session_id, "reason": "평가 케이스 종료"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 판정
|
||||
prices = [rd["req_price"] for rd in rounds if rd.get("req_price") is not None]
|
||||
# 1% 카드 수락 시 합의가(= 직전 제안가 × 0.99)는 상대가 동의한 제안가로 판정에 포함
|
||||
if accepted_1pct and final_price is not None:
|
||||
prices.append(final_price)
|
||||
lowest = min(prices) if prices else None
|
||||
prev_price = case.get("item_price") or case.get("revenue")
|
||||
success_target = bool(lowest is not None and case.get("target") is not None
|
||||
and float(lowest) <= float(case["target"]))
|
||||
success_product = bool(lowest is not None and prev_price is not None
|
||||
and float(lowest) <= float(prev_price))
|
||||
success_engine = bool(reached_done and final_price is not None
|
||||
and float(final_price) <= float(case["target"]))
|
||||
|
||||
# ③ 가격 협상률: 협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가
|
||||
reduction_pct = None
|
||||
if reached_done and final_price is not None and prev_price:
|
||||
reduction_pct = round(100 * (float(prev_price) - float(final_price))
|
||||
/ float(prev_price), 3)
|
||||
|
||||
return {"case_id": case["id"], "quotation_number": case.get("quotation_number"),
|
||||
"item_name": case.get("item_name"),
|
||||
"success": success_target, "success_target": success_target,
|
||||
"success_product": success_product, "success_engine": success_engine,
|
||||
"lowest_offer": lowest, "prev_price": prev_price,
|
||||
"accepted_1pct": accepted_1pct,
|
||||
"target": case.get("target"), "anchor": case.get("anchor"),
|
||||
"initial_offer": initial, "final_price": final_price,
|
||||
"reduction_pct": reduction_pct,
|
||||
"outcome": rounds[-1]["res_step"] if rounds else None,
|
||||
"n_messages": len(rounds), "rounds": rounds}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--url", default="http://127.0.0.1:53117/v1/nego/chat")
|
||||
ap.add_argument("--opponent", default="scripted", choices=["scripted", "llm"])
|
||||
ap.add_argument("--testset", default="testset_1000.json",
|
||||
help="testdata/ 안의 케이스셋 파일명")
|
||||
ap.add_argument("--target-rate", type=float, default=70.0, help="① 목표 성공률(%%)")
|
||||
ap.add_argument("--target-reduction", type=float, default=3.0, help="③ 목표 협상률(%%)")
|
||||
ap.add_argument("--profiling", action="store_true",
|
||||
help="N-profiling(LLM 톤 재작성) 활성 상태로 측정 (기본 off)")
|
||||
ap.add_argument("--llm-reserve-ratio", type=float, default=0.90)
|
||||
ap.add_argument("--model", default="gpt-4o", help="LLM 상대 모델 (opponent=llm일 때)")
|
||||
ap.add_argument("--case-range", default=None,
|
||||
help="케이스 id 범위 'START:END' (양끝 포함, 예: 1:333) — 분할 측정용")
|
||||
ap.add_argument("--out-dir", default=None, help="산출물 폴더 (기본: 스크립트 폴더)")
|
||||
ap.add_argument("--tag", default=None, help="산출물 접미사 → detail_{tag}.jsonl, result_{tag}.json")
|
||||
ap.add_argument("--resume", action="store_true",
|
||||
help="기존 detail의 완료 case_id는 스킵하고 이어서 측정")
|
||||
ap.add_argument("--verbose", "-v", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
# [사전 점검] NEGO_AGENT 서버 응답 확인
|
||||
base_url = args.url.split("/v1/")[0]
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + "/health", timeout=5) as r:
|
||||
body = r.read().decode(errors="replace")
|
||||
if "NEGO_AGENT" not in body:
|
||||
raise SystemExit(f"[사전 점검 실패] {base_url}/health 가 NEGO_AGENT 서버가 아닙니다: {body[:120]}")
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise SystemExit(f"[사전 점검 실패] 서버({base_url}) 연결 불가: {e}\n"
|
||||
f"→ cd server && .venv/bin/python web_main.py")
|
||||
|
||||
data = json.loads((TESTDATA_DIR / args.testset).read_text(encoding="utf-8"))
|
||||
cases = data["cases"]
|
||||
if args.case_range:
|
||||
lo, hi = (int(x) for x in args.case_range.split(":"))
|
||||
cases = [c for c in cases if lo <= c["id"] <= hi]
|
||||
cases = cases[: args.limit]
|
||||
opponent = LLMOpponent(args.llm_reserve_ratio, model=args.model) \
|
||||
if args.opponent == "llm" else ScriptedOpponent()
|
||||
|
||||
out_dir = Path(args.out_dir) if args.out_dir else HERE
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
suffix = f"_{args.tag}" if args.tag else ""
|
||||
detail_path = out_dir / f"detail{suffix}.jsonl"
|
||||
|
||||
# 재개: 기존 detail에서 정상 완료 건은 스킵, '오류' 건은 버리고 재측정
|
||||
done_ids, results = set(), []
|
||||
if args.resume and detail_path.exists():
|
||||
dropped = 0
|
||||
for line in detail_path.read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
r = json.loads(line)
|
||||
if str(r.get("outcome", "")).startswith("오류"):
|
||||
dropped += 1
|
||||
continue
|
||||
done_ids.add(r["case_id"])
|
||||
results.append(r)
|
||||
# 오류 행 제거본으로 파일 재작성 (이후 append로 이어짐)
|
||||
detail_path.write_text(
|
||||
"".join(json.dumps(r, ensure_ascii=False) + "\n" for r in results),
|
||||
encoding="utf-8")
|
||||
print(f"[재개] 정상 완료 {len(done_ids)}건 스킵, 오류 {dropped}건 재측정 포함 "
|
||||
f"남은 {len(cases) - len(done_ids)}건 진행")
|
||||
else:
|
||||
detail_path.write_text("", encoding="utf-8")
|
||||
|
||||
from datetime import datetime as _dt
|
||||
for case in cases:
|
||||
if case["id"] in done_ids:
|
||||
continue
|
||||
try:
|
||||
r = negotiate(args.url, case, opponent, profiling=args.profiling)
|
||||
except QuotaExhausted as e:
|
||||
# 크레딧 소진: 이 케이스는 기록하지 않고 측정 전체 중단 (충전 후 --resume)
|
||||
print(f"\n[중단] {e} — 완료 {len(results)}건은 보존됨", flush=True)
|
||||
raise SystemExit(3)
|
||||
except Exception as e:
|
||||
r = {"case_id": case["id"], "quotation_number": case.get("quotation_number"),
|
||||
"success": False, "outcome": f"오류: {e}", "rounds": []}
|
||||
results.append(r)
|
||||
with open(detail_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
mark = "✅ 성공" if r["success"] else "❌ 실패"
|
||||
print(f"[{len(results):3d}/{len(cases)}] {str(r.get('item_name') or '')[:16]:16s} "
|
||||
f"{str(r.get('outcome')):8s} 최종가 {str(r.get('final_price')):>10s} "
|
||||
f"/ 목표 {str(r.get('target')):>10s} {mark}", flush=True)
|
||||
if args.verbose:
|
||||
for rd in r.get("rounds", []):
|
||||
if rd.get("req_price") is not None or rd["res_step"] in ("협상완료", "협상실패"):
|
||||
print(f" {rd['req_step']:14s} 제안 {str(rd.get('req_price')):>10s} → {rd['res_step']}")
|
||||
# 25건마다 중간 집계
|
||||
if len(results) % 25 == 0:
|
||||
_s = sum(1 for x in results if x.get("success"))
|
||||
_reds = [x["reduction_pct"] for x in results if x.get("reduction_pct") is not None]
|
||||
_avg = round(sum(_reds) / len(_reds), 3) if _reds else 0.0
|
||||
print(f"--- 중간집계 [{_dt.now().strftime('%H:%M:%S')}] {len(results)}건: "
|
||||
f"① {round(100 * _s / len(results), 2)}% · ③ {_avg}% ---", flush=True)
|
||||
|
||||
# 집계
|
||||
total = len(results)
|
||||
success = sum(1 for r in results if r["success"])
|
||||
success_prod = sum(1 for r in results if r.get("success_product"))
|
||||
success_eng = sum(1 for r in results if r.get("success_engine"))
|
||||
rate = round(100 * success / total, 2) if total else 0.0
|
||||
reductions = [r["reduction_pct"] for r in results if r.get("reduction_pct") is not None]
|
||||
avg_reduction = round(sum(reductions) / len(reductions), 3) if reductions else 0.0
|
||||
|
||||
out = {
|
||||
"opponent": args.opponent, "testset": args.testset, "profiling": args.profiling,
|
||||
"total": total,
|
||||
"지표①_협상성공률": {
|
||||
"판정기준": "목표가 이하 제안 확보",
|
||||
"success": success, "win_rate_pct": rate,
|
||||
"target_pct": args.target_rate,
|
||||
"verdict": "PASS" if rate >= args.target_rate else "FAIL",
|
||||
"참고지표": {
|
||||
"상품가_이하_확보": {"success": success_prod,
|
||||
"rate_pct": round(100 * success_prod / total, 2) if total else 0.0,
|
||||
"기준": "기존 공급가 유지·인하 = 손해 없는 협상"},
|
||||
"앵커가_도달_합의": {"success": success_eng,
|
||||
"rate_pct": round(100 * success_eng / total, 2) if total else 0.0,
|
||||
"기준": "앵커가 도달 협상완료 (엔진 룰)"},
|
||||
},
|
||||
},
|
||||
"지표③_평균가격협상률": {
|
||||
"산식": "협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균",
|
||||
"합의건수": len(reductions), "avg_reduction_pct": avg_reduction,
|
||||
"target_pct": args.target_reduction,
|
||||
"verdict": "PASS" if avg_reduction >= args.target_reduction else "FAIL",
|
||||
},
|
||||
"detail_file": detail_path.name,
|
||||
}
|
||||
if args.opponent == "llm":
|
||||
out["model"] = args.model
|
||||
out["seed"] = LLMOpponent.SEED
|
||||
if args.case_range:
|
||||
out["case_range"] = args.case_range
|
||||
(out_dir / f"result{suffix}.json").write_text(
|
||||
json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
from datetime import datetime
|
||||
avg_msg = sum(r.get("n_messages", 0) for r in results) / total if total else 0
|
||||
W = 66
|
||||
print()
|
||||
print("=" * W)
|
||||
print(" ①③ 협상 성공률 · 평균 가격 협상률 — 평가 요약".center(W - 12))
|
||||
print("=" * W)
|
||||
print(f" 시험 일시 : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print(f" 상대 에이전트 : " + ("scripted (결정적 양보 스케줄)" if args.opponent == "scripted"
|
||||
else f"{args.model} (seed 고정)"))
|
||||
print(f" 케이스 : {total}건 ({args.testset}) · profiling {'on' if args.profiling else 'off'}")
|
||||
print(f" ① 협상 성공률 : {rate} % (목표 {args.target_rate} %) → "
|
||||
f"{out['지표①_협상성공률']['verdict']} [성공 {success} / 실패 {total - success}]")
|
||||
print(f" 참고: 상품가 이하 {success_prod}건 / 앵커가 합의 {success_eng}건")
|
||||
print(f" ③ 평균 협상률 : {avg_reduction} % (목표 {args.target_reduction} %) → "
|
||||
f"{out['지표③_평균가격협상률']['verdict']} [합의 {len(reductions)}건 기준]")
|
||||
print(f" 평균 메시지 : {avg_msg:.1f}건")
|
||||
print(f" 산출물 : result{suffix}.json · {detail_path.name}")
|
||||
print("=" * W)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""① 본측정 오케스트레이터 — OpenAI 3종 분할 측정.
|
||||
|
||||
계획서 목표 근거("LLM 협상 시뮬레이션 상위 세 개 모델 평균")에 맞춰 케이스를
|
||||
3개 모델에 블록 분할(모델당 100건, 총 300건 — 2026-08-28 축소 결정)하고,
|
||||
모델별 결과 + 3모델 통합을 집계한다.
|
||||
|
||||
※ 블록 분할 이유: 테스트셋이 27개 조합(유통×파트너×매출) 순환 구조라 교차 분할(id%3)을
|
||||
쓰면 모델당 9개 조합만 배정된다. 연속 블록 333건이면 27조합이 각 ~12회씩 온전히 돈다.
|
||||
|
||||
사용:
|
||||
python run_split.py # 새 측정 (본측정_YYYYMMDD/ 폴더 생성)
|
||||
python run_split.py --resume --dir 본측정_20260828 # 중단 지점부터 재개
|
||||
|
||||
기록:
|
||||
<폴더>/detail_<모델>.jsonl 건별 상세 (케이스마다 즉시 append — 중단 안전)
|
||||
<폴더>/log_<모델>.txt 진행 로그 (25건마다 중간집계 포함, tail -f 가능)
|
||||
<폴더>/result_<모델>.json 모델별 집계
|
||||
<폴더>/result.json 3모델 통합 (모델별 breakdown + 가중평균 + ①③ 판정)
|
||||
<폴더>/meta.json 측정 조건 (모델·분할·seed·시작/종료 시각)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
# 축소 설계 (2026-08-28 사용자 결정): 모델당 100건 × 3 = 총 300건
|
||||
# 연속 블록 100건이면 27조합(유통×파트너×매출)이 각 3~4회씩 돌아 모델별 커버리지 유지
|
||||
MODELS = [
|
||||
("gpt-4o", "1:100"),
|
||||
("gpt-4.1", "101:200"),
|
||||
("gpt-4o-mini", "201:300"),
|
||||
]
|
||||
TESTSET = "testset_1000.json"
|
||||
TARGET_RATE, TARGET_REDUCTION = 70.0, 3.0
|
||||
|
||||
|
||||
def run_model(model: str, case_range: str, out_dir: Path, resume: bool) -> int:
|
||||
tag = model.replace(".", "_")
|
||||
log_path = out_dir / f"log_{tag}.txt"
|
||||
cmd = [sys.executable, str(HERE / "run.py"),
|
||||
"--opponent", "llm", "--model", model,
|
||||
"--testset", TESTSET, "--case-range", case_range,
|
||||
"--out-dir", str(out_dir), "--tag", tag]
|
||||
if resume:
|
||||
cmd.append("--resume")
|
||||
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} ({case_range}) 시작 → {log_path.name}",
|
||||
flush=True)
|
||||
with open(log_path, "a", encoding="utf-8") as log:
|
||||
log.write(f"\n===== {datetime.now().isoformat()} {model} {case_range} =====\n")
|
||||
log.flush()
|
||||
rc = subprocess.call(cmd, stdout=log, stderr=subprocess.STDOUT)
|
||||
print(f"[{datetime.now().strftime('%H:%M:%S')}] {model} 종료 (rc={rc})", flush=True)
|
||||
return rc
|
||||
|
||||
|
||||
def aggregate(out_dir: Path) -> dict:
|
||||
per_model, all_details = {}, []
|
||||
for model, case_range in MODELS:
|
||||
tag = model.replace(".", "_")
|
||||
detail_path = out_dir / f"detail_{tag}.jsonl"
|
||||
rows = []
|
||||
if detail_path.exists():
|
||||
rows = [json.loads(x) for x in
|
||||
detail_path.read_text(encoding="utf-8").splitlines() if x.strip()]
|
||||
all_details.extend(rows)
|
||||
n = len(rows)
|
||||
s = sum(1 for r in rows if r.get("success"))
|
||||
reds = [r["reduction_pct"] for r in rows if r.get("reduction_pct") is not None]
|
||||
per_model[model] = {
|
||||
"case_range": case_range, "n": n, "success": s,
|
||||
"win_rate_pct": round(100 * s / n, 2) if n else None,
|
||||
"avg_reduction_pct": round(sum(reds) / len(reds), 3) if reds else None,
|
||||
"상품가_이하": sum(1 for r in rows if r.get("success_product")),
|
||||
"앵커가_합의": sum(1 for r in rows if r.get("success_engine")),
|
||||
}
|
||||
|
||||
total = len(all_details)
|
||||
success = sum(1 for r in all_details if r.get("success"))
|
||||
reds = [r["reduction_pct"] for r in all_details if r.get("reduction_pct") is not None]
|
||||
rate = round(100 * success / total, 2) if total else 0.0
|
||||
avg_red = round(sum(reds) / len(reds), 3) if reds else 0.0
|
||||
model_rates = [m["win_rate_pct"] for m in per_model.values() if m["win_rate_pct"] is not None]
|
||||
return {
|
||||
"설계": "OpenAI 상위 3종 분할 측정 — 계획서 근거 '상위 세 개 모델 평균'(arxiv 2402.05863) 대응",
|
||||
"testset": TESTSET, "seed": 20260828, "profiling": False,
|
||||
"모델별": per_model,
|
||||
"지표①_협상성공률": {
|
||||
"판정기준": "목표가 이하 제안 확보",
|
||||
"total": total, "success": success,
|
||||
"win_rate_pct_통합": rate,
|
||||
"win_rate_pct_3모델단순평균": round(sum(model_rates) / len(model_rates), 2)
|
||||
if len(model_rates) == len(MODELS) else None,
|
||||
"target_pct": TARGET_RATE,
|
||||
"verdict": "PASS" if rate >= TARGET_RATE else "FAIL",
|
||||
"참고지표": {
|
||||
"상품가_이하_확보(계획서 기준: 손해 없는 협상)":
|
||||
sum(1 for r in all_details if r.get("success_product")),
|
||||
"앵커가_도달_합의":
|
||||
sum(1 for r in all_details if r.get("success_engine")),
|
||||
},
|
||||
},
|
||||
"지표③_평균가격협상률": {
|
||||
"산식": "협상완료 합의 건의 (기존 공급가 − 최종 합의가) / 기존 공급가 평균",
|
||||
"합의건수": len(reds), "avg_reduction_pct": avg_red,
|
||||
"target_pct": TARGET_REDUCTION,
|
||||
"verdict": "PASS" if avg_red >= TARGET_REDUCTION else "FAIL",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--dir", default=None, help="측정 폴더 (기본: 본측정_YYYYMMDD)")
|
||||
ap.add_argument("--resume", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
out_dir = HERE / (args.dir or f"본측정_{datetime.now().strftime('%Y%m%d')}")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
meta_path = out_dir / "meta.json"
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {
|
||||
"설계": "OpenAI 3종 블록 분할 — 모델당 100건 (1~100/101~200/201~300)",
|
||||
"models": dict(MODELS), "testset": TESTSET, "seed": 20260828,
|
||||
"profiling": False, "시작": datetime.now().isoformat(),
|
||||
}
|
||||
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
for model, case_range in MODELS:
|
||||
rc = run_model(model, case_range, out_dir, resume=args.resume)
|
||||
# 모델 하나 끝날 때마다 통합 결과 갱신 (중간에도 result.json이 항상 최신)
|
||||
result = aggregate(out_dir)
|
||||
(out_dir / "result.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
if rc == 3: # 크레딧 소진 — 다음 모델로 넘어가지 않고 전체 중단
|
||||
print("[중단] OpenAI 크레딧 소진 — 충전 후 `python3 run_split.py "
|
||||
f"--dir {out_dir.name} --resume` 로 재개", flush=True)
|
||||
raise SystemExit(3)
|
||||
|
||||
meta["종료"] = datetime.now().isoformat()
|
||||
meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
result = aggregate(out_dir)
|
||||
print()
|
||||
print(json.dumps({"모델별": result["모델별"],
|
||||
"①": result["지표①_협상성공률"]["win_rate_pct_통합"],
|
||||
"③": result["지표③_평균가격협상률"]["avg_reduction_pct"]},
|
||||
ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""② 협상 성공률(대인) — 운용통계 실기록 추출 + 집계.
|
||||
|
||||
입력: 네고위즈 운용통계데이터/통합.xlsx (마감데이터_통합 시트, 2025-06~11 운용 전수)
|
||||
방법 (선택 편향 방지 — 케이스 선별이 아니라 규칙 표집):
|
||||
1. 중복여부=='중복' 행 제외 (원장 정리 기준 승계)
|
||||
2. 모집단 전수의 상태값 분포를 그대로 유지하는 **비례 층화 무작위 표집** 100건
|
||||
(seed 고정 — 재현 가능. 모집단 성공률을 설계상 보존하므로 표본이 모집단을 대표)
|
||||
3. 성공 정의: 협력사별 상태값 == '협상완료' (미참여·협상거부 = 실패로 보수 집계)
|
||||
|
||||
컬럼: 측정 엔진(NEGO_AGENT)이 산출 가능한 필드만 유지 —
|
||||
견적명·견적번호·견적차수·상품코드·협력사코드·협력사별 상태값·협상구분·시나리오·인터넷최저가
|
||||
(배송형태·부가세여부·거부사유·출처파일·중복여부는 엔진 산출 범위 밖이라 제외)
|
||||
|
||||
사용: python extract_from_negowiz.py [--n 100] [--seed 20260831] [--target 75]
|
||||
출력: data/human_sample<N>.csv, data/human_sample<N>_meta.json, result.json
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import random
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
SOURCE = HERE.parent.parent.parent / "네고위즈 운용통계데이터" / "통합.xlsx"
|
||||
KEEP = ["견적명", "견적번호", "견적차수", "상품코드", "협력사코드",
|
||||
"협력사별 상태값", "협상구분", "시나리오", "인터넷최저가"]
|
||||
SUCCESS_STATE = "협상완료"
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--n", type=int, default=100)
|
||||
ap.add_argument("--seed", type=int, default=20260831)
|
||||
ap.add_argument("--target", type=float, default=75.0)
|
||||
args = ap.parse_args()
|
||||
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(SOURCE, read_only=True)
|
||||
ws = wb["마감데이터_통합"]
|
||||
it = ws.iter_rows(values_only=True)
|
||||
hdr = list(next(it))
|
||||
idx = {h: i for i, h in enumerate(hdr)}
|
||||
rows = [r for r in it if r[idx["견적번호"]]]
|
||||
|
||||
pop = [r for r in rows if r[idx["중복여부"]] != "중복"]
|
||||
pop_states = Counter(r[idx["협력사별 상태값"]] for r in pop)
|
||||
pop_rate = 100 * pop_states[SUCCESS_STATE] / len(pop)
|
||||
|
||||
# 비례 층화: 상태값별 표본 수 = round(모집단 비율 × n), 잔여는 최대 층에 보정
|
||||
quota = {s: round(c / len(pop) * args.n) for s, c in pop_states.items()}
|
||||
drift = args.n - sum(quota.values())
|
||||
quota[max(pop_states, key=pop_states.get)] += drift
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
sample = []
|
||||
for state, k in quota.items():
|
||||
bucket = [r for r in pop if r[idx["협력사별 상태값"]] == state]
|
||||
sample.extend(rng.sample(bucket, k))
|
||||
rng.shuffle(sample)
|
||||
|
||||
out_csv = HERE / "data" / f"human_sample{args.n}.csv"
|
||||
out_csv.parent.mkdir(exist_ok=True)
|
||||
with open(out_csv, "w", encoding="utf-8-sig", newline="") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(KEEP)
|
||||
for r in sample:
|
||||
w.writerow([r[idx[k]] for k in KEEP])
|
||||
|
||||
success = sum(1 for r in sample if r[idx["협력사별 상태값"]] == SUCCESS_STATE)
|
||||
rate = round(100 * success / len(sample), 2)
|
||||
meta = {
|
||||
"출처": str(SOURCE.name) + " (마감데이터_통합, 2025-06~11 운용 전수)",
|
||||
"추출규칙": "중복 제외 → 상태값 비례 층화 무작위 표집 (케이스 선별 없음)",
|
||||
"seed": args.seed,
|
||||
"모집단": {"n": len(pop), "상태분포": dict(pop_states),
|
||||
"성공률_pct": round(pop_rate, 2)},
|
||||
"표본": {"n": len(sample), "층화쿼터": quota},
|
||||
"성공정의": f"협력사별 상태값 == '{SUCCESS_STATE}' (미참여·협상거부 = 실패)",
|
||||
}
|
||||
(HERE / "data" / f"human_sample{args.n}_meta.json").write_text(
|
||||
json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
result = {
|
||||
"지표": "② 협상 성공률(대인) — 운용 실기록",
|
||||
**meta,
|
||||
"success": success, "win_rate_pct": rate,
|
||||
"target_pct": args.target,
|
||||
"verdict": "PASS" if rate >= args.target else "FAIL",
|
||||
}
|
||||
(HERE / "result.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑥ 답변속도 — 서버 계측(response_time.jsonl) 집계기.
|
||||
|
||||
서버가 /v1/nego/chat 요청마다 기록한 처리시간(요청 수신 → 응답 완료 ms)을 집계한다.
|
||||
측정 구간: 답변 생성 엔진 내부 처리 (HTTP 미들웨어 계측, localhost 왕복 제외분 없음)
|
||||
|
||||
사용:
|
||||
python aggregate.py # 서버 data/response_time.jsonl 전체
|
||||
python aggregate.py --since 2026-08-28T15:14 # 특정 시각 이후만 (본측정 구간 등)
|
||||
python aggregate.py --target 600
|
||||
|
||||
출력: result.json (n, p50/p95/p99/max, 목표 대비 판정)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
DEFAULT_LOG = HERE.parent.parent / "server" / "data" / "response_time.jsonl"
|
||||
|
||||
|
||||
def percentile(sorted_vals, p):
|
||||
if not sorted_vals:
|
||||
return None
|
||||
k = (len(sorted_vals) - 1) * p / 100
|
||||
lo, hi = int(k), min(int(k) + 1, len(sorted_vals) - 1)
|
||||
return round(sorted_vals[lo] + (sorted_vals[hi] - sorted_vals[lo]) * (k - lo), 2)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--log", default=str(DEFAULT_LOG))
|
||||
ap.add_argument("--since", default=None, help="ISO 시각 이후 표본만 (예: 2026-08-28T15:14)")
|
||||
ap.add_argument("--until", default=None)
|
||||
ap.add_argument("--target", type=float, default=600.0, help="목표 ms")
|
||||
args = ap.parse_args()
|
||||
|
||||
rows = []
|
||||
for line in Path(args.log).read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
r = json.loads(line)
|
||||
if args.since and r["ts"] < args.since:
|
||||
continue
|
||||
if args.until and r["ts"] > args.until:
|
||||
continue
|
||||
if r.get("status") == 200:
|
||||
rows.append(r)
|
||||
|
||||
vals = sorted(r["ms"] for r in rows)
|
||||
n = len(vals)
|
||||
p95 = percentile(vals, 95)
|
||||
out = {
|
||||
"측정구간": "서버 요청 수신 → 응답 완료 (HTTP 미들웨어 계측)",
|
||||
"표본": {"log": args.log, "since": args.since, "until": args.until, "n": n},
|
||||
"ms": {
|
||||
"p50": percentile(vals, 50), "p95": p95, "p99": percentile(vals, 99),
|
||||
"min": round(vals[0], 2) if vals else None,
|
||||
"max": round(vals[-1], 2) if vals else None,
|
||||
"mean": round(sum(vals) / n, 2) if n else None,
|
||||
},
|
||||
"target_ms": args.target,
|
||||
"판정기준": "p95 ≤ 목표",
|
||||
"verdict": "PASS" if (p95 is not None and p95 <= args.target) else "FAIL",
|
||||
}
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑥ 답변속도 — 정식 부하 측정 (표준 라이브러리만, 기존 04 bench 방식 계승).
|
||||
|
||||
측정 구간: 답변 생성 엔진 요청 수신 → 응답 완료 (HTTP 왕복, localhost)
|
||||
측정 경로: --profile heavy = 가격협상 진입 (Q-Table 카드 선택 경로, 기본)
|
||||
--profile light = 고정 스크립트 스텝(시작)
|
||||
부하 형태: 동시 사용자(--vus) × 총 요청(--n), 웜업(--warmup) 제외 후 집계
|
||||
|
||||
사용: python bench.py [--n 1000] [--warmup 50] [--vus 10] [--target 600]
|
||||
출력: result_bench_<profile>.json (p50/p95/p99, 판정) + detail_bench_<profile>.jsonl
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
HEAVY = {"rq_type": "재협상", "session_id": "BENCH", "step": "가격협상_확인", "index": 5,
|
||||
"user_input": "예", "item_price": 163600, "revenue": 163600, "dist": "R",
|
||||
"partners_yn": "없음", "partners": 0, "anchor": 8099, "target": 8180,
|
||||
"initial": 9000, "input": 9000, "iteration": 0, "is_new_quote": True,
|
||||
"profiling": False}
|
||||
LIGHT = {"rq_type": "재협상", "session_id": "BENCH", "step": "시작", "index": 0,
|
||||
"profiling": False}
|
||||
|
||||
|
||||
def once(url: str, body: bytes) -> float:
|
||||
t0 = time.perf_counter()
|
||||
req = urllib.request.Request(url, body, {"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
r.read()
|
||||
return (time.perf_counter() - t0) * 1000
|
||||
|
||||
|
||||
def percentile(vals, p):
|
||||
if not vals:
|
||||
return None
|
||||
k = (len(vals) - 1) * p / 100
|
||||
lo, hi = int(k), min(int(k) + 1, len(vals) - 1)
|
||||
return round(vals[lo] + (vals[hi] - vals[lo]) * (k - lo), 2)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--url", default="http://127.0.0.1:53117/v1/nego/chat")
|
||||
ap.add_argument("--n", type=int, default=1000)
|
||||
ap.add_argument("--warmup", type=int, default=50)
|
||||
ap.add_argument("--vus", type=int, default=10, help="동시 사용자 수")
|
||||
ap.add_argument("--profile", default="heavy", choices=["heavy", "light"])
|
||||
ap.add_argument("--target", type=float, default=600.0)
|
||||
args = ap.parse_args()
|
||||
|
||||
body = json.dumps(HEAVY if args.profile == "heavy" else LIGHT).encode()
|
||||
|
||||
# 웜업 (집계 제외)
|
||||
for _ in range(args.warmup):
|
||||
once(args.url, body)
|
||||
|
||||
t_start = time.perf_counter()
|
||||
with ThreadPoolExecutor(max_workers=args.vus) as ex:
|
||||
samples = list(ex.map(lambda _: once(args.url, body), range(args.n)))
|
||||
wall = time.perf_counter() - t_start
|
||||
|
||||
with open(HERE / f"detail_bench_{args.profile}.jsonl", "w", encoding="utf-8") as f:
|
||||
for ms in samples:
|
||||
f.write(json.dumps({"ms": round(ms, 3)}) + "\n")
|
||||
|
||||
vals = sorted(samples)
|
||||
p95 = percentile(vals, 95)
|
||||
out = {
|
||||
"측정구간": "요청 수신 → 응답 완료 (HTTP 왕복, localhost)",
|
||||
"부하": {"profile": args.profile, "n": args.n, "warmup_제외": args.warmup,
|
||||
"동시사용자": args.vus, "총소요_초": round(wall, 2),
|
||||
"처리율_req_s": round(args.n / wall, 1)},
|
||||
"ms": {"p50": percentile(vals, 50), "p95": p95, "p99": percentile(vals, 99),
|
||||
"min": round(vals[0], 2), "max": round(vals[-1], 2),
|
||||
"mean": round(sum(vals) / len(vals), 2)},
|
||||
"target_ms": args.target,
|
||||
"판정기준": "p95 ≤ 목표",
|
||||
"verdict": "PASS" if p95 is not None and p95 <= args.target else "FAIL",
|
||||
}
|
||||
(HERE / f"result_bench_{args.profile}.json").write_text(
|
||||
json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑦ 협상 데이터 수집 — 서버 계약 데이터화(contracts.jsonl) 집계기.
|
||||
|
||||
계획서: "협상 챗봇으로 이루어진 계약 데이터화" — 목표 10,000건/년.
|
||||
|
||||
집계 관점 2가지를 병기한다:
|
||||
1. 누적 수집: 측정 구간의 계약 레코드 건수 + 구간 일수 기준 연환산
|
||||
2. 처리량(capacity): 실측 처리 속도 기준 연간 처리 가능 건수
|
||||
(데모 환경은 운용 트래픽이 없으므로, 파이프라인의 수집 능력을 실증하는 관점)
|
||||
|
||||
사용:
|
||||
python aggregate.py # 전체 로그
|
||||
python aggregate.py --since 2026-08-29 # 특정 시점 이후
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
DEFAULT_LOG = HERE.parent.parent / "server" / "data" / "contracts.jsonl"
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--log", default=str(DEFAULT_LOG))
|
||||
ap.add_argument("--since", default=None)
|
||||
ap.add_argument("--until", default=None)
|
||||
ap.add_argument("--target", type=float, default=10000.0, help="목표 건/년")
|
||||
args = ap.parse_args()
|
||||
|
||||
rows = []
|
||||
for line in Path(args.log).read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
r = json.loads(line)
|
||||
if args.since and r["ts"] < args.since:
|
||||
continue
|
||||
if args.until and r["ts"] > args.until:
|
||||
continue
|
||||
rows.append(r)
|
||||
|
||||
n = len(rows)
|
||||
out = {"측정대상": "협상 챗봇 계약 데이터화 레코드 (서버 contracts.jsonl)",
|
||||
"표본": {"log": args.log, "since": args.since, "until": args.until, "n": n}}
|
||||
|
||||
if n >= 2:
|
||||
ts = sorted(datetime.fromisoformat(r["ts"]) for r in rows)
|
||||
span_sec = max((ts[-1] - ts[0]).total_seconds(), 1.0)
|
||||
span_days = span_sec / 86400
|
||||
# 1) 누적 관점: 구간 연환산
|
||||
out["누적수집"] = {
|
||||
"건수": n, "구간_일수": round(span_days, 4),
|
||||
"연환산_건": round(n / span_days * 365) if span_days > 0 else None,
|
||||
}
|
||||
# 2) 처리량 관점: 계약 1건당 평균 간격 → 연간 처리 가능량
|
||||
out["처리량"] = {
|
||||
"건당_평균간격_초": round(span_sec / (n - 1), 3),
|
||||
"연간_처리가능_건": round((n - 1) / span_sec * 86400 * 365),
|
||||
}
|
||||
rq = {}
|
||||
red = [r["reduction_pct"] for r in rows if r.get("reduction_pct") is not None]
|
||||
for r in rows:
|
||||
rq[r.get("rq_type")] = rq.get(r.get("rq_type"), 0) + 1
|
||||
out["구성"] = {"rq_type": rq,
|
||||
"평균_감액률_pct": round(sum(red) / len(red), 3) if red else None}
|
||||
|
||||
out["target_per_year"] = args.target
|
||||
out["판정기준"] = "연간 수집(또는 처리 가능) 건수 ≥ 목표 — 표본 100건 미만은 판정 보류"
|
||||
yearly = (out.get("누적수집") or {}).get("연환산_건")
|
||||
if n < 100:
|
||||
out["verdict"] = "판정보류(표본 부족)"
|
||||
else:
|
||||
out["verdict"] = "PASS" if (yearly is not None and yearly >= args.target) else "FAIL"
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑥ 자립형 스냅샷 수집기 — prism 서비스 없이 검색+AI 매칭을 직접 실행.
|
||||
|
||||
측정 코어는 prism_core/ (PRISM backend 발췌본 — 출처: prism_core/PROVENANCE.md).
|
||||
prism 저장소·DB·큐·브라우저 인프라에 종속되지 않는다.
|
||||
|
||||
검색 범위: 무차단 HTTP 몰 (danawa·enuri·gsshop — 카탈로그형이라 실질 종합 소스).
|
||||
브라우저 5몰(naver·coupang·gmarket·auction·st11) 포함 측정은 PRISM 서비스 기동 후
|
||||
capture_snapshots.py 를 사용한다.
|
||||
|
||||
필요: OPENAI_API_KEY (../.env 자동 로드 — AI 동일상품 판정), 인터넷.
|
||||
사용: python capture_local.py [--golden data/golden.json] [--out data/snapshots]
|
||||
[--sources danawa,enuri,gsshop] [--limit N]
|
||||
출력: <out>/<product_code>.json — run.py 가 재생하는 몰별 가격표 스냅샷 (PRISM 응답과 동일 골격)
|
||||
"""
|
||||
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))
|
||||
|
||||
# OPENAI_API_KEY: 환경변수 → server/config.toml 순 (NEGO_AGENT 공통 규약)
|
||||
_server_config = HERE.parent.parent / "server" / "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 prism_core.contract import AdapterError # noqa: E402
|
||||
from prism_core.core import apply_filters # noqa: E402
|
||||
from prism_core.danawa import DanawaAdapter # noqa: E402
|
||||
from prism_core.enuri import EnuriAdapter # noqa: E402
|
||||
from prism_core.enums import SourceState # noqa: E402
|
||||
from prism_core.gsshop import GsshopAdapter # noqa: E402
|
||||
from prism_core.identity import same_group # noqa: E402
|
||||
from prism_core.identity import veto as identity_veto # noqa: E402
|
||||
from prism_core.similarity import SimilarityJudge # noqa: E402
|
||||
from 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}
|
||||
|
||||
|
||||
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) -> list:
|
||||
"""검색어 재정제 라운드 (룰 기반) — 원본 PRISM의 '원본 → 정밀 → 광역' 설계 계승.
|
||||
|
||||
긴 조달형 품명은 몰 검색에서 0건이 나기 쉽다. 0매칭이면 순서대로 재시도:
|
||||
1) 원본 그대로
|
||||
2) 부연(괄호·슬래시)·수식어(불용어) 제거 전체
|
||||
3) 브랜드(첫 토큰) + 모델(숫자 포함 토큰) — 모델 일치 우선
|
||||
4) 브랜드 + 핵심명사(마지막 명사 토큰)
|
||||
5) 앞 2토큰 (광역)
|
||||
"""
|
||||
import re as _re
|
||||
|
||||
from 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))
|
||||
model_toks = [t for t in toks if _re.search(r"\d", t)]
|
||||
nouns = [t for t in toks if t not in model_toks]
|
||||
if nouns and model_toks:
|
||||
add(" ".join([nouns[0]] + model_toks))
|
||||
if len(nouns) >= 2:
|
||||
add(" ".join([nouns[0], nouns[-1]] + model_toks))
|
||||
if len(toks) > 2:
|
||||
add(" ".join(toks[:2]))
|
||||
return queries[:5]
|
||||
|
||||
|
||||
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):
|
||||
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 capture(g: dict, sources: list[str], judge: SimilarityJudge,
|
||||
keyword_gen=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)
|
||||
# 식별 게이트 기준 텍스트 — LocalJudge.target_text 와 동일 조합
|
||||
target_text = " ".join(str(payload.get(k) or "") for k in
|
||||
("company", "product_name", "model", "specification"))
|
||||
|
||||
# 재정제 라운드: 게이트 통과 매칭이 나올 때까지 좁은 검색어 → 넓은 검색어 순으로 시도
|
||||
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)
|
||||
judgments = await judge.judge(payload, kept) if kept else []
|
||||
|
||||
# 식별 게이트: AI 수락 + 결정적 veto 없음 — AI 는 판별, 존재 검증은 코드가 한다.
|
||||
# 이전엔 min(price)만 봐서 점수 90 저가 오탐이 점수 100 정답을 밀어냈다(회귀 8건).
|
||||
gated = []
|
||||
pool_log = []
|
||||
for p, j in zip(kept, judgments):
|
||||
reasons = identity_veto(target_text, p.name)
|
||||
accepted = j.is_match and not reasons
|
||||
pool_log.append({"source": p.source, "name": p.name, "price": p.price,
|
||||
"ai_match": j.is_match, "ai_score": j.score,
|
||||
"veto": reasons, "accepted": accepted})
|
||||
if accepted:
|
||||
gated.append((p, j))
|
||||
|
||||
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))
|
||||
else:
|
||||
row_state = SourceState.NO_MATCH if items else state
|
||||
price = name = url = ship = score = 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})
|
||||
|
||||
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,
|
||||
# 오프라인 백테스트용 후보 전량 (이름·가격·AI점수·veto 사유·수락 여부) —
|
||||
# 이게 없으면 게이트 튜닝 1회당 100품목 재크롤링이 필요하다.
|
||||
"pool": pool_log,
|
||||
# 기권 사유: AI 는 매칭했지만 식별 게이트가 전부 기각 — 오탐 채택보다 정직한 상태
|
||||
"abstain_reason": ("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(HERE / "data" / "golden.json"))
|
||||
ap.add_argument("--out", default=str(HERE / "data" / "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("--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 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 prism_core.keyword import KeywordGenerator
|
||||
keyword_gen = KeywordGenerator(api_key=os.environ["OPENAI_API_KEY"])
|
||||
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)
|
||||
(out_dir / f"{g['product_code']}.json").write_text(
|
||||
json.dumps(snap, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(f" → 후보 {snap['candidates']} / AI매칭 {snap['ai_matched']} / "
|
||||
f"최저 {snap['lowest_price']}({snap['lowest_source']}) / partial={snap['partial']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑧ 골든셋 수집기 — 타겟 몰(danawa)에서 실재 상품명을 수집한다.
|
||||
|
||||
설계 (2026-08-29 확정):
|
||||
- 골든셋은 협상 테스트 데이터(testdata/)와 **분리**된 ⑧ 전용 데이터로 구축한다.
|
||||
- 타겟 몰(카탈로그형 danawa)에서 카테고리 키워드 검색으로 **실재가 확인된 상품명**만
|
||||
수집 → "3몰에 상품이 없어서 실패"(원인 조사에서 미확보의 ~60%)를 골든셋에서 제거.
|
||||
- 측정 의미: 실재 보장 상품에 대해 시스템이 목표 상품을 반환하는 비율 = 검색 정확도.
|
||||
|
||||
카테고리: 기업 구매(MRO)·사무·생활 소모품 위주 — 과제 도메인(B2B 물품 협상)과 정합.
|
||||
|
||||
사용: python harvest_names.py [--per-keyword 5] [--seed 829]
|
||||
출력: data/골든수집_danawa.json — [{"keyword", "name", "price"}]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
|
||||
from prism_core.danawa import DanawaAdapter # noqa: E402
|
||||
|
||||
# 기업 구매(MRO)·사무·생활 소모품 카테고리 키워드
|
||||
KEYWORDS = [
|
||||
"무선마우스", "기계식키보드", "모니터 27인치", "노트북 거치대", "USB 허브",
|
||||
"A4 복사용지", "토너 카트리지", "라벨 프린터", "문서 세단기", "화이트보드",
|
||||
"멀티탭 6구", "LED 전구", "케이블타이", "절연 테이프", "건전지 AA",
|
||||
"전동드릴", "드라이버 세트", "안전화", "안전모", "작업장갑",
|
||||
"분말 소화기", "화재 감지기", "구급함", "손소독제", "마스크 KF94",
|
||||
"공기청정기", "가습기", "선풍기", "전기포트", "커피믹스",
|
||||
"생수 2L", "물티슈", "종이컵", "쓰레기봉투", "세탁세제",
|
||||
"보조배터리", "블루투스 이어폰", "웹캠", "공유기", "외장하드",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--per-keyword", type=int, default=5, help="키워드당 수집 상품 수")
|
||||
ap.add_argument("--seed", type=int, default=829)
|
||||
args = ap.parse_args()
|
||||
|
||||
adapter = DanawaAdapter(use_proxy=False)
|
||||
rng = random.Random(args.seed)
|
||||
|
||||
harvested, seen = [], set()
|
||||
for i, kw in enumerate(KEYWORDS, 1):
|
||||
try:
|
||||
items = await adapter.search(kw)
|
||||
except Exception as e:
|
||||
print(f"[{i}/{len(KEYWORDS)}] {kw} — 오류: {e}")
|
||||
continue
|
||||
picked = 0
|
||||
for p in items:
|
||||
name = (p.name or "").strip()
|
||||
if not name or name in seen or len(name) < 5 or p.price is None:
|
||||
continue
|
||||
seen.add(name)
|
||||
harvested.append({"keyword": kw, "name": name, "price": p.price})
|
||||
picked += 1
|
||||
if picked >= args.per_keyword:
|
||||
break
|
||||
print(f"[{i}/{len(KEYWORDS)}] {kw} — 검색 {len(items)}건 중 {picked}건 수집")
|
||||
|
||||
rng.shuffle(harvested)
|
||||
out = {"source": "danawa 검색 실재 상품명 (타겟 몰 수집)", "수집일": time.strftime("%Y-%m-%d"),
|
||||
"keywords": KEYWORDS, "count": len(harvested), "items": harvested}
|
||||
(HERE / "data").mkdir(exist_ok=True)
|
||||
(HERE / "data" / "골든수집_danawa.json").write_text(
|
||||
json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(f"\n총 {len(harvested)}건 → data/골든수집_danawa.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑧ 골든셋 생성 — 실상품명 목록에서 검색 타겟을 뽑아 golden.json 을 만든다.
|
||||
|
||||
계획서: "평가를 위해 e-commerce 업체에서 실제 활용하는 1,000건의 데이터를 시험 데이터로 사용"
|
||||
→ 독립 프로젝트 원칙에 따라, 운용 견적명에서 분리·정제한 실상품명(testdata/product_names.json)을
|
||||
검색 타겟으로 사용한다 (가격·거래조건은 사용하지 않음 — 검색 정확도는 상품명만 필요).
|
||||
|
||||
주의: 이름이 지나치게 짧거나(≤4자) 사내 맥락 없이는 검색이 무의미한 이름(지역 표기 등)은
|
||||
웹 검색 타겟으로 부적합할 수 있어 최소 길이 필터를 둔다. 최종 골든셋은 파일럿 수집 후
|
||||
확보율을 보고 보강한다 (기존 과제 방식과 동일).
|
||||
|
||||
사용: python make_golden.py [--n 1000] [--seed 88] [--min-len 5]
|
||||
출력: data/golden.json — [{"product_code": "G-0001", "product_name": ...}]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
NAMES_PATH = HERE.parent.parent / "testdata" / "product_names.json"
|
||||
|
||||
# 주문 안내·옵션 문구 — 검색어를 오염시키므로 절단
|
||||
_NOISE_RE = re.compile(r"[_/]?\s*(배송\s*메모.*|색상\s*입력.*|옵션\s*[::].*|.*입력\s*필수.*)$")
|
||||
|
||||
|
||||
def clean_search_name(name: str) -> str:
|
||||
"""상품명에서 주문 안내 문구 제거 (예: 'P2V78A HP 746 300-ml_배송메모색상입력 필수')."""
|
||||
n = name.split("_")[0].strip() if "_" in name and len(name.split("_")[0].strip()) >= 5 \
|
||||
else name
|
||||
n = _NOISE_RE.sub("", n).strip()
|
||||
return re.sub(r"\s+", " ", n)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--n", type=int, default=1000)
|
||||
ap.add_argument("--seed", type=int, default=88)
|
||||
ap.add_argument("--min-len", type=int, default=5)
|
||||
args = ap.parse_args()
|
||||
|
||||
names = json.load(open(NAMES_PATH, encoding="utf-8"))["names"]
|
||||
names = [clean_search_name(n) for n in names]
|
||||
names = sorted({n for n in names if len(n) >= args.min_len})
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
rng.shuffle(names)
|
||||
picked = names[: args.n]
|
||||
if len(picked) < args.n:
|
||||
print(f"[주의] 가용 상품명 {len(picked)}건 < 요청 {args.n}건 — 전량 사용 (보강 필요)")
|
||||
|
||||
golden = [{"product_code": f"G-{i + 1:04d}", "product_name": name}
|
||||
for i, name in enumerate(picked)]
|
||||
|
||||
(HERE / "data").mkdir(exist_ok=True)
|
||||
out = HERE / "data" / "golden.json"
|
||||
out.write_text(json.dumps(golden, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(json.dumps({"골든셋": len(golden), "min_len": args.min_len, "seed": args.seed,
|
||||
"출력": str(out)}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑥ 검수 시트 생성기 — 스냅샷의 반환 상품을 사람 검수용 CSV로 정리 (표준 라이브러리만).
|
||||
|
||||
capture_local.py 가 만든 스냅샷에서 시스템 반환 상품(최저가 몰의 상품명·가격·URL)을 뽑아
|
||||
data/review.csv 초안을 만든다. 검수자는 '일치여부' 컬럼에 O(동일 상품)/X(다른 상품)만 기입.
|
||||
- 반환 실패(매칭 0건) 행은 '반환실패'로 자동 기입 — 검수 불필요, 집계 시 불일치 처리
|
||||
- 기존 review.csv 의 검수값(일치여부)은 보존하고 새 행만 추가한다
|
||||
사용: python make_review_sheet.py
|
||||
"""
|
||||
import argparse, csv, json
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
COLS = ["상품코드", "상품명", "검색어", "탐색한_상품명", "가격", "배송비", "URL", "AI유사도", "검색일시", "소요초", "일치여부"]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--golden", default=str(HERE / "data" / "golden_100.json"))
|
||||
ap.add_argument("--snapshots", default=str(HERE / "data" / "snapshots"))
|
||||
ap.add_argument("--out", default=str(HERE / "data" / "review_100.csv"))
|
||||
args = ap.parse_args()
|
||||
golden = json.loads(Path(args.golden).read_text(encoding="utf-8"))
|
||||
dst = Path(args.out)
|
||||
existing = {}
|
||||
if dst.exists():
|
||||
with open(dst, encoding="utf-8-sig") as f:
|
||||
existing = {r["상품코드"]: r for r in csv.DictReader(f)}
|
||||
|
||||
rows, n_fail, n_nosnap = [], 0, 0
|
||||
for g in golden:
|
||||
code = g["product_code"]
|
||||
row = {"상품코드": code, "상품명": g.get("product_name", "")}
|
||||
snap_p = Path(args.snapshots) / f"{code}.json"
|
||||
if not snap_p.exists():
|
||||
n_nosnap += 1
|
||||
row.update({"검색어": "", "탐색한_상품명": "", "가격": "", "배송비": "", "URL": "",
|
||||
"AI유사도": "", "검색일시": "", "소요초": "", "일치여부": ""})
|
||||
else:
|
||||
snap = json.loads(snap_p.read_text(encoding="utf-8"))
|
||||
best = next((m for m in snap.get("malls", [])
|
||||
if m.get("source") == snap.get("lowest_source")), None)
|
||||
common = {"검색어": snap.get("query", ""), "검색일시": snap.get("triggered_at", ""),
|
||||
"소요초": snap.get("elapsed_sec", "")}
|
||||
if snap.get("lowest_price") is None or best is None:
|
||||
n_fail += 1
|
||||
row.update({**common, "탐색한_상품명": "", "가격": "", "배송비": "", "URL": "",
|
||||
"AI유사도": "", "일치여부": "반환실패"})
|
||||
else:
|
||||
row.update({**common, "탐색한_상품명": best.get("name", ""),
|
||||
"가격": best.get("price", ""),
|
||||
"배송비": best.get("shipping_fee", "") if best.get("shipping_fee") is not None else "",
|
||||
"URL": best.get("detail_url", "") or "",
|
||||
"AI유사도": best.get("ai_score", "") if best.get("ai_score") is not None else "",
|
||||
"일치여부": ""})
|
||||
prev = existing.get(code, {}).get("일치여부", "").strip()
|
||||
if prev and row["일치여부"] == "":
|
||||
row["일치여부"] = prev # 기존 검수값 보존
|
||||
rows.append(row)
|
||||
|
||||
with open(dst, "w", encoding="utf-8-sig", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=COLS)
|
||||
w.writeheader()
|
||||
w.writerows(rows)
|
||||
reviewed = sum(1 for r in rows if r["일치여부"] in ("O", "X", "o", "x"))
|
||||
print(f"review.csv: {len(rows)}행 (반환실패 {n_fail} · 스냅샷없음 {n_nosnap} · 기검수 {reviewed})")
|
||||
print(f"→ '일치여부' 빈 칸에 O(동일 상품)/X(다른 상품) 기입 후 python run.py")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
# prism_core 출처
|
||||
|
||||
- 원본: gitea.o2o.kr/Negosium/prism backend @ d2a27c3 (2026-08-27 발췌)
|
||||
- 발췌 범위: HTTP 몰 검색 어댑터(danawa·enuri·gsshop) + 파이프라인(필터·이상치) + AI 동일상품 판정
|
||||
- 서비스 의존성(DB·큐·프록시·설정 시스템)은 shims.py 로 대체 — prism 저장소 없이 자립 실행
|
||||
- 임포트 경로만 치환, 로직 무수정
|
||||
@@ -0,0 +1,5 @@
|
||||
"""prism_core — PRISM(gitea.o2o.kr/Negosium/prism)에서 발췌한 최저가 검색 측정 코어.
|
||||
|
||||
HTTP 몰 검색(danawa·enuri·gsshop) + 필터/이상치 파이프라인 + AI 동일상품 판정.
|
||||
서비스 의존성(DB·큐·프록시·설정)은 shims.py 로 대체 — 출처·범위는 PROVENANCE.md 참조.
|
||||
"""
|
||||
@@ -0,0 +1,185 @@
|
||||
"""몰 도메인 공통 계약 — 검색 카드 출력과 상품 상세(URL 해석) 출력.
|
||||
|
||||
크롤링/검색 소스(네이버·쿠팡 …)는 각자 수집 방식과 안티봇 대응을 캡슐화하고,
|
||||
코어 파이프라인(필터·이상치·AI)은 정규화된 NormalizedProduct 만 본다.
|
||||
새 소스는 SearchAdapter 를 구현하기만 하면 코어 변경 없이 붙는다(트레드밀 격리).
|
||||
|
||||
URL 해석 쪽 계약(ResolveOutcome·ResolvedProduct)도 여기 있다 — 같은 몰의 두 출력이라서다.
|
||||
ResolvedProduct 는 라우터 응답(protocol.Res_ResolveUrl)에도 **그대로** 실린다 — 같은 모양을
|
||||
protocol 에 한 벌 더 정의하면 필드 추가 때마다 두 곳이 어긋난다.
|
||||
"""
|
||||
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from enum import StrEnum
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prism_core.enums import SourceState
|
||||
|
||||
|
||||
class NormalizedProduct(BaseModel):
|
||||
"""소스 무관 정규화 상품 스키마. 어댑터의 유일한 출력 계약."""
|
||||
|
||||
source: str = Field(description="수집 소스 (naver|coupang)")
|
||||
name: str = Field(description="상품명")
|
||||
price: int = Field(description="판매가(원, 정수). 파싱 실패분은 어댑터에서 제외")
|
||||
# ⚠️ 두 필드는 현재 **어떤 어댑터도 채우지 않는다**(검색 카드에는 없는 정보다).
|
||||
# 상세 페이지를 읽는 URL 해석(malls 의 PDP 파서)이 같은 정보를 ResolvedProduct 로 다루므로,
|
||||
# 언젠가 채우려거든 그쪽 파서를 재사용할 것. 지우지 않는 이유: 계약에서 필드를 빼면
|
||||
# 이미 저장된 job.result(JSONB)와 모양이 어긋난다.
|
||||
model: Optional[str] = Field(None, description="모델명(있으면). 현재 미수집 — 위 주석 참고")
|
||||
manufacturer: Optional[str] = Field(None, description="제조사(있으면). 현재 미수집 — 위 주석 참고")
|
||||
image_url: Optional[str] = Field(None, description="썸네일 URL")
|
||||
detail_url: Optional[str] = Field(None, description="상품 상세 URL")
|
||||
shipping_fee: Optional[int] = Field(None, description="배송비(원). 무료=0, 미확인=None")
|
||||
shipping_type: Optional[str] = Field(None, description="배송 유형: free(명시 무료)|paid(유료)|rocket(로켓배송, 조건부 무료)|rocket_merchant(판매자로켓)|None(미확인). 네이버는 lprice 가 배송비 제외 상품가라 항상 None")
|
||||
mall_name: Optional[str] = Field(None, description="판매몰/스토어명. None 이면 판매처를 모른다 — "
|
||||
"seller_count 가 있으면 '사이트가 안 알려줌'(가격비교), "
|
||||
"없으면 '우리가 못 읽음'(파싱 실패)")
|
||||
# 가격비교(카탈로그) 카드의 판매처 수. 네이버는 "최저 7,790원 · 판매처 239" 처럼
|
||||
# **값만 주고 주인을 안 알려준다.** 그 값의 주인이 G마켓·11번가일 수도 있어(실측),
|
||||
# 'naver' 라는 가게에서 파는 값이 아니다. 화면이 "239곳 중 최저"라고 말할 수 있게 남긴다.
|
||||
seller_count: Optional[int] = Field(None, description="가격비교 판매처 수. None=단일 판매처 또는 미상")
|
||||
# 배송 원문 표기. 금액만으로는 의미가 불완전하다 — 같은 '무료배송'이라도 주체(쿠팡 로켓/판매자)와
|
||||
# 조건(와우회원·최소금액·새벽배송)이 다르고, 배송 주체가 바뀌면 금액 비교 자체가 무의미해진다.
|
||||
# 그래서 숫자(shipping_fee)·분류(shipping_type)와 별개로 **화면 문구를 그대로** 남긴다.
|
||||
shipping_label: Optional[str] = Field(None, description="배송 표기 원문(예: '무료배송 ∙ 무료반품 ∙ 새벽도착', '배송비3,000원 · 내일배송 8.6.(목) 도착')")
|
||||
# ── 해외직구 landed-cost(총 도착가) ─────────────────────────────────
|
||||
# 해외몰(아마존·알리)은 상품가만으론 비교가 안 된다 — 관세·배송비·배송기간이 총비용을 가른다.
|
||||
# 이 값들은 검색 카드가 아니라 **상세페이지**에 있어, 매칭된 대표 상품 1개만 후보강해 채운다.
|
||||
# 국내몰은 전부 None(해당 없음). shipping_fee/label 은 국내와 공유한다.
|
||||
#
|
||||
# ⚠️ import_fee 의 0 과 None 은 **다른 사실**이다(이 프로젝트의 '없음'≠'못 봄'):
|
||||
# 0 = 몰이 '수입 요금 없음'을 명시(아마존 면세, ₩ 소액면세 한도 아래). 관세가 정말 0.
|
||||
# None = 관세를 **모른다**. 알리는 PDP 에 관세를 안 띄운다(체크아웃까지 안 보임) → 지어내지 않는다.
|
||||
# 따라서 총 도착가를 0 으로 단정하면 안 되고, None 이면 '관세 별도 가능'으로 표시해야 한다.
|
||||
import_fee: Optional[int] = Field(None, description="관세·수입비(원). 0=명시적 면세, None=미표시/모름")
|
||||
import_fee_label: Optional[str] = Field(None, description="관세 표기 원문(예: '₩234,310 Import Charges', '수입 요금 없음'). None=표기 없음")
|
||||
# 발송지 — '한국 발송'이면 관세·배송기간이 국내 수준이고, '중국/해외 발송'이면 다르다.
|
||||
# 배송**대상**국(ship-to)은 상품이 아니라 요청 설정이다(나중에 변경 가능). 여기엔 발송**출발**지만 담는다.
|
||||
ship_from: Optional[str] = Field(None, description="발송지 원문(예: '대한민국 배송', '한국 발송', '중국/해외 발송'). None=미확인")
|
||||
# 배송 소요. 원문 라벨(표시용)과 파싱된 최대 예상일(정렬·비교용)을 분리한다 — shipping 3종과 같은 패턴.
|
||||
delivery_label: Optional[str] = Field(None, description="배송 예정 원문(예: '8월 25일-30일 도착', '무료 8/31-9/7 · 신속 8/24-27'). None=미확인")
|
||||
delivery_days: Optional[int] = Field(None, description="예상 배송 최대일(정수, 오늘 기준). 파싱 실패=None(0 아님)")
|
||||
external_id: Optional[str] = Field(None, description="소스 내 상품 식별자")
|
||||
# ── 신뢰 신호 ──────────────────────────────────────────────────────
|
||||
# 최저가는 '가장 싼 값'이 아니라 '실제로 살 수 있는 가장 싼 값'이어야 한다. 리뷰·평점이
|
||||
# 전혀 없는 오퍼는 재고 없는 미끼가격일 수 있어, 그걸 최저가로 보고하면 사용자는 그 가격에
|
||||
# 살 수 없다. 두 소스 모두 카드에 노출하는 값만 담는다(교차 비교가 되어야 하므로).
|
||||
rating: Optional[float] = Field(None, description="평점(5점 만점). 없으면 None=신규/미검증 오퍼 신호")
|
||||
review_count: Optional[int] = Field(None, description="리뷰 수. 0/None 이면 거래 이력이 없다는 뜻")
|
||||
|
||||
|
||||
class AdapterHealth(BaseModel):
|
||||
"""어댑터 건강도. 성공률 급락 = 레이아웃 변경/차단 신호 → 알림 훅."""
|
||||
|
||||
source: str
|
||||
ok: bool = Field(description="현재 정상 동작 여부")
|
||||
recent_success_rate: float = Field(0.0, description="최근 요청 성공률(0~1)")
|
||||
blocked_rate: float = Field(0.0, description="최근 차단(봇탐지) 비율(0~1)")
|
||||
note: str = ""
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
"""어댑터 수집 실패. blocked=True 면 안티봇 차단으로 판단(에스컬레이션/알림 트리거).
|
||||
|
||||
fatal=True 는 **재시도해도 절대 안 되는 차단**이다 — IP 를 바꿔도 같은 결과가 나오는
|
||||
구조적 원인(예: 네이버 msearch 에 해외 IP 로 접근 = 게이트웨이 설정이 틀림).
|
||||
호출부는 회전·재시도를 멈추고 설정을 고쳐야 한다.
|
||||
|
||||
⚠️ `state` 는 **'그 몰을 봤는가'** 를 담는다. blocked/fatal 은 '어떻게 대응할까'(회전·재시도)를
|
||||
위한 값이고, state 는 '사용자에게 뭐라고 말할까'를 위한 값이라 쓰임이 다르다.
|
||||
특히 blocked=False 하나에 두 가지가 섞여 있어 state 없이는 갈라낼 수 없다:
|
||||
결과 0건(EMPTY) 그 몰을 봤고 정말 없었다 → "없음"이라 말해도 된다
|
||||
전송 실패(UNAVAILABLE) 그 몰을 못 봤다 → "없음"이라 말하면 거짓
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, source: str, blocked: bool = False, fatal: bool = False,
|
||||
state: SourceState | None = None):
|
||||
super().__init__(message)
|
||||
self.source = source
|
||||
self.blocked = blocked
|
||||
self.fatal = fatal
|
||||
# state 를 안 준 옛 호출부도 맞게 동작하도록 blocked/fatal 에서 유도한다.
|
||||
# (모르면 UNAVAILABLE — '못 봤다' 쪽이 안전한 기본값이다. EMPTY 로 잘못 넘기면
|
||||
# 확인도 안 한 몰을 '없음'으로 단정하게 된다)
|
||||
self.state = state or (SourceState.ENV_BLOCKED if fatal else
|
||||
SourceState.BLOCKED if blocked else SourceState.UNAVAILABLE)
|
||||
|
||||
|
||||
class ResolveOutcome(StrEnum):
|
||||
"""URL 해석 결과 상태. '왜 못 읽었나'가 서로 다른 사실이므로 하나로 뭉개지 않는다 —
|
||||
상태마다 사용자가 다음에 할 일이 다르다(상품명 입력 / 지원 목록 확인 / 재시도)."""
|
||||
|
||||
RESOLVED = "resolved" # 읽었다 — product 가 채워져 있다
|
||||
NEEDS_INFRA = "needs_infra" # 아는 사이트지만 차단 우회 인프라가 필요(쿠팡·네이버·G마켓·옥션)
|
||||
UNSUPPORTED = "unsupported" # 모르는 사이트
|
||||
INVALID_URL = "invalid_url" # URL 형태가 아님
|
||||
FETCH_FAILED = "fetch_failed" # 네트워크/타임아웃/비정상 응답
|
||||
BLOCKED = "blocked" # 무차단 등급 사이트가 차단 응답 — 등급 실측이 낡았다는 신호
|
||||
PARSE_FAILED = "parse_failed" # 페이지는 왔는데 상품 정보를 못 읽음(마크업 드리프트)
|
||||
|
||||
|
||||
class ResolvedProduct(BaseModel):
|
||||
"""상품 URL 에서 읽어낸 정보 — 검색 폼 5칸에 그대로 프리필된다.
|
||||
|
||||
여기서도 이 프로젝트의 규칙이 그대로 적용된다: **못 읽은 값은 비워 둔다.**
|
||||
가격을 못 읽었으면 None 이지 0 이 아니고, 제조사를 못 찾았으면 "" 이지 추측이 아니다 —
|
||||
여기서 지어낸 값은 그대로 검색어·필터 입력이 되어 5몰 전체를 오염시킨다.
|
||||
"""
|
||||
|
||||
product_name: str = Field("", description="상품명(카탈로그 정규화명 또는 판매자 작성명)")
|
||||
company: str = Field("", description="제조사/브랜드. 페이지가 명시한 경우만")
|
||||
model: str = Field("", description="모델명. 페이지가 명시한 경우만")
|
||||
specification: str = Field("", description="규격(다나와 spec_list 등). 없으면 빈 값")
|
||||
price: Optional[int] = Field(None, description="기준가(카탈로그 최저가/판매가). null=못 읽음(0원이 아니다)")
|
||||
image_url: Optional[str] = Field(None, description="대표 이미지")
|
||||
category: Optional[str] = Field(None, description="사이트의 분류 경로('휴대폰 > 스마트폰')")
|
||||
catalog_id: Optional[str] = Field(None, description="사이트의 영구 상품 ID(pcode/modelno/prdid/상품번호)")
|
||||
|
||||
|
||||
class SearchAdapter(ABC):
|
||||
"""검색 소스 어댑터. 소스별 수집/에스컬레이션/안티봇을 내부에 캡슐화한다."""
|
||||
|
||||
source: str
|
||||
|
||||
@abstractmethod
|
||||
async def search(self, query: str, limit: int = 40) -> list[NormalizedProduct]:
|
||||
"""query 로 검색해 정규화 상품 리스트를 반환. 차단 시 AdapterError(blocked=True)."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def enrich(self, product: NormalizedProduct) -> NormalizedProduct:
|
||||
"""몰별 **대표 상품 1개**에 부가 정보를 보강한다(검색 카드엔 없는 상세 정보).
|
||||
|
||||
해외몰(아마존·알리)의 landed-cost(배송비·관세·배송일·발송지)가 여기 채워진다 —
|
||||
상세페이지 fetch 1회가 붙으므로 매칭된 대표에만 부른다. 기본은 무변경(국내몰은 보강 없음).
|
||||
실패해도 원본을 그대로 반환한다 — 보강은 부가 정보라 검색을 깨지 않는다."""
|
||||
return product
|
||||
|
||||
async def health(self) -> AdapterHealth:
|
||||
"""기본 건강도. 어댑터가 관측 지표를 축적하면 override."""
|
||||
return AdapterHealth(source=self.source, ok=True)
|
||||
|
||||
# ---- 시간 윈도우 성공/실패 카운터(장기 실패 알림용) ------------------
|
||||
# 기존 _ok/_blocked 는 기동 후 누적이라 '최근 30분 성공 0건' 같은 장기 실패를 못 본다.
|
||||
# 어댑터의 search 성공/실패 지점에서 _note_result 를 부르면 ops-monitor 가 recent_stats 로 읽는다.
|
||||
# (lazy init — 서브클래스가 super().__init__ 을 부르지 않아도 동작)
|
||||
|
||||
def _note_result(self, ok: bool):
|
||||
ev = getattr(self, "_win_events", None)
|
||||
if ev is None:
|
||||
ev = self._win_events = deque(maxlen=512)
|
||||
ev.append((time.monotonic(), ok))
|
||||
|
||||
def recent_stats(self, window_sec: float = 1800.0) -> tuple[int, int]:
|
||||
"""최근 window_sec 내 (시도 수, 성공 수)."""
|
||||
now = time.monotonic()
|
||||
tries = ok = 0
|
||||
for t, s in getattr(self, "_win_events", ()):
|
||||
if now - t <= window_sec:
|
||||
tries += 1
|
||||
ok += s
|
||||
return tries, ok
|
||||
@@ -0,0 +1,157 @@
|
||||
"""최저가 코어 파이프라인.
|
||||
|
||||
검색 결과(NormalizedProduct[]) → 필터 → 이상치 제거 → 정렬 → top-N 최저가.
|
||||
각 STAGE 의 in/out 건수를 기록해 관측성을 확보한다(레퍼런스 pipeline_log 패턴 계승).
|
||||
|
||||
AI 유사도 판정(같은 상품인지)은 키 준비 시 이 사이(이상치 제거 뒤, top-N 앞)에 끼운다 —
|
||||
지금은 슬롯만 비워두고 규칙 매칭을 하지 않는다(고정 파서 취약성 회피).
|
||||
"""
|
||||
|
||||
from prism_core.contract import NormalizedProduct
|
||||
from prism_core.filters import keep_only_mall, filter_out_malls, filter_by_price_band, filter_brand_mismatch
|
||||
from prism_core.outliers import remove_price_outliers, iqr_band
|
||||
|
||||
# 분포 그래프용 상세를 남길 최대 표본 수. 넘으면 남기지 않는다(stages JSONB 비대 방지).
|
||||
# 실측 상한이 5몰×40건=200 이라 1000 이면 사실상 항상 남는다.
|
||||
_MAX_PLOT_POINTS = 1000
|
||||
# 제외된 항목만 상품명을 남긴다. '왜 잘렸나'를 되짚는 건 제외된 쪽이고,
|
||||
# 후보의 정체는 mall_candidate 에 이미 저장된다 — 통과분뿐 아니라 **AI 탈락분과 점수까지**
|
||||
# 남기므로(2026-08-11) 여기서 또 담을 필요가 없다.
|
||||
_REMOVED_NAME_LEN = 60
|
||||
|
||||
|
||||
def _distribution(kept: list[NormalizedProduct], removed: list[NormalizedProduct]) -> dict | None:
|
||||
"""이상치 단계의 분포 상세 — 화면이 박스플롯+점 그래프를 그릴 재료.
|
||||
|
||||
건수만 남기면(`{"in":138,"out":10}`) **무엇이 왜 잘렸는지 되짚을 수 없다.**
|
||||
`mall_candidate` 에 매칭 후보를 전량 남기기로 한 것과 같은 이유다(요구사항 5절):
|
||||
잘라낸 근거를 못 보면 오매칭·과잉필터의 원인을 추적할 수 없다.
|
||||
|
||||
담는 것:
|
||||
band 판정 기준(사분위·상하한·바닥 적용 여부) — 그래프의 상자와 밴드 선
|
||||
points 전 표본의 (가격, 소스, 유지여부) — 스트립 플롯의 점
|
||||
제외된 점에만 상품명을 붙인다(호버로 '왜 잘렸나'를 보는 쪽이라서)
|
||||
"""
|
||||
prices = [p.price for p in kept + removed if p.price and p.price > 0]
|
||||
if len(prices) > _MAX_PLOT_POINTS or len(prices) < 4:
|
||||
return None
|
||||
|
||||
band = iqr_band(prices)
|
||||
pts = [{"price": p.price, "source": p.source, "kept": True} for p in kept if p.price]
|
||||
pts += [{
|
||||
"price": p.price, "source": p.source, "kept": False,
|
||||
"name": (p.name or "")[:_REMOVED_NAME_LEN],
|
||||
# 밴드의 어느 쪽으로 벗어났는지. **저가쪽이 오매칭 방어의 본체**라
|
||||
# 화면에서 색을 갈라야 한다(비싼 묶음상품이 잘린 건 최저가에 무해하다).
|
||||
"side": "low" if p.price < band["lo"] else "high",
|
||||
} for p in removed if p.price]
|
||||
return {"band": band, "points": sorted(pts, key=lambda x: x["price"])}
|
||||
|
||||
|
||||
def apply_filters(
|
||||
products: list[NormalizedProduct],
|
||||
*,
|
||||
base_price: int | None = None,
|
||||
company: str | None = None,
|
||||
keep_mall: str | None = None,
|
||||
banned_malls=(),
|
||||
band_tolerance: float = 0.7,
|
||||
remove_outliers: bool = True,
|
||||
) -> tuple[list[NormalizedProduct], list[dict]]:
|
||||
"""mall → 브랜드 → 가격밴드 → 이상치(IQR) 순으로 후보를 좁힌다. (후보, STAGE로그) 반환.
|
||||
AI 유사도 판정은 이 뒤(top-N 앞)에 결합한다."""
|
||||
stages: list[dict] = []
|
||||
cur = list(products)
|
||||
|
||||
def stage(name: str, before: list, after: list):
|
||||
stages.append({"stage": name, "in": len(before), "out": len(after)})
|
||||
|
||||
if keep_mall:
|
||||
before = cur
|
||||
cur = keep_only_mall(cur, keep_mall)
|
||||
stage("keep_mall", before, cur)
|
||||
elif banned_malls:
|
||||
before = cur
|
||||
cur = filter_out_malls(cur, banned_malls)
|
||||
stage("filter_out_malls", before, cur)
|
||||
|
||||
# 브랜드는 규칙으로 확실히 판정되는 축이라 AI 앞에서 먼저 좁힌다 —
|
||||
# AI 가 걸러야 할 양이 적을수록 오탐이 줄고, 오탐 1건이 최저가를 오염시키는 경로가 막힌다.
|
||||
if company:
|
||||
before = cur
|
||||
cur = filter_brand_mismatch(cur, company)
|
||||
stage("brand", before, cur)
|
||||
|
||||
if base_price:
|
||||
before = cur
|
||||
cur = filter_by_price_band(cur, base_price, band_tolerance)
|
||||
stage("price_band", before, cur)
|
||||
|
||||
if remove_outliers:
|
||||
before = cur
|
||||
cur, dropped = remove_price_outliers(cur)
|
||||
stage("outlier", before, cur)
|
||||
# 제거된 항목을 그냥 버리면 화면이 '이상치 제거'를 숫자 두 개로만 보게 된다.
|
||||
# 분포 상세를 이 단계에 붙여 둔다(handler 가 search_run.stages 로 그대로 적재).
|
||||
dist = _distribution(cur, dropped)
|
||||
if dist:
|
||||
stages[-1].update(dist)
|
||||
|
||||
return cur, stages
|
||||
|
||||
|
||||
def group_by_source(products: list[NormalizedProduct]) -> dict[str, list[NormalizedProduct]]:
|
||||
"""매칭 후보를 **소스별로** 가른다(각 리스트는 가격 오름차순).
|
||||
|
||||
선행 프로젝트에는 이 자리에 summarize_by_mall 이 있었다 — 몰명(canonical)으로 dedup 해서
|
||||
'같은 몰이 네이버 노출과 직접 크롤 양쪽에서 오면 1건으로 병합'했다. 최저가 1개가 답이라
|
||||
같은 몰이 두 줄로 보이면 안 됐기 때문이다.
|
||||
|
||||
PRISM 은 반대다. **네이버에서 본 G마켓 가격과 G마켓에서 직접 본 가격은 서로 다른 사실**이고,
|
||||
둘 다 답의 일부다(요구사항 2절 — 중복을 알고도 허용한다). 그래서 병합하지 않고
|
||||
소스 그대로 가른다. 판매처 구분은 mall_name 을 화면에 병기해 해결한다.
|
||||
"""
|
||||
out: dict[str, list[NormalizedProduct]] = {}
|
||||
for p in products:
|
||||
out.setdefault(p.source, []).append(p)
|
||||
for items in out.values():
|
||||
items.sort(key=lambda p: p.price)
|
||||
return out
|
||||
|
||||
|
||||
def rank_result(products: list[NormalizedProduct], total_found: int, stages: list[dict], top_n: int = 5) -> dict:
|
||||
"""최저가순 정렬 + top-N + 결과 봉투 조립(top_n STAGE 포함).
|
||||
|
||||
AI 없는 동기 경로(run_price_pipeline)의 출력 형태다. 실제 검색 결과의 정식 형태는
|
||||
몰별 행(worker/handlers.py::_finalize_malls)이며 이 함수를 쓰지 않는다.
|
||||
"""
|
||||
ranked = sorted(products, key=lambda p: p.price)
|
||||
top = ranked[:top_n]
|
||||
stages = stages + [{"stage": "top_n", "in": len(ranked), "out": len(top)}]
|
||||
return {
|
||||
"total_found": total_found,
|
||||
"kept": len(ranked),
|
||||
"lowest": top[0].model_dump() if top else None,
|
||||
"top": [p.model_dump() for p in top],
|
||||
"by_source": {src: [p.model_dump() for p in items] for src, items in group_by_source(ranked).items()},
|
||||
"stages": stages,
|
||||
}
|
||||
|
||||
|
||||
def run_price_pipeline(
|
||||
products: list[NormalizedProduct],
|
||||
*,
|
||||
base_price: int | None = None,
|
||||
company: str | None = None,
|
||||
keep_mall: str | None = None,
|
||||
banned_malls=(),
|
||||
band_tolerance: float = 0.7,
|
||||
remove_outliers: bool = True,
|
||||
top_n: int = 5,
|
||||
) -> dict:
|
||||
"""AI 없는 동기 파이프라인(테스트/기본 경로). apply_filters + rank_result 조합."""
|
||||
cur, stages = apply_filters(
|
||||
products, base_price=base_price, company=company, keep_mall=keep_mall,
|
||||
banned_malls=banned_malls, band_tolerance=band_tolerance, remove_outliers=remove_outliers,
|
||||
)
|
||||
return rank_result(cur, len(products), stages, top_n)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""다나와 — 상품 페이지(PDP) 해석 + 검색 어댑터. 무차단 카탈로그(2026-08-18 실측).
|
||||
|
||||
PDP(prod.danawa.com/info/?pcode=…)는 무차단 몰 중 데이터가 가장 좋다 —
|
||||
JSON-LD Product(상품명·이미지)에 더해
|
||||
· AggregateOffer.lowPrice = 판매처들 중 최저가 → **기준가**(가격밴드 필터 입력)로 그대로 쓴다
|
||||
· .spec_list = 정규화된 규격("골프화 / 남성용 / [소재] 갑피: 합성피혁 …")
|
||||
· .made_info = "제조사: 본필" — company 칸을 채우는 유일한 무추측 소스
|
||||
|
||||
검색(search.danawa.com/dsearch.php)은 서버렌더 카드(li.prod_item)다. 다나와는
|
||||
네이버처럼 **어그리게이터**라 카드의 가격은 '어느 몰의 최저가'이고 주인 몰은 카드에
|
||||
없다 — mall_name 은 비워 둔다(판매처 미상, '우리가 못 읽음'이 아니라 '카탈로그가
|
||||
안 알려줌'이다).
|
||||
"""
|
||||
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from selectolax.parser import HTMLParser
|
||||
|
||||
from prism_core import jsonld
|
||||
from prism_core.contract import NormalizedProduct, ResolvedProduct
|
||||
from prism_core.http_adapter import HttpSearchAdapter
|
||||
from prism_core.util import extract_price, parse_price
|
||||
|
||||
_PCODE = re.compile(r"[?&]pcode=(\d+)")
|
||||
# made_info 예: "등록월: 2023.10. ㅣ 제조사: 본필 ㅣ 이미지출처: G마켓" — 구분자 'ㅣ'(한글 자모)
|
||||
_MAKER = re.compile(r"제조사\s*[::]\s*([^ㅣ|<\n]+)")
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
|
||||
def _text(tree: HTMLParser, selector: str) -> str:
|
||||
node = tree.css_first(selector)
|
||||
return _WS.sub(" ", node.text(separator=" ")).strip() if node else ""
|
||||
|
||||
|
||||
def _summarize_spec(text: str) -> str:
|
||||
"""spec_list 원문 → 프리필·검색어에 쓸 요약.
|
||||
|
||||
원문은 [영양정보] 같은 상세 블록까지 통째다(실측 300자: "… / 400개입 / [영양정보]
|
||||
열량 : 50kcal / 나트륨 : 10mg …"). 그대로 specification 에 넣으면 검색어 조합이
|
||||
그 토큰들을 다 실어서 **라운드 1이 통째로 죽는다**(2026-08-18 실측: 원본 쿼리
|
||||
0매칭 → LLM 재정제 라운드가 회복). 요약 규칙:
|
||||
- 첫 브라켓 섹션([특징]·[영양정보]…)부터는 버린다 — 거기부터가 상세 블록이다
|
||||
- "개당중량 : 12g" 같은 key:value 항목도 버린다 — 수량("400개입")은 자체 세그먼트로 남는다
|
||||
- 최대 5개 세그먼트, 100자
|
||||
"""
|
||||
parts = []
|
||||
for seg in text.split(" / "):
|
||||
seg = seg.strip()
|
||||
if seg.startswith("["):
|
||||
break
|
||||
if " : " in seg:
|
||||
continue
|
||||
parts.append(seg)
|
||||
if len(parts) >= 5:
|
||||
break
|
||||
return " / ".join(parts)[:100]
|
||||
|
||||
|
||||
def parse(html: str, url: str) -> ResolvedProduct | None:
|
||||
product = jsonld.find_product(html)
|
||||
if not product or not product.get("name"):
|
||||
return None
|
||||
|
||||
tree = HTMLParser(html)
|
||||
image = product.get("image")
|
||||
if isinstance(image, list):
|
||||
image = image[0] if image else None
|
||||
|
||||
maker = ""
|
||||
made = _text(tree, ".made_info")
|
||||
m = _MAKER.search(made)
|
||||
if m:
|
||||
maker = m.group(1).strip()
|
||||
|
||||
m_id = _PCODE.search(url)
|
||||
return ResolvedProduct(
|
||||
product_name=str(product["name"]).strip(),
|
||||
company=maker,
|
||||
specification=_summarize_spec(_text(tree, ".spec_list")),
|
||||
price=parse_price(jsonld.offer_price(product)),
|
||||
image_url=str(image) if image else None,
|
||||
catalog_id=m_id.group(1) if m_id else None,
|
||||
)
|
||||
|
||||
|
||||
# ── 검색 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
_SEARCH_URL = "https://search.danawa.com/dsearch.php?query={q}"
|
||||
|
||||
|
||||
def parse_search(html: str) -> list[NormalizedProduct]:
|
||||
"""검색 결과 카드 → NormalizedProduct. 상품 링크(pcode)와 가격이 없는 카드
|
||||
(광고·기획전·연관검색 블록)는 상품이 아니므로 버린다."""
|
||||
out: list[NormalizedProduct] = []
|
||||
for card in HTMLParser(html).css("li.prod_item"):
|
||||
a = card.css_first("p.prod_name a")
|
||||
price_node = card.css_first("p.price_sect strong")
|
||||
if not a or not price_node:
|
||||
continue
|
||||
href = a.attributes.get("href") or ""
|
||||
m = _PCODE.search(href)
|
||||
if "prod.danawa.com/info" not in href or not m:
|
||||
continue
|
||||
# 옵션이 여럿인 카드는 price_sect 가 옵션 수만큼 있다 — 첫 번째가 대표 옵션이고
|
||||
# 상품명도 그 옵션 기준이라 첫 값만 쓴다(다른 옵션은 다른 상품이다).
|
||||
price = extract_price(price_node.text())
|
||||
if not price:
|
||||
continue
|
||||
img = card.css_first("img")
|
||||
out.append(NormalizedProduct(
|
||||
source="danawa",
|
||||
name=re.sub(r"\s+", " ", a.text(separator=" ")).strip(),
|
||||
price=price,
|
||||
detail_url=href,
|
||||
external_id=m.group(1),
|
||||
image_url=(img.attributes.get("src") or None) if img else None,
|
||||
# 카탈로그 최저가 — 주인 몰을 카드가 안 알려준다(네이버 가격비교와 같은 성질).
|
||||
mall_name=None,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
class DanawaAdapter(HttpSearchAdapter):
|
||||
source = "danawa"
|
||||
|
||||
def _search_url(self, query: str, limit: int) -> str:
|
||||
return _SEARCH_URL.format(q=quote(query))
|
||||
|
||||
def _parse(self, html: str) -> list[NormalizedProduct]:
|
||||
return parse_search(html)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""prism common/enums.py 발췌 — 측정에 필요한 SourceState만 (로직 무수정)."""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class SourceState(Enum):
|
||||
"""한 상품을 **한 몰에서** 찾은 결과.
|
||||
|
||||
가장 중요한 경계는 `확인함` 과 `못 봄` 사이다:
|
||||
MATCHED·NO_MATCH·EMPTY 그 몰을 실제로 봤다 → "없다"고 말해도 되는 사실
|
||||
BLOCKED·ENV_BLOCKED·UNAVAILABLE 못 봤다 → "없다"고 말하면 거짓이 된다
|
||||
"""
|
||||
|
||||
MATCHED = 1 # 수집·매칭 성공 — 가격 확보
|
||||
NO_MATCH = 2 # 수집은 됐으나 같은 상품이 없음(액세서리·다른 규격만)
|
||||
EMPTY = 3 # 그 몰의 검색 결과 자체가 0건
|
||||
BLOCKED = 4 # 안티봇 차단 — IP 회전으로 회복 가능(자동)
|
||||
ENV_BLOCKED = 5 # 회전해도 안 되는 차단(환경·게이트웨이 설정) — 사람이 고쳐야 함
|
||||
UNAVAILABLE = 6 # 전송 실패·가용 IP 없음 등 일시적 — 잠시 후 재시도로 회복
|
||||
SKIPPED = 7 # 그 소스를 아예 쓰지 않음(폴백 OFF 등)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""에누리 — 상품 페이지(PDP) 해석 + 검색 어댑터. 무차단 카탈로그(2026-08-18 실측).
|
||||
|
||||
PDP(enuri.com/detail.jsp?modelno=…)의 정적 HTML 에 있는 것은 BreadcrumbList
|
||||
JSON-LD(정규화 상품명 + 카테고리 경로)와 <title> 뿐이다 — 가격·스펙은 AJAX 라
|
||||
여기서는 **읽지 않는다**(없는 값은 비워 두는 게 규칙).
|
||||
|
||||
검색(enuri.com/search.jsp)은 반대로 **JSON-LD ItemList 가 통째로** 있다 — 상품명·
|
||||
modelno·AggregateOffer(최저가·판매처 수)·평점까지. HTML 셀렉터가 아예 필요 없어서
|
||||
마크업 드리프트에도 가장 강한 파서다. 다나와처럼 어그리게이터라 mall_name 은
|
||||
비워 두되(판매처 미상) **offerCount 를 seller_count 로** 남긴다 — '카탈로그가
|
||||
안 알려줌'과 '우리가 못 읽음'을 화면이 가를 수 있는 근거다.
|
||||
"""
|
||||
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from selectolax.parser import HTMLParser
|
||||
|
||||
from prism_core import jsonld
|
||||
from prism_core.contract import NormalizedProduct, ResolvedProduct
|
||||
from prism_core.http_adapter import HttpSearchAdapter
|
||||
from prism_core.util import parse_price
|
||||
|
||||
_MODELNO = re.compile(r"[?&]modelno=(\d+)")
|
||||
_TITLE_SUFFIX = re.compile(r"\s*-\s*에누리\s*가격비교\s*$")
|
||||
|
||||
|
||||
def parse(html: str, url: str) -> ResolvedProduct | None:
|
||||
name = ""
|
||||
category = None
|
||||
|
||||
crumb = jsonld.find_breadcrumb(html)
|
||||
if crumb:
|
||||
name = str(crumb.get("name") or "").strip()
|
||||
items = crumb.get("itemListElement")
|
||||
if isinstance(items, list):
|
||||
# '홈'을 뺀 분류 경로. 마지막 항목이 상품명 자신인 사이트도 있어 이름과 같으면 뺀다.
|
||||
parts = [str(i.get("name")).strip() for i in items
|
||||
if isinstance(i, dict) and i.get("name") and str(i.get("name")).strip() not in ("홈", name)]
|
||||
category = " > ".join(parts) or None
|
||||
|
||||
if not name:
|
||||
node = HTMLParser(html).css_first("title")
|
||||
if node:
|
||||
name = _TITLE_SUFFIX.sub("", node.text().strip())
|
||||
|
||||
if not name:
|
||||
return None
|
||||
|
||||
m_id = _MODELNO.search(url)
|
||||
return ResolvedProduct(
|
||||
product_name=name,
|
||||
category=category,
|
||||
catalog_id=m_id.group(1) if m_id else None,
|
||||
)
|
||||
|
||||
|
||||
# ── 검색 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
_SEARCH_URL = "https://www.enuri.com/search.jsp?keyword={q}"
|
||||
|
||||
|
||||
def _as_int(v) -> int | None:
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def parse_search(html: str) -> list[NormalizedProduct]:
|
||||
"""검색 페이지의 JSON-LD ItemList → NormalizedProduct. 가격 없는 항목은 버린다."""
|
||||
out: list[NormalizedProduct] = []
|
||||
for block in jsonld.blocks(html):
|
||||
if block.get("@type") != "ItemList":
|
||||
continue
|
||||
for li in block.get("itemListElement") or []:
|
||||
item = li.get("item") if isinstance(li, dict) else None
|
||||
if not isinstance(item, dict) or not item.get("name"):
|
||||
continue
|
||||
offers = item.get("offers") if isinstance(item.get("offers"), dict) else {}
|
||||
price = parse_price(offers.get("lowPrice"))
|
||||
if not price:
|
||||
continue
|
||||
rating = item.get("aggregateRating") if isinstance(item.get("aggregateRating"), dict) else {}
|
||||
rating_value = rating.get("ratingValue")
|
||||
out.append(NormalizedProduct(
|
||||
source="enuri",
|
||||
name=str(item["name"]).strip(),
|
||||
price=price,
|
||||
detail_url=str(item.get("url") or "") or None,
|
||||
external_id=str(item.get("sku") or "").strip() or None,
|
||||
image_url=str(item.get("image") or "") or None,
|
||||
mall_name=None, # 카탈로그 최저가 — 주인 몰 미상
|
||||
seller_count=_as_int(offers.get("offerCount")), # '안 알려줌'이 아니라 '몇 곳 중'인지는 안다
|
||||
rating=float(rating_value) if rating_value is not None else None,
|
||||
review_count=_as_int(rating.get("reviewCount")),
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
class EnuriAdapter(HttpSearchAdapter):
|
||||
source = "enuri"
|
||||
|
||||
def _search_url(self, query: str, limit: int) -> str:
|
||||
return _SEARCH_URL.format(q=quote(query))
|
||||
|
||||
def _parse(self, html: str) -> list[NormalizedProduct]:
|
||||
return parse_search(html)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""가격 파이프라인 순수 필터(부작용 없음). 레퍼런스의 mall/price-band 필터를 NormalizedProduct 로 이식."""
|
||||
|
||||
from prism_core.contract import NormalizedProduct
|
||||
from prism_core.util import brand_tokens, norm_token
|
||||
|
||||
|
||||
def keep_only_mall(products: list[NormalizedProduct], mall_name: str) -> list[NormalizedProduct]:
|
||||
target = (mall_name or "").strip().lower()
|
||||
return [p for p in products if (p.mall_name or "").strip().lower() == target]
|
||||
|
||||
|
||||
def filter_out_malls(products: list[NormalizedProduct], banned) -> list[NormalizedProduct]:
|
||||
"""banned mall(문자열/리스트) 제거. 네이버 결과에서 오픈마켓을 걷어낼 때 쓴다(쿠팡 단독이면 no-op)."""
|
||||
names = [banned] if isinstance(banned, str) else list(banned or [])
|
||||
ban = {m.strip().lower() for m in names if m}
|
||||
if not ban:
|
||||
return list(products)
|
||||
return [p for p in products if (p.mall_name or "").strip().lower() not in ban]
|
||||
|
||||
|
||||
def filter_by_price_band(products: list[NormalizedProduct], base_price: int, tolerance: float = 0.7) -> list[NormalizedProduct]:
|
||||
"""기준가 ±(tolerance×100)% 밴드만 남긴다. base_price 가 없거나 0 이하면 무필터 통과.
|
||||
요청의 현재가(price)를 기준으로 '엉뚱한 저가/고가'(액세서리·묶음 등)를 targeted 하게 컷."""
|
||||
if not base_price or base_price <= 0:
|
||||
return list(products)
|
||||
lo, hi = base_price * (1 - tolerance), base_price * (1 + tolerance)
|
||||
return [p for p in products if p.price is not None and lo <= p.price <= hi]
|
||||
|
||||
|
||||
def filter_brand_mismatch(products: list[NormalizedProduct], company: str) -> list[NormalizedProduct]:
|
||||
"""제조사가 주어졌으면 **그 브랜드가 안 보이는 후보를 잘라낸다**(AI 판정 이전).
|
||||
|
||||
왜 AI 앞에서 규칙으로 자르는가 — AI 는 걸러야 할 양이 많아질수록 오탐 확률이 올라간다.
|
||||
후보 141건 중 136건을 걸러야 하는 상황이면 15배치 중 한 번만 틀려도 되고,
|
||||
**그 오탐이 하필 싼 값이면 그게 최저가로 확정된다**(2026-08-10 실측: 'LG 무선청소기'에
|
||||
캐치웰 89,000원이 최저가로 잡혔다 — 다른 몰은 전부 36~52만원대 LG 제품이었다).
|
||||
브랜드 불일치는 규칙으로 확실히 판정할 수 있으니, AI 가 판단할 양 자체를 줄여 준다.
|
||||
|
||||
판정은 **상품명 또는 판매몰명**에 브랜드 토큰이 있는지로 한다(util.brand_tokens —
|
||||
전체 이름 + 2글자 접두. '동서식품' 이 '동서)맥심...' 으로 나오는 표기 축약을 흡수한다).
|
||||
|
||||
── 안전밸브: **몰별로 판단하고, 그 몰에 브랜드 표기가 하나도 없으면 자르지 않는다** ──
|
||||
브랜드를 아예 안 적는 상품이 많다('맥심 모카골드 마일드' 에는 '동서' 가 없다).
|
||||
그 몰의 결과가 통째로 그런 표기면, 자르는 순간 정상 상품까지 전멸해 '없음' 으로 둔갑한다.
|
||||
반대로 **같은 몰에 브랜드 표기 상품이 존재하는데도 안 적힌 후보**라면 다른 브랜드일 확률이
|
||||
높다 — 실제 사고가 그 모양이었다(G마켓 상위 40건 중 38건이 LG 였는데 캐치웰 1건이 통과).
|
||||
|
||||
company 가 비어 있으면 아무것도 자르지 않는다.
|
||||
"""
|
||||
tokens = brand_tokens(company or "")
|
||||
if not tokens:
|
||||
return list(products)
|
||||
|
||||
def has_brand(p: NormalizedProduct) -> bool:
|
||||
return any(t in norm_token(f"{p.name or ''} {p.mall_name or ''}") for t in tokens)
|
||||
|
||||
by_source: dict[str, list[NormalizedProduct]] = {}
|
||||
for p in products:
|
||||
by_source.setdefault(p.source, []).append(p)
|
||||
|
||||
kept: list[NormalizedProduct] = []
|
||||
for items in by_source.values():
|
||||
matched = [p for p in items if has_brand(p)]
|
||||
# 그 몰에 브랜드 표기가 하나도 없으면 판단 근거가 없다 → 자르지 않고 AI 에 맡긴다.
|
||||
kept.extend(matched if matched else items)
|
||||
# 입력 순서를 보존한다(뒤 단계의 정렬·배치 구성이 입력 순서에 의존한다).
|
||||
keep = {id(p) for p in kept}
|
||||
return [p for p in products if id(p) in keep]
|
||||
@@ -0,0 +1,98 @@
|
||||
"""GS샵 — 상품 페이지(PDP) 해석 + 검색 어댑터. 무차단 직영몰(2026-08-18 실측).
|
||||
|
||||
PDP(gsshop.com/prd/prd.gs?prdid=…)는 JSON-LD 가 @graph 안에 완전한
|
||||
Product(name·brand·offers.price·image)로 온다. 주의: GS샵은 홈쇼핑 기획상품
|
||||
(단독 구성)이 많아, 읽은 상품이 다른 몰에 없는 게 정상일 수 있다 — 그건 파서가
|
||||
아니라 검색 결과(NO_MATCH)가 말할 사실이다.
|
||||
|
||||
검색은 **모바일 표면**(m.gsshop.com/search/searchSect.gs)을 쓴다 — PC 검색 경로는
|
||||
405 를 주지만 모바일은 article.prd-item 카드가 서버렌더로 온다(브랜드·판매가·배송·
|
||||
평점·상품평 수까지). 직영몰이라 mall_name 은 "GS샵" 고정이다.
|
||||
"""
|
||||
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from selectolax.parser import HTMLParser
|
||||
|
||||
from prism_core import jsonld
|
||||
from prism_core.contract import NormalizedProduct, ResolvedProduct
|
||||
from prism_core.http_adapter import HttpSearchAdapter
|
||||
from prism_core.util import extract_price, parse_price, shipping_from_text
|
||||
|
||||
_PRDID = re.compile(r"[?&]prdid=(\d+)")
|
||||
|
||||
|
||||
def parse(html: str, url: str) -> ResolvedProduct | None:
|
||||
product = jsonld.find_product(html)
|
||||
if not product or not product.get("name"):
|
||||
return None
|
||||
|
||||
image = product.get("image")
|
||||
if isinstance(image, list):
|
||||
image = image[0] if image else None
|
||||
|
||||
m_id = _PRDID.search(url)
|
||||
return ResolvedProduct(
|
||||
product_name=str(product["name"]).strip(),
|
||||
company=jsonld.brand_name(product),
|
||||
price=parse_price(jsonld.offer_price(product)),
|
||||
image_url=str(image) if image else None,
|
||||
catalog_id=m_id.group(1) if m_id else None,
|
||||
)
|
||||
|
||||
|
||||
# ── 검색 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
_SEARCH_URL = "https://m.gsshop.com/search/searchSect.gs?tq={q}"
|
||||
_RATING = re.compile(r"([\d.]+)\s*점")
|
||||
_REVIEWS = re.compile(r"\(([\d,]+)\s*건\)")
|
||||
|
||||
|
||||
def parse_search(html: str) -> list[NormalizedProduct]:
|
||||
"""모바일 검색의 article.prd-item 카드 → NormalizedProduct."""
|
||||
out: list[NormalizedProduct] = []
|
||||
for card in HTMLParser(html).css("article.prd-item"):
|
||||
link = card.css_first("a.prd-link")
|
||||
price_node = card.css_first(".set-price strong")
|
||||
name_node = card.css_first(".prd-name")
|
||||
if not link or not price_node or not name_node:
|
||||
continue
|
||||
price = extract_price(price_node.text())
|
||||
if not price:
|
||||
continue
|
||||
brand = card.css_first(".brand-name")
|
||||
name = " ".join(p for p in ((brand.text().strip() if brand else ""),
|
||||
name_node.text().strip()) if p)
|
||||
ship_node = card.css_first(".ship")
|
||||
fee, ship_type = shipping_from_text(ship_node.text()) if ship_node else (None, None)
|
||||
side = card.css_first(".user-side")
|
||||
side_text = side.text(separator=" ") if side else ""
|
||||
m_rating = _RATING.search(side_text)
|
||||
m_reviews = _REVIEWS.search(side_text)
|
||||
img = card.css_first("img")
|
||||
out.append(NormalizedProduct(
|
||||
source="gsshop",
|
||||
name=name,
|
||||
price=price,
|
||||
detail_url=(link.attributes.get("href") or "") or None,
|
||||
external_id=(card.attributes.get("data-prdcd") or "") or None,
|
||||
image_url=(img.attributes.get("src") or None) if img else None,
|
||||
mall_name="GS샵",
|
||||
shipping_fee=fee,
|
||||
shipping_type=ship_type,
|
||||
shipping_label=(ship_node.text().strip() or None) if ship_node else None,
|
||||
rating=float(m_rating.group(1)) if m_rating else None,
|
||||
review_count=int(m_reviews.group(1).replace(",", "")) if m_reviews else None,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
class GsshopAdapter(HttpSearchAdapter):
|
||||
source = "gsshop"
|
||||
|
||||
def _search_url(self, query: str, limit: int) -> str:
|
||||
return _SEARCH_URL.format(q=quote(query))
|
||||
|
||||
def _parse(self, html: str) -> list[NormalizedProduct]:
|
||||
return parse_search(html)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""무차단 몰용 HTTP 검색 어댑터 베이스 — 브라우저 없이 httpx 로 검색 페이지 한 장.
|
||||
|
||||
브라우저 어댑터(access/browser.BrowserSearchAdapter)와 같은 계약(SearchAdapter)을
|
||||
구현하므로 워커·파이프라인은 둘을 구분하지 않는다. 차이는 수단뿐이다:
|
||||
무차단 몰(다나와·에누리·GS샵, 2026-08-18 실측)은 챌린지가 없어 실브라우저·프로필·
|
||||
웜업이 전부 불필요하고, 검색 1회 = fetch 1회다.
|
||||
|
||||
⚠️ '무차단'은 실측의 스냅샷이다. 이 어댑터가 BLOCKED 를 내기 시작하면
|
||||
malls/registry 의 등급과 함께 재실측할 것 — 그때는 브라우저 어댑터로 옮겨야 할 수도 있다.
|
||||
"""
|
||||
|
||||
from abc import abstractmethod
|
||||
|
||||
from prism_core.enums import SourceState
|
||||
from prism_core.shims import LOG
|
||||
from prism_core.shims import DecodoProxy
|
||||
from prism_core.shims import ProxiedHttpClient
|
||||
from prism_core.contract import AdapterError, NormalizedProduct, SearchAdapter
|
||||
|
||||
|
||||
class HttpSearchAdapter(SearchAdapter):
|
||||
"""HTTP 검색 어댑터. 서브클래스는 _search_url / _parse 만 구현한다(브라우저 베이스와 동일 계약)."""
|
||||
|
||||
source: str
|
||||
# 정상 결과 페이지의 최소 크기. 이 몰들은 0건이어도 페이지 크롬이 커서 수십 KB 는 된다 —
|
||||
# 이보다 작으면 결과가 아니라 차단/오류 페이지다(0건과 차단을 같은 칸에 두지 않는다).
|
||||
min_result_html = 30000
|
||||
|
||||
def __init__(self, proxy: DecodoProxy | None = None, *, use_proxy: bool = True,
|
||||
timeout_sec: float = 15.0):
|
||||
self._client = ProxiedHttpClient(
|
||||
proxy if proxy is not None else DecodoProxy(owner=f"prism-http-{self.source}"),
|
||||
timeout_sec=timeout_sec, use_proxy=use_proxy,
|
||||
)
|
||||
self.last_bytes = 0 # 최근 fetch 의 실제 전송 바이트 — 핸들러가 대역폭 비용에 귀속한다
|
||||
|
||||
@property
|
||||
def uses_proxy(self) -> bool:
|
||||
"""프록시(DECODO) 경유 여부 — 대역폭 비용 귀속용(handlers._timed_search 가 읽는다).
|
||||
⚠️ 이게 없으면 use_proxy=true 여도 비용이 0 으로 샌다(2026-08-20 실측 버그)."""
|
||||
return self._client.uses_proxy
|
||||
|
||||
def _rotate_ip(self, reason: str):
|
||||
"""DECODO exit IP 를 교체한다(브라우저 어댑터와 동일 시그니처 — 웜업이 실패 시 부른다).
|
||||
무차단 몰엔 무해하고, 레이트 민감 몰(알리·아마존)엔 punish 를 푸는 실효 수단이다."""
|
||||
self._client.rotate(reason)
|
||||
|
||||
@abstractmethod
|
||||
def _search_url(self, query: str, limit: int) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def _parse(self, html: str) -> list[NormalizedProduct]:
|
||||
raise NotImplementedError
|
||||
|
||||
async def search(self, query: str, limit: int = 40) -> list[NormalizedProduct]:
|
||||
url = self._search_url(query, limit)
|
||||
self.last_bytes = 0 # 실패·재청구 방지 — 성공하면 아래에서 실제 바이트로 채운다
|
||||
try:
|
||||
fetched = await self._client.fetch(url)
|
||||
except Exception as ex:
|
||||
self._note_result(False)
|
||||
raise AdapterError(f"{self.source} fetch 실패: {type(ex).__name__}: {ex}",
|
||||
source=self.source, state=SourceState.UNAVAILABLE) from ex
|
||||
|
||||
# 차단 페이지도 프록시 대역폭을 썼다 — 상태와 무관하게 바이트를 기록한다(비용은 사실이다).
|
||||
self.last_bytes = fetched.nbytes
|
||||
if fetched.status in (403, 429):
|
||||
self._note_result(False)
|
||||
raise AdapterError(f"{self.source} 차단 응답 HTTP {fetched.status}",
|
||||
source=self.source, blocked=True)
|
||||
if fetched.status != 200:
|
||||
self._note_result(False)
|
||||
raise AdapterError(f"{self.source} HTTP {fetched.status}",
|
||||
source=self.source, state=SourceState.UNAVAILABLE)
|
||||
if len(fetched.html) < self.min_result_html:
|
||||
# 200 인데 비정상적으로 작다 = 위장 차단/오류 페이지. EMPTY(봤고 없다)로 넘기면
|
||||
# 못 본 몰이 없는 몰이 된다 — 그 혼동이 이 프로젝트가 내내 막아 온 것이다.
|
||||
self._note_result(False)
|
||||
raise AdapterError(f"{self.source} 응답이 비정상적으로 작음({len(fetched.html)}B)",
|
||||
source=self.source, blocked=True)
|
||||
|
||||
items = self._parse(fetched.html)[:limit]
|
||||
self._note_result(True)
|
||||
LOG.d(f"[{self.source}] HTTP 검색 {len(items)}건 (html {len(fetched.html):,}B)")
|
||||
return items
|
||||
@@ -0,0 +1,181 @@
|
||||
"""상품 식별 게이트 — 이름 기반 결정적 동일성 검증 (2026-08-31 설계).
|
||||
|
||||
배경: AI 판정(SimilarityJudge)은 후보를 독립 채점할 뿐 후보 간 비교를 못 하고,
|
||||
선택부가 min(price)만 봐서 점수 90짜리 저가 오탐이 점수 100짜리 정답을 밀어냈다
|
||||
(회귀 8건의 전부). 이 모듈은 그 사이에 서는 결정적 거부권(veto)이다:
|
||||
LLM은 판별에 쓰되, 식별 토큰(브랜드·모델·변형어·규격)의 존재 검증은 코드가 한다.
|
||||
|
||||
비교 규약 (local_judge.score_candidate 와 동일 계보):
|
||||
- 문자열 존재 검사는 반드시 공백 제거 + norm_token 후 substring —
|
||||
danawa 가 브랜드를 '삼성 전자'처럼 띄어 반환하므로 토큰 단위 비교는 오폭한다.
|
||||
- 비대칭 안전밸브: 양쪽 모두 값이 있을 때만 충돌로 본다 (없는 건 미기재일 뿐).
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from prism_core.local_judge import _SPEC_RE, _STOPWORDS, _specs
|
||||
from prism_core.util import norm_token
|
||||
|
||||
_NUM_RE = re.compile(r"\d")
|
||||
|
||||
# 한↔영 브랜드 별칭 — 몰별 표기 차이 흡수 (gsshop 은 셀러 자유기재라 한글 표기가 흔함).
|
||||
# 업계 공통 표기만 등재한다 (케이스별 하드코딩 아님).
|
||||
_BRAND_PAIRS = [
|
||||
("seagate", "씨게이트"), ("brother", "브라더"), ("logitech", "로지텍"),
|
||||
("philips", "필립스"), ("apple", "애플"), ("samsung", "삼성"),
|
||||
("lg", "엘지"), ("msi", "엠에스아이"), ("razer", "레이저"),
|
||||
("bosch", "보쉬"), ("corelle", "코렐"), ("braun", "브라운"),
|
||||
("3m", "쓰리엠"), ("anker", "앤커"), ("corsair", "커세어"),
|
||||
("epson", "엡손"), ("sandisk", "샌디스크"), ("cuckoo", "쿠쿠"),
|
||||
("balmuda", "발뮤다"), ("hp", "에이치피"), ("aula", "아울라"),
|
||||
]
|
||||
_BRAND_ALIASES: dict = {}
|
||||
for _en, _ko in _BRAND_PAIRS:
|
||||
_BRAND_ALIASES.setdefault(_en, []).append(_ko)
|
||||
_BRAND_ALIASES.setdefault(_ko, []).append(_en)
|
||||
|
||||
# 등급/에디션 변형어 렉시콘 — '같은 라인의 다른 SKU'를 가르는 업계 공통 어휘.
|
||||
# 한글은 substring 검사('라이트핏'→'라이트'), 영문은 토큰 단위 검사(mouse 안의 'se' 오폭 방지).
|
||||
# 한↔영 표기는 같은 변형어다: '아이폰 16 Pro' == '아이폰 16 프로' (등가 정규화 필수 —
|
||||
# 미등가 시 같은 단어가 var-miss 와 var-extra 로 이중 처벌되는 버그가 실측됨).
|
||||
_VARIANT_CANON = {
|
||||
"pro": "pro", "프로": "pro", "plus": "plus", "플러스": "plus",
|
||||
"max": "max", "맥스": "max", "lite": "lite", "라이트": "lite",
|
||||
"mini": "mini", "미니": "mini", "ultra": "ultra", "울트라": "ultra",
|
||||
"se": "se", "prime": "prime", "neo": "neo", "에디션": "에디션",
|
||||
}
|
||||
_VARIANTS_EN = {v for v in _VARIANT_CANON if v.isascii()}
|
||||
_VARIANTS_KO = {v for v in _VARIANT_CANON if not v.isascii()}
|
||||
# 한국어 수량·등급 접미 표현 — 숫자+접미 전체일치면 규격으로 분류 (모델 토큰 아님):
|
||||
# '2세대'·'6인용'·'12캔'·'1급' 이 모델로 오분류되면 표기 생략 후보가 전부 죽는다.
|
||||
_KO_COUNT_RE = re.compile(r"^\d+(세대|인용|캔|급|단|구|도|번|차)$")
|
||||
_DIGIT_LETTER_RE = re.compile(r"^\d+[a-z]$") # '4k'·'8k' 류 해상도 표기 — 식별력 없음
|
||||
|
||||
|
||||
def _joined(text: str) -> str:
|
||||
"""존재 검사용 정규화 — 소문자화 후 영숫자·한글만 남긴다 (공백·하이픈·'/'·'˚' 등
|
||||
기호 전부 제거). 모델 토큰 정규화(bare)와 반드시 같은 규칙이어야 한다 —
|
||||
한쪽만 기호를 지우면 'MXP93KH/A' 가 자기 자신과도 불일치하는 오폭이 난다."""
|
||||
return re.sub(r"[^0-9a-z가-힣]", "", (text or "").lower())
|
||||
|
||||
|
||||
def _tokens(text: str) -> list[str]:
|
||||
toks = [norm_token(t) for t in (text or "").split()]
|
||||
return [t for t in toks if t and t not in _STOPWORDS]
|
||||
|
||||
|
||||
def _model_tokens(text: str) -> list[str]:
|
||||
"""숫자+문자 혼합 식별 토큰. 순수 규격(16A·2L·12W 등 숫자+단위 전체일치)은 제외 —
|
||||
규격은 _specs 충돌 검사가 따로 다루며, 여기 넣으면 규격 생략 표기가 오폭한다."""
|
||||
out = []
|
||||
for t in _tokens(text):
|
||||
if not _NUM_RE.search(t):
|
||||
continue
|
||||
bare = re.sub(r"[^0-9a-z가-힣]", "", t) # 하이픈·˚ 등 기호 제거 ('360˚'→'360')
|
||||
if _SPEC_RE.fullmatch(t) or _SPEC_RE.fullmatch(bare):
|
||||
continue
|
||||
if not bare or bare.isdigit(): # 순수 숫자(수량·연식 추정)는 식별력이 없다
|
||||
continue
|
||||
if _KO_COUNT_RE.match(bare) or _DIGIT_LETTER_RE.match(bare):
|
||||
continue
|
||||
out.append(bare)
|
||||
return out
|
||||
|
||||
|
||||
def _brand(text: str) -> str | None:
|
||||
"""선두 비수치 토큰 = 브랜드 추정. 첫 토큰이 모델형(S-2, 3M)이면 브랜드 판정 포기 —
|
||||
카테고리 명사를 브랜드로 오인해 정답을 죽이는 것보다 검사 생략이 안전하다."""
|
||||
toks = _tokens(text)
|
||||
if not toks:
|
||||
return None
|
||||
first = toks[0]
|
||||
if _NUM_RE.search(first):
|
||||
return None
|
||||
return first
|
||||
|
||||
|
||||
def _brand_present(brand: str, cand_joined: str) -> bool:
|
||||
cands = [brand] + _BRAND_ALIASES.get(brand, [])
|
||||
if len(brand) > 2: # 상품명은 회사명을 줄여 쓴다: '동서식품'→'동서)맥심' (util.brand_tokens 계보)
|
||||
cands.append(brand[:2])
|
||||
return any(a in cand_joined for a in cands)
|
||||
|
||||
|
||||
_CANON_SURFACES: dict = {}
|
||||
for _s, _c in _VARIANT_CANON.items():
|
||||
_CANON_SURFACES.setdefault(_c, []).append(_s)
|
||||
|
||||
|
||||
def _variants(text: str) -> set[str]:
|
||||
"""변형어 추출(정규형) — 모델 토큰(GM51·GEN8·에어팟4 등 숫자 포함)은 스캔에서
|
||||
제외해 'GEN8'의 gen, '에어팟4'의 '에어' 같은 오인을 막는다."""
|
||||
out = set()
|
||||
for t in _tokens(text):
|
||||
if _NUM_RE.search(t):
|
||||
continue
|
||||
if t in _VARIANT_CANON:
|
||||
out.add(_VARIANT_CANON[t])
|
||||
else:
|
||||
for v in _VARIANTS_KO:
|
||||
# 접두 일치는 나머지가 한글일 때만 변형어로 본다 — '라이트핏'(핏)은 변형어,
|
||||
# '울트라hd'(hd)는 해상도 용어(UltraHD)라 등급어가 아니다 (오폭 실측).
|
||||
rest = t[len(v):]
|
||||
if t.startswith(v) and (not rest or not rest.isascii()):
|
||||
out.add(_VARIANT_CANON[v])
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _variant_present(canon: str, other_text: str) -> bool:
|
||||
"""정규형 변형어가 상대 텍스트에 (어느 표기로든) 존재하는가."""
|
||||
toks = set(_tokens(other_text))
|
||||
oj = _joined(other_text)
|
||||
for s in _CANON_SURFACES.get(canon, [canon]):
|
||||
if s.isascii():
|
||||
if s in toks: # 영문은 토큰 단위 (mouse 안의 'se' 오폭 방지)
|
||||
return True
|
||||
elif s in oj: # 한글은 substring ('라이트핏' 흡수)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def veto(target_text: str, cand_name: str) -> list[str]:
|
||||
"""타겟과 후보가 동일 상품일 수 없는 결정적 근거 목록. 빈 리스트 = 통과.
|
||||
|
||||
반환 사유: brand / model:<tok> / var-miss:<v> / var-extra:<v> / spec:<unit>
|
||||
"""
|
||||
reasons = []
|
||||
cj = _joined(cand_name)
|
||||
if not cj:
|
||||
return ["empty"]
|
||||
|
||||
brand = _brand(target_text)
|
||||
if brand and not _brand_present(brand, cj):
|
||||
reasons.append("brand")
|
||||
|
||||
for m in _model_tokens(target_text):
|
||||
if m not in cj:
|
||||
reasons.append(f"model:{m}")
|
||||
|
||||
t_vars, c_vars = _variants(target_text), _variants(cand_name)
|
||||
for v in t_vars - c_vars:
|
||||
if not _variant_present(v, cand_name):
|
||||
reasons.append(f"var-miss:{v}")
|
||||
for v in c_vars - t_vars:
|
||||
if not _variant_present(v, target_text):
|
||||
reasons.append(f"var-extra:{v}")
|
||||
|
||||
t_specs, c_specs = _specs(target_text), _specs(cand_name)
|
||||
for unit, t_vals in t_specs.items():
|
||||
c_vals = c_specs.get(unit)
|
||||
if c_vals and not (t_vals & c_vals):
|
||||
reasons.append(f"spec:{unit}")
|
||||
|
||||
return reasons
|
||||
|
||||
|
||||
def same_group(name_a: str, name_b: str) -> bool:
|
||||
"""두 후보명이 같은 정체성(동일 SKU 라인)인가 — 상호 veto 없음으로 정의.
|
||||
canonical(최고 확신 매칭)과 같은 그룹의 후보끼리만 최저가 경쟁을 시켜,
|
||||
'싼 정답'(해외구매 등)은 지키고 '싼 오탐'만 배제한다."""
|
||||
return not veto(name_a, name_b) and not veto(name_b, name_a)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""JSON-LD(<script type="application/ld+json">) 파싱 — 이 저장소 최초의 구조화 데이터 소비자.
|
||||
|
||||
검색 카드 파서는 셀렉터로 마크업을 더듬지만, 상세 페이지에는 사이트가 **직접 선언한**
|
||||
schema.org 데이터가 있다(4/4 무차단 사이트 실측: 다나와·11번가·GS샵 은 Product,
|
||||
에누리는 BreadcrumbList). 셀렉터보다 이것이 먼저다 — 마크업은 자주 바뀌어도
|
||||
검색엔진에 보여주는 구조화 데이터는 잘 안 바뀐다.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from selectolax.parser import HTMLParser
|
||||
|
||||
|
||||
def blocks(html: str) -> list[dict]:
|
||||
"""페이지의 모든 JSON-LD 블록을 dict 리스트로. 깨진 블록은 조용히 건너뛴다."""
|
||||
out: list[dict] = []
|
||||
for node in HTMLParser(html).css('script[type="application/ld+json"]'):
|
||||
raw = (node.text() or "").strip()
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
# strict=False: 사이트가 제어문자를 섞어 넣는 경우가 있다(그래도 데이터는 멀쩡하다)
|
||||
data = json.loads(raw, strict=False)
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(data, list):
|
||||
out.extend(d for d in data if isinstance(d, dict))
|
||||
elif isinstance(data, dict):
|
||||
out.append(data)
|
||||
return out
|
||||
|
||||
|
||||
def find_product(html: str) -> dict | None:
|
||||
"""@type=Product 블록을 찾는다. @graph 안쪽(GS샵)도 본다.
|
||||
|
||||
@type 이 없어도 name+offers 를 함께 가진 dict 는 상품으로 본다 —
|
||||
11번가가 @type 표기 없이 상품 JSON-LD 를 내는 케이스 방어.
|
||||
"""
|
||||
candidates: list[dict] = []
|
||||
for b in blocks(html):
|
||||
candidates.append(b)
|
||||
graph = b.get("@graph")
|
||||
if isinstance(graph, list):
|
||||
candidates.extend(g for g in graph if isinstance(g, dict))
|
||||
for c in candidates:
|
||||
t = c.get("@type")
|
||||
types = t if isinstance(t, list) else [t]
|
||||
if "Product" in types:
|
||||
return c
|
||||
for c in candidates:
|
||||
if c.get("name") and isinstance(c.get("offers"), dict):
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def find_breadcrumb(html: str) -> dict | None:
|
||||
"""BreadcrumbList 블록(에누리의 유일한 구조화 데이터)."""
|
||||
for b in blocks(html):
|
||||
if b.get("@type") == "BreadcrumbList":
|
||||
return b
|
||||
return None
|
||||
|
||||
|
||||
def brand_name(product: dict) -> str:
|
||||
"""Product 의 brand — dict({"name": "공차"}) 와 문자열 표기 둘 다 방어."""
|
||||
brand = product.get("brand")
|
||||
if isinstance(brand, dict):
|
||||
return str(brand.get("name") or "").strip()
|
||||
if isinstance(brand, str):
|
||||
return brand.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def offer_price(product: dict):
|
||||
"""offers 에서 가격 후보를 꺼낸다 — Offer 는 price, AggregateOffer 는 lowPrice 가 먼저다.
|
||||
|
||||
(다나와의 lowPrice 가 이 API 의 '기준가'로 가장 좋은 값이다 — 판매처들 중 최저.)
|
||||
타입 변환은 하지 않는다: "28970"(문자열)로 오는 사이트가 있어 호출부가 parse_price 로 받는다.
|
||||
"""
|
||||
offers = product.get("offers")
|
||||
if not isinstance(offers, dict):
|
||||
return None
|
||||
for key in ("lowPrice", "price"):
|
||||
v = offers.get(key)
|
||||
if v not in (None, ""):
|
||||
return v
|
||||
return None
|
||||
@@ -0,0 +1,45 @@
|
||||
"""LLM 검색어 생성 — 재정제 라운드용 정밀/광역 쿼리 생성 (PRISM keyword.py 이식).
|
||||
|
||||
룰 기반 재정제(capture_local.refine_queries)가 전부 0매칭일 때만 호출된다(lazy —
|
||||
PRISM 설계 계승). 룰이 못 하는 것을 보강한다: 조달식 표기의 시판 검색어 번역,
|
||||
상품명에 없는 모델명·규격 재구성 (예: "스탠리 텀블러" → "스탠리 퀜처 887ml").
|
||||
"""
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
_SYSTEM = (
|
||||
"너는 커머스 검색어 생성기다. 상품 정보를 받아 쇼핑몰 검색창에 넣을 한국어 검색어 2개를 만든다.\n"
|
||||
"- precise: 모델명(있으면 최우선)과 핵심 규격(용량/사이즈/개입 등)을 포함한 정밀 검색어. "
|
||||
"동일 상품을 정확히 찾기 위함. 일반 카테고리 단어만 나열하지 말 것.\n"
|
||||
"- broad: 핵심 상품 명사(브랜드+제품군) 위주의 광역 검색어. precise 가 0건일 때 폭넓게 찾기 위함. "
|
||||
"사내·조달식 표기는 소비자 쇼핑몰에서 통용되는 표현으로 바꿀 것.\n"
|
||||
"검색어에 따옴표/특수문자/불필요한 수식어를 넣지 말 것."
|
||||
)
|
||||
|
||||
|
||||
class Keywords(BaseModel):
|
||||
precise: str = Field(description="모델/규격 포함 정밀 검색어")
|
||||
broad: str = Field(description="핵심 명사 위주 광역 검색어")
|
||||
|
||||
|
||||
class KeywordGenerator:
|
||||
def __init__(self, api_key: str, model: str = "gpt-4o-mini"):
|
||||
self._model = model
|
||||
self._client = AsyncOpenAI(api_key=api_key)
|
||||
|
||||
async def generate(self, target: dict) -> Keywords:
|
||||
user = (
|
||||
f"상품명: {target.get('product_name', '')}\n"
|
||||
f"모델: {target.get('model', '')}\n"
|
||||
f"규격: {target.get('specification', '')}\n"
|
||||
f"제조사/브랜드: {target.get('company', '')}"
|
||||
)
|
||||
resp = await self._client.beta.chat.completions.parse(
|
||||
model=self._model,
|
||||
messages=[{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content": user}],
|
||||
response_format=Keywords,
|
||||
temperature=0,
|
||||
)
|
||||
return resp.choices[0].message.parsed or Keywords(precise="", broad="")
|
||||
@@ -0,0 +1,107 @@
|
||||
"""로컬 텍스트 검증 판정기 — LLM 없이 '찾는 상품과 동일한 상품'인지 판별.
|
||||
|
||||
계획서 평가방법("텍스트 정보 검증 프로세스")의 로컬 구현. SimilarityJudge(AI)와
|
||||
동일한 인터페이스(judge)로 교체 가능하다 — capture_local --judge local|ai.
|
||||
|
||||
판정 규칙 (AI 판정기의 시스템 프롬프트 규칙을 결정적 룰로 옮김):
|
||||
1. 규격 충돌 = 불일치: 타겟 이름의 수량·용량 토큰(숫자+단위)과 같은 단위의
|
||||
다른 값이 후보에 있으면 다른 상품 (예: 3.3kg vs 1.5kg, 30롤 vs 60롤)
|
||||
2. 토큰 커버리지 = 유사도: 타겟 이름 토큰(정규화)이 후보 이름에 포함된 비율.
|
||||
숫자·모델 토큰은 가중 2배 (모델명 일치 우선 원칙)
|
||||
3. is_match = 규격 충돌 없음 AND score ≥ 임계값(기본 70)
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from prism_core.contract import NormalizedProduct
|
||||
from prism_core.util import norm_token
|
||||
|
||||
# 수량·용량 토큰: 숫자+단위 (규격 비교의 기본 단위)
|
||||
_UNITS = (r"kg|mg|g|ml|l|리터|cc|cm|mm|m|인치|inch|롤|팩|매|장|개입|개|입|p|ea|호|권|족|"
|
||||
r"박스|box|세트|set|kw|w|v|a|ah|mah|gb|tb|mb")
|
||||
_SPEC_RE = re.compile(rf"(\d+(?:[.,]\d+)?)\s*({_UNITS})(?![a-z가-힣])", re.IGNORECASE)
|
||||
_NUM_TOKEN_RE = re.compile(r"\d")
|
||||
|
||||
# 상품 동일성과 무관한 수식어 — 커버리지 분모에서 제외 (판매 문구·상태 표기)
|
||||
_STOPWORDS = {
|
||||
"정품", "새상품", "신형", "구형", "최신형", "국산", "국내산", "수입", "무료배송",
|
||||
"당일발송", "당일출고", "사은품", "증정", "벌크", "낱개", "박스", "묶음", "행사",
|
||||
"특가", "세일", "할인", "인기", "추천", "고급", "프리미엄", "옵션", "택1", "모음",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Judgment:
|
||||
"""SimilarityJudge.Judgment 와 동형 (index 1부터, is_match, score 0~100)."""
|
||||
index: int
|
||||
is_match: bool
|
||||
score: int
|
||||
|
||||
|
||||
def _norm_unit(unit: str) -> str:
|
||||
u = unit.lower()
|
||||
return {"리터": "l", "cc": "ml", "inch": "인치", "box": "박스", "set": "세트",
|
||||
"입": "개입", "ea": "개"}.get(u, u)
|
||||
|
||||
|
||||
def _specs(text: str) -> dict:
|
||||
"""텍스트에서 {단위: {값,...}} 추출. '3.3kg' → {'kg': {3.3}}"""
|
||||
out: dict = {}
|
||||
for num, unit in _SPEC_RE.findall((text or "").lower().replace(",", "")):
|
||||
try:
|
||||
v = float(num)
|
||||
except ValueError:
|
||||
continue
|
||||
out.setdefault(_norm_unit(unit), set()).add(v)
|
||||
return out
|
||||
|
||||
|
||||
def _tokens(text: str) -> list:
|
||||
toks = [norm_token(t) for t in (text or "").split() if norm_token(t)]
|
||||
return [t for t in toks if t not in _STOPWORDS]
|
||||
|
||||
|
||||
def score_candidate(target_text: str, candidate_name: str) -> tuple:
|
||||
"""(score 0~100, 규격충돌 여부). 타겟 토큰의 후보 내 커버리지 기반."""
|
||||
t_specs = _specs(target_text)
|
||||
c_specs = _specs(candidate_name)
|
||||
# 규격 충돌: 같은 단위에서 타겟 값이 후보에 하나도 없고 후보에 다른 값이 있으면 불일치
|
||||
for unit, t_vals in t_specs.items():
|
||||
c_vals = c_specs.get(unit)
|
||||
if c_vals and not (t_vals & c_vals):
|
||||
return 0, True
|
||||
|
||||
t_toks = _tokens(target_text)
|
||||
if not t_toks:
|
||||
return 0, False
|
||||
c_join = norm_token((candidate_name or "").replace(" ", ""))
|
||||
|
||||
got = total = 0
|
||||
for tok in t_toks:
|
||||
# 숫자 포함 토큰(모델·규격)은 가중 2배 — 모델 일치 우선
|
||||
w = 2 if _NUM_TOKEN_RE.search(tok) else 1
|
||||
total += w
|
||||
if tok in c_join:
|
||||
got += w
|
||||
return int(100 * got / total), False
|
||||
|
||||
|
||||
class LocalJudge:
|
||||
"""텍스트 검증 판정기 — SimilarityJudge 와 동일한 judge() 인터페이스 (async)."""
|
||||
|
||||
def __init__(self, threshold: int = 60):
|
||||
self.threshold = threshold
|
||||
self.last_usage = None # AI 판정기와의 인터페이스 호환 (토큰 사용량 없음)
|
||||
|
||||
async def judge(self, target: dict, candidates: list) -> list:
|
||||
target_text = " ".join(str(target.get(k) or "") for k in
|
||||
("company", "product_name", "model", "specification"))
|
||||
out = []
|
||||
for i, c in enumerate(candidates):
|
||||
name = c.name if isinstance(c, NormalizedProduct) else str(c)
|
||||
score, conflict = score_candidate(target_text, name)
|
||||
out.append(Judgment(index=i + 1,
|
||||
is_match=(not conflict) and score >= self.threshold,
|
||||
score=score))
|
||||
return out
|
||||
@@ -0,0 +1,63 @@
|
||||
"""가격 이상치 제거.
|
||||
|
||||
레퍼런스는 반복 z-score(정규분포 가정)를 썼으나, 가격 분포는 한쪽으로 치우친(로그정규) 경우가
|
||||
많아 취약하다. 대신 분포 가정이 없는 **IQR(사분위 범위) 방식**을 쓴다(stdlib 만, numpy 불필요).
|
||||
목적: '엉뚱한 초저가(액세서리/오매칭)·초고가(묶음)'가 최저가 산정을 오염시키는 것을 막는다.
|
||||
"""
|
||||
|
||||
import statistics
|
||||
|
||||
from prism_core.contract import NormalizedProduct
|
||||
|
||||
|
||||
def iqr_band(prices: list[int], k: float = 1.5, floor_ratio: float = 0.25) -> dict:
|
||||
"""가격 목록의 IQR 밴드와 사분위수를 낸다(순수 함수).
|
||||
|
||||
화면이 '무엇이 왜 잘렸는지'를 그리려면 잘린 결과뿐 아니라 **판정 기준 자체**가 필요하다.
|
||||
특히 `lo_raw`(원식 하한)와 `lo`(바닥 적용 후)를 **둘 다** 내보내는 게 중요하다 —
|
||||
둘이 다르다는 건 `Q1 - k·IQR` 이 음수로 무력화돼 바닥 방어가 실제로 일한 순간이고,
|
||||
그게 이 프로젝트가 밟았던 지뢰(3,800원 케이스가 최저가로 잡힌 건)의 재발 감시 지점이다.
|
||||
"""
|
||||
q1, med, q3 = statistics.quantiles(prices, n=4)
|
||||
iqr = q3 - q1
|
||||
lo_raw, hi = q1 - k * iqr, q3 + k * iqr
|
||||
lo = max(lo_raw, q1 * floor_ratio)
|
||||
return {
|
||||
"q1": round(q1), "median": round(med), "q3": round(q3), "iqr": round(iqr),
|
||||
"lo": round(lo), "hi": round(hi),
|
||||
"lo_raw": round(lo_raw), # 바닥 적용 전 — 음수면 원식이 무력했다는 뜻
|
||||
"floor_applied": lo > lo_raw, # 바닥이 실제로 하한을 끌어올렸는가
|
||||
"k": k, "floor_ratio": floor_ratio,
|
||||
}
|
||||
|
||||
|
||||
def remove_price_outliers(
|
||||
products: list[NormalizedProduct], k: float = 1.5, min_items: int = 4, floor_ratio: float = 0.25
|
||||
) -> tuple[list[NormalizedProduct], list[NormalizedProduct]]:
|
||||
"""IQR 기반 이상치 제거. [Q1 - k·IQR, Q3 + k·IQR] 밖을 제거.
|
||||
데이터가 min_items 미만이면 통계가 무의미하므로 그대로 통과. (kept, removed) 반환."""
|
||||
prices = [p.price for p in products if p.price and p.price > 0]
|
||||
if len(prices) < min_items:
|
||||
return list(products), []
|
||||
|
||||
# ── 하한 방어 (선행 프로젝트에서 실측된 버그) — iqr_band 안에서 적용된다 ──────
|
||||
# 가격이 넓게 퍼지면 IQR 이 커져 `Q1 - 1.5·IQR` 이 **음수**가 된다. 음수 하한은
|
||||
# 어떤 가격도 걸러내지 못하므로 초저가 방어가 통째로 죽는다 — '갤럭시 s6' 검색에
|
||||
# 3,800원짜리 **케이스**가 살아남아 최저가로 잡혔다(정상대 36,660~152,400).
|
||||
#
|
||||
# 최저가 관점에서 위험한 쪽은 항상 아래다(싼 오매칭이 답을 통째로 망친다). 그래서
|
||||
# 하한이 무력해지면 Q1 의 일정 비율을 바닥으로 깐다. 상한은 그대로 둔다 —
|
||||
# 비싼 묶음상품은 최저가를 오염시키지 않아 굳이 잘라낼 이유가 없다.
|
||||
#
|
||||
# 실측(2026-08-10, 맥심 커피 5몰 456건): 원식 하한 -16,296원 → 바닥 적용 7,520원.
|
||||
# 음수였으므로 이 방어가 없었다면 5,090원짜리 '20개입'(찾는 건 180개입)이 살아남는다.
|
||||
band = iqr_band(prices, k, floor_ratio)
|
||||
lo, hi = band["lo"], band["hi"]
|
||||
|
||||
kept, removed = [], []
|
||||
for p in products:
|
||||
if p.price is None or lo <= p.price <= hi:
|
||||
kept.append(p)
|
||||
else:
|
||||
removed.append(p)
|
||||
return kept, removed
|
||||
@@ -0,0 +1,89 @@
|
||||
"""prism 서비스 의존성 대체 셤 — 성능측정 자립 실행용.
|
||||
|
||||
원본(prism/backend)의 common/logger · services/access/{decodo,http} · config/server_configs 를
|
||||
프록시·설정 시스템 없이 같은 계약으로 제공한다. 측정 환경은 직결(무프록시)이 기본이다.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import httpx
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(message)s")
|
||||
_log = logging.getLogger("prism_core")
|
||||
|
||||
|
||||
class _Log:
|
||||
def d(self, msg): _log.debug(msg)
|
||||
def i(self, msg): _log.info(msg)
|
||||
def w(self, msg): _log.warning(msg)
|
||||
def e(self, msg): _log.error(msg)
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
|
||||
|
||||
class DecodoProxy:
|
||||
"""프록시 미사용 셤 — 원본과 같은 시그니처, 항상 직결."""
|
||||
|
||||
def __init__(self, owner: str = ""):
|
||||
self.enabled = False
|
||||
|
||||
def rotate(self, reason: str = ""):
|
||||
pass
|
||||
|
||||
def proxy_url(self):
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FetchResult:
|
||||
status: int
|
||||
html: str
|
||||
nbytes: int
|
||||
|
||||
|
||||
_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
|
||||
"Accept-Language": "ko-KR,ko;q=0.9,en;q=0.8",
|
||||
}
|
||||
|
||||
|
||||
class ProxiedHttpClient:
|
||||
"""직결 httpx 셤 — 원본과 같은 fetch 계약(FetchResult 반환), 프록시·회전은 no-op."""
|
||||
|
||||
def __init__(self, proxy=None, *, timeout_sec: float = 12.0,
|
||||
use_proxy: bool = True, rotate_per_request: bool = True):
|
||||
self._timeout = timeout_sec
|
||||
|
||||
@property
|
||||
def uses_proxy(self) -> bool:
|
||||
return False
|
||||
|
||||
def rotate(self, reason: str = "rotate"):
|
||||
pass
|
||||
|
||||
def session_proxy_url(self):
|
||||
return None
|
||||
|
||||
async def fetch(self, url: str) -> FetchResult:
|
||||
async with httpx.AsyncClient(headers=_HEADERS, timeout=self._timeout,
|
||||
follow_redirects=True) as c:
|
||||
r = await c.get(url)
|
||||
return FetchResult(status=r.status_code, html=r.text, nbytes=len(r.content))
|
||||
|
||||
|
||||
class _OpenAIConfig:
|
||||
"""환경변수 직결 — 실행환경/.env 는 capture_local.py 가 로드한다."""
|
||||
|
||||
@property
|
||||
def api_key(self) -> str:
|
||||
return os.getenv("OPENAI_API_KEY", "")
|
||||
|
||||
@property
|
||||
def model(self) -> str:
|
||||
return os.getenv("OPENAI_MODEL_JUDGE", "gpt-4o-mini")
|
||||
|
||||
|
||||
openai_config = _OpenAIConfig()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""AI 유사도 판정 — 검색 결과가 '찾는 상품과 동일한 상품'인지 OpenAI 로 판별.
|
||||
|
||||
파이프라인(이상치 제거 뒤, top-N 앞) 슬롯에 결합한다. 규칙 고정 파싱이 취약한 문제를
|
||||
LLM 판단으로 대체 — 액세서리/호환부품/다른 상품/명백히 다른 규격을 걸러 최저가 오염을 막는다.
|
||||
structured output(Pydantic)으로 정규식 파싱 없이 안정적으로 결과를 받는다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prism_core.shims import LOG
|
||||
from prism_core.shims import openai_config
|
||||
from prism_core.contract import NormalizedProduct
|
||||
|
||||
# 규칙은 '무시할 차이'와 '불일치로 볼 차이'로 갈라 쓴다. 예전엔 "포장(개수/박스) 차이는 동일"과
|
||||
# "용량·규격이 다르면 불일치"가 함께 있어 '30롤 1팩' vs '30롤 2팩'(=60롤)을 어느 쪽으로 볼지
|
||||
# 모델이 정할 수 없었다. 최저가 관점에선 수량이 다르면 다른 상품이다(60롤 값을 30롤 최저가로
|
||||
# 쓰면 왜곡). 종류 혼동(프라이팬/볶음팬/웍팬)도 실측에서 오탐을 만들어 명시한다.
|
||||
_SYSTEM = (
|
||||
"너는 최저가 비교 시스템의 상품 매칭기다. 후보가 '찾는 상품과 동일한 상품'인지 판별하라.\n"
|
||||
"동일하다고 보는 차이(무시할 것):\n"
|
||||
"- 판매자·스토어, 색상/향, 사은품·증정품, 배송 문구, 상품명 수식어(무형광·프리미엄 등)\n"
|
||||
"불일치로 보는 차이:\n"
|
||||
"- 종류가 다름: 프라이팬 / 볶음팬 / 웍팬 / 냄비는 서로 다른 종류다. 세트 구성품도 단품과 다르다\n"
|
||||
"- 브랜드·모델이 다름(모델명이 주어지면 모델 일치를 우선)\n"
|
||||
"- 용량·크기가 다름(ml·L·g·cm)\n"
|
||||
"- 수량이 다름: 개입·롤수·팩수. 예) '30롤 1팩'과 '30롤 2팩'(=60롤)은 다른 상품이다\n"
|
||||
"- 액세서리·호환부품(뚜껑·손잡이·거치대·리필 전용 부속 등)\n"
|
||||
"- 같은 브랜드의 다른 제품 라인/시리즈(예: One Touch 와 Expansion)는 불일치다\n"
|
||||
"- 등급/에디션 차이(Pro·SE·플러스·라이트 등)는 다른 상품이다\n"
|
||||
"score 앵커:\n"
|
||||
"- 100 = 브랜드·모델·라인·등급·규격이 전부 확인됨 (표기 흔들림만 다름)\n"
|
||||
"- 90 = 모델은 같은데 후보 이름에 명시되지 않은 축이 하나 있음\n"
|
||||
"- 70 이하 = 같은 브랜드/카테고리지만 모델 또는 라인이 다르다\n"
|
||||
"후보 이름에 모델명이 아예 없으면 절대 90 이상을 주지 마라."
|
||||
)
|
||||
|
||||
# 한 번에 판정할 후보 수. **크면 판정이 통째로 무너진다** — 실측(2026-08-05): 후보 37건을 일괄로
|
||||
# 넣으면 gpt-4o-mini 가 전 항목에 같은 점수(70)를 매기고 전부 불일치로 답한다(3회 재현).
|
||||
# 10건씩 나누면 같은 입력·같은 모델로 12건이 매칭됐다(0건 → 12건). 상품 3종에서 모두 재현.
|
||||
_BATCH = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Usage:
|
||||
"""배치 여러 개의 토큰을 합쳐 계측부(metrics.add_ai)에 하나로 넘긴다."""
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
|
||||
|
||||
class Judgment(BaseModel):
|
||||
index: int = Field(description="후보 번호(1부터)")
|
||||
is_match: bool = Field(description="찾는 상품과 동일 상품이면 true")
|
||||
score: int = Field(description="동일 확신도 0~100")
|
||||
|
||||
|
||||
class JudgmentList(BaseModel):
|
||||
judgments: list[Judgment]
|
||||
|
||||
|
||||
class SimilarityJudge:
|
||||
def __init__(self, model: str | None = None, api_key: str | None = None):
|
||||
self._model = model or openai_config.model
|
||||
self._client = AsyncOpenAI(api_key=api_key or openai_config.api_key)
|
||||
self.last_usage = None # 직전 호출 토큰 usage(계측용) — 호출부가 await 직후 읽는다
|
||||
|
||||
async def judge(self, target: dict, candidates: list[NormalizedProduct]) -> list[Judgment]:
|
||||
"""후보별 동일상품 여부 판정. candidates 와 같은 순서/길이로 Judgment 리스트 반환.
|
||||
|
||||
후보를 _BATCH 단위로 쪼개 **병렬**로 묻고 합친다(지연은 배치 1개분). 쪼개는 이유는
|
||||
속도가 아니라 정확도다 — 위 _BATCH 주석의 실측 참고.
|
||||
"""
|
||||
self.last_usage = None
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
chunks = [candidates[i:i + _BATCH] for i in range(0, len(candidates), _BATCH)]
|
||||
results = await asyncio.gather(*(self._judge_batch(target, ch) for ch in chunks))
|
||||
|
||||
out: list[Judgment] = []
|
||||
prompt = completion = 0
|
||||
for offset, (judgments, usage) in zip(range(0, len(candidates), _BATCH), results):
|
||||
for k in range(len(chunks[offset // _BATCH])):
|
||||
j = judgments.get(k + 1)
|
||||
# 배치 안 번호(1..n)를 전체 번호로 되돌린다. 누락은 보수적으로 불일치.
|
||||
out.append(Judgment(index=offset + k + 1,
|
||||
is_match=bool(j and j.is_match), score=j.score if j else 0))
|
||||
prompt += getattr(usage, "prompt_tokens", 0) or 0
|
||||
completion += getattr(usage, "completion_tokens", 0) or 0
|
||||
self.last_usage = _Usage(prompt, completion)
|
||||
LOG.d(f"[ai] 판정 {len(candidates)}건({len(chunks)}배치) 중 매칭 {sum(1 for j in out if j.is_match)}건")
|
||||
return out
|
||||
|
||||
async def _judge_batch(self, target: dict, candidates: list[NormalizedProduct]):
|
||||
"""배치 1개 판정 → ({배치내 index: Judgment}, usage)."""
|
||||
lines = "\n".join(f"{i + 1}. {c.name} ({c.price}원)" for i, c in enumerate(candidates))
|
||||
user = (
|
||||
f"[찾는 상품]\n"
|
||||
f"상품명: {target.get('product_name', '')}\n"
|
||||
f"모델: {target.get('model', '')}\n"
|
||||
f"규격: {target.get('specification', '')}\n"
|
||||
f"제조사/브랜드: {target.get('company', '')}\n\n"
|
||||
f"[검색 결과 후보]\n{lines}\n\n"
|
||||
f"각 후보가 찾는 상품과 동일 상품인지 index 별로 판별하라."
|
||||
)
|
||||
|
||||
resp = await self._client.beta.chat.completions.parse(
|
||||
model=self._model,
|
||||
messages=[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": user}],
|
||||
response_format=JudgmentList,
|
||||
temperature=0,
|
||||
)
|
||||
parsed = resp.choices[0].message.parsed
|
||||
return {j.index: j for j in (parsed.judgments if parsed else [])}, getattr(resp, "usage", None)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""검색 어댑터 공용 순수 유틸(부작용 없음). 레퍼런스의 parse_price 를 정리 이식."""
|
||||
|
||||
import re
|
||||
|
||||
_NUM = re.compile(r"[\d,]+")
|
||||
_WON = re.compile(r"([\d,]+)\s*원") # '원' 바로 앞 숫자(단위가격/퍼센트 오인 방지)
|
||||
_NUM3 = re.compile(r"([\d,]{3,})") # 3자리+ 숫자 토큰(가격 후보)
|
||||
_SHIP_FEE = re.compile(r"배송비\s*([\d,]+)\s*원")
|
||||
_LABELS = ("상품명", "브랜드명", "판매가", "할인가") # 오픈마켓 카드의 a11y 라벨 프리픽스
|
||||
|
||||
|
||||
def parse_price(value) -> int | None:
|
||||
"""'44,900원', 44900, '44.900' 등 다형 입력 → int. 실패 시 None."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
m = _NUM.search(str(value))
|
||||
if not m:
|
||||
return None
|
||||
digits = m.group(0).replace(",", "")
|
||||
return int(digits) if digits.isdigit() else None
|
||||
|
||||
|
||||
def extract_price(text: str) -> int | None:
|
||||
"""가격 노드 텍스트 → int. '원' 앵커 우선, 없으면 첫 3자리+ 숫자.
|
||||
('1%할인가44,540원' → 44540, '44,540' → 44540). 실패 시 None."""
|
||||
if not text:
|
||||
return None
|
||||
m = _WON.search(text)
|
||||
if m:
|
||||
return int(m.group(1).replace(",", ""))
|
||||
m = _NUM3.search(text)
|
||||
return int(m.group(1).replace(",", "")) if m else None
|
||||
|
||||
|
||||
def clean_name(text: str) -> str:
|
||||
"""오픈마켓 카드 이름에서 a11y 라벨('상품명'/'브랜드명' 등) 프리픽스를 제거."""
|
||||
s = (text or "").strip()
|
||||
for lab in _LABELS:
|
||||
s = s.replace(lab, " ")
|
||||
return re.sub(r"\s+", " ", s).strip()
|
||||
|
||||
|
||||
def shipping_from_text(text: str, name: str | None = None) -> tuple[int | None, str | None]:
|
||||
"""카드 텍스트에서 (배송비, 배송유형) 추출 — 오픈마켓 공용(로켓 없음).
|
||||
'무료배송'→(0,'free'), '배송비 X원'→(X,'paid'), 그 외 (None, None).
|
||||
상품명에 '무료배송'이 들어간 오탐 방지를 위해 이름 제거 후 매칭."""
|
||||
t = text or ""
|
||||
if name:
|
||||
t = t.replace(name, " ")
|
||||
if "무료배송" in t:
|
||||
return 0, "free"
|
||||
m = _SHIP_FEE.search(t)
|
||||
if m:
|
||||
return int(m.group(1).replace(",", "")), "paid"
|
||||
return None, None
|
||||
|
||||
|
||||
def parse_ko_count(text: str) -> int | None:
|
||||
"""'1.7만'→17000 · '3,705'→3705 · '1.2천'→1200 · ''→None.
|
||||
|
||||
네이버는 리뷰·구매 수를 만/천 단위로 줄여 쓴다. 그대로 int() 하면 1.7만이 1이 된다.
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
t = text.strip().replace(",", "")
|
||||
m = re.match(r"^([\d.]+)\s*([만천])?$", t)
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
n = float(m.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
unit = {"만": 10000, "천": 1000}.get(m.group(2) or "", 1)
|
||||
return int(n * unit)
|
||||
|
||||
|
||||
# ── 검색어 조합 ─────────────────────────────────────────────────────────────
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
|
||||
def norm_token(t: str) -> str:
|
||||
"""비교용 정규화 — 대소문자·공백·괄호류를 지운다('LG전자' 와 'lg 전자' 를 같게 본다).
|
||||
|
||||
(pipeline/filters.py 의 브랜드 비교도 이 함수를 쓴다 — 정규화 규칙이 두 벌이 되면 안 된다.)"""
|
||||
return re.sub(r"[\s()\[\]{}·,]", "", t).lower()
|
||||
|
||||
|
||||
def build_search_query(payload: dict) -> str:
|
||||
"""상품 입력 → **쇼핑몰 검색창에 넣을 검색어**.
|
||||
|
||||
사람이 검색창에 치는 순서 그대로 조합한다: 제조사 → 상품명 → 모델 → 규격.
|
||||
(현재가는 가격밴드 필터 입력이지 검색어가 아니라 제외한다.)
|
||||
|
||||
⚠️ 왜 상품명만 쓰면 안 되는가 — 2026-08-10 실측:
|
||||
'무선청소기' G마켓 상위 40건 중 LG 0건(0%) ← AI 가 40건 전부를 걸러내야 한다
|
||||
'LG 무선청소기' G마켓 상위 40건 중 LG 38건(95%) ← AI 가 2건만 걸러내면 된다
|
||||
브랜드가 검색어에 없으면 카테고리 전체를 긁어오고, 그러면 AI 가 걸러야 할 양이 폭증한다.
|
||||
걸러야 할 게 많을수록 오탐 확률이 올라가고, **오탐 1건이 하필 싸면 그게 최저가가 된다**
|
||||
(실제로 'LG 무선청소기' 검색에 캐치웰 89,000원이 최저가로 잡혔다).
|
||||
|
||||
좁혀서 0건이 나는 건 괜찮다 — 그건 이 프로젝트가 정직하게 다루는 상태(NO_MATCH·EMPTY)이고,
|
||||
0매칭이면 재정제 라운드가 LLM 으로 넓혀 준다(원본 → 정밀 → 광역).
|
||||
"""
|
||||
parts, seen = [], set()
|
||||
for key in ("company", "product_name", "model", "specification"):
|
||||
raw = (payload.get(key) or "").strip()
|
||||
if not raw:
|
||||
continue
|
||||
for tok in _WS.split(raw):
|
||||
n = norm_token(tok)
|
||||
# 이미 나온 토큰은 건너뛴다 — 상품명에 브랜드가 이미 있으면 'LG LG 무선청소기' 가 된다.
|
||||
if not n or n in seen:
|
||||
continue
|
||||
seen.add(n)
|
||||
parts.append(tok)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def brand_tokens(company: str) -> list[str]:
|
||||
"""브랜드 비교에 쓸 토큰들 — 전체 이름 + 2글자 접두.
|
||||
|
||||
접두를 함께 보는 이유: 상품명은 회사명을 줄여 쓴다. '동서식품' 이 상품명엔
|
||||
'동서)맥심모카골드' 로 나온다 — 전체 일치만 보면 정상 상품을 잘라낸다.
|
||||
"""
|
||||
n = norm_token(company)
|
||||
if not n:
|
||||
return []
|
||||
out = [n]
|
||||
if len(n) > 2:
|
||||
out.append(n[:2])
|
||||
return out
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑥ 상품 최저가 검색 정확도 — 상품일치 검수 집계 평가기 (표준 라이브러리만).
|
||||
|
||||
판정 기준 (확정 2026-08-27, GERI 성적서 선례와 동일): 시스템이 반환한 상품이
|
||||
타겟 상품과 동일 상품인지 **사람 검수(O/X)** — "검색결과 중 상품일치여부만 판단".
|
||||
- 반환 실패(매칭 0건)는 불일치로 집계 (시스템이 답을 못 냈으므로, 보수적)
|
||||
- 미검수 행도 불일치로 집계하되 개수를 병기 (전건 검수가 완료돼야 확정치)
|
||||
|
||||
측정 범위 (확정 2026-08-27): 자립형 HTTP 3몰 — danawa·enuri·gsshop
|
||||
(다나와·에누리는 카탈로그형 종합 소스. 브라우저 5몰 확장은 capture_snapshots.py)
|
||||
|
||||
입력 (data/):
|
||||
golden.json 타겟 상품 정보 [{"product_code","product_name"[,"company","model","specification"]}]
|
||||
snapshots/ capture_local.py 산출 몰별 가격표 스냅샷
|
||||
review.csv make_review_sheet.py 생성 후 사람이 일치여부(O/X) 기입한 검수 시트
|
||||
흐름: capture_local.py → make_review_sheet.py → (사람 검수) → python run.py [--target 95]
|
||||
"""
|
||||
import argparse, csv, json
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--target", type=float, default=95.0)
|
||||
ap.add_argument("--review", default=str(HERE / "data" / "review_100.csv"))
|
||||
ap.add_argument("--golden-file", default=str(HERE / "data" / "golden_100.json"),
|
||||
help="측정 모집단 (기본: 타겟 몰 수집 실재 상품 100건)")
|
||||
args = ap.parse_args()
|
||||
golden = json.loads(Path(args.golden_file).read_text(encoding="utf-8"))
|
||||
with open(args.review, encoding="utf-8-sig") as f:
|
||||
review = {r["상품코드"]: r for r in csv.DictReader(f)}
|
||||
|
||||
total = len(golden)
|
||||
match = mismatch = fail = unreviewed = missing = 0
|
||||
detail = []
|
||||
for g in golden:
|
||||
code = g["product_code"]
|
||||
r = review.get(code)
|
||||
if r is None:
|
||||
missing += 1
|
||||
detail.append({"상품코드": code, "구분": "검수시트없음"})
|
||||
continue
|
||||
v = (r.get("일치여부") or "").strip().upper()
|
||||
if v == "O":
|
||||
match += 1
|
||||
gubun = "일치"
|
||||
elif v == "X":
|
||||
mismatch += 1
|
||||
gubun = "불일치"
|
||||
elif v == "반환실패":
|
||||
fail += 1
|
||||
gubun = "반환실패(불일치 집계)"
|
||||
else:
|
||||
unreviewed += 1
|
||||
gubun = "미검수(불일치 집계)"
|
||||
detail.append({"상품코드": code, "검색어": r.get("검색어"),
|
||||
"탐색한_상품명": r.get("탐색한_상품명"), "가격": r.get("가격"),
|
||||
"URL": r.get("URL"), "일치여부": v or None, "구분": gubun})
|
||||
with open(HERE / "detail.jsonl", "w", encoding="utf-8") as f:
|
||||
for d in detail:
|
||||
f.write(json.dumps(d, ensure_ascii=False, default=str) + "\n")
|
||||
|
||||
# 몰별 분포 (측정 범위 명기 정합용 — 결과표에는 URL만, 집계에만 몰 분포)
|
||||
mall_dist = {}
|
||||
for g in golden:
|
||||
sp = HERE / "data" / "snapshots" / f"{g['product_code']}.json"
|
||||
if sp.exists():
|
||||
src = json.loads(sp.read_text(encoding="utf-8")).get("lowest_source")
|
||||
if src:
|
||||
mall_dist[src] = mall_dist.get(src, 0) + 1
|
||||
|
||||
acc = round(100 * match / total, 2) if total else 0.0
|
||||
out = {"판정기준": "반환 상품의 타겟 동일성 사람 검수 (GERI 선례 — 상품일치여부만 판단)",
|
||||
"측정범위": "자립형 HTTP 3몰 (danawa·enuri·gsshop)",
|
||||
"몰별_반환_분포": mall_dist,
|
||||
"total": total, "일치": match, "불일치": mismatch,
|
||||
"반환실패": fail, "미검수": unreviewed, "검수시트없음": missing,
|
||||
"accuracy_pct": acc, "target_pct": args.target,
|
||||
"verdict": "PASS" if acc >= args.target else "FAIL"}
|
||||
if unreviewed or missing:
|
||||
out["주의"] = "미검수/누락 행이 불일치로 집계됨 — 전건 검수 완료 후 확정치"
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 품목별 협상 시나리오 분류 — 자체 라벨링 데이터 구축.
|
||||
|
||||
계획서: "자체 구축한 라벨링 데이터(품목 - 협상 시나리오)에 대한 Classification 결과의 F1-score"
|
||||
|
||||
구축 방식 (2026-08-28 확정, B안):
|
||||
- 품목명: 운용 견적명에서 분리·정제한 실상품명 목록(testdata/product_names.json) 재사용
|
||||
- 라벨: 4분면 룰(testdata/scenario_rule.py — 원본 nego_quadrant_service 중립 재현)로
|
||||
(협상구분, 공급유형, 공급사수, 매출)에서 산출 → Scenario_A/B/C/D
|
||||
- 피처: 품목명 + 협상구분·공급유형·공급사수·매출·품목가격 (실서비스 판정 입력과 동일 계열)
|
||||
- 분할: **품목명 단위 8:2 홀드아웃** (같은 품목이 train/test에 걸치지 않음 — 누수 방지)
|
||||
|
||||
사용: python build_dataset.py [--per-name 6] [--seed 926]
|
||||
출력: data/train.csv, data/test.csv
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
TESTDATA = HERE.parent.parent / "testdata"
|
||||
sys.path.insert(0, str(TESTDATA))
|
||||
|
||||
from scenario_rule import scenario_label # noqa: E402
|
||||
|
||||
|
||||
def log_uniform(rng, lo, hi):
|
||||
import math
|
||||
return math.exp(rng.uniform(math.log(lo), math.log(hi)))
|
||||
|
||||
|
||||
def sample_features(rng: random.Random) -> dict:
|
||||
rq_type = rng.choice(["재협상", "재협상", "재견적"]) # 운용 비중(재협상 2:1 근사)
|
||||
dist = rng.choice(["R", "W", "M"])
|
||||
partners = rng.choice([0, 1, 2, 3, 4, 5])
|
||||
revenue = int(log_uniform(rng, 1_000_000, 100_000_000))
|
||||
item_price = round(log_uniform(rng, 1_000, 2_000_000) / 10) * 10
|
||||
return {"rq_type": rq_type, "dist": dist, "partners": partners,
|
||||
"revenue": revenue, "item_price": item_price}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--per-name", type=int, default=6, help="품목명당 표본 수")
|
||||
ap.add_argument("--seed", type=int, default=926)
|
||||
ap.add_argument("--test-ratio", type=float, default=0.2)
|
||||
args = ap.parse_args()
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
names = json.load(open(TESTDATA / "product_names.json", encoding="utf-8"))["names"]
|
||||
rng.shuffle(names)
|
||||
|
||||
# 품목명 단위 분할 (누수 방지)
|
||||
n_test = int(len(names) * args.test_ratio)
|
||||
test_names = set(names[:n_test])
|
||||
|
||||
(HERE / "data").mkdir(exist_ok=True)
|
||||
fields = ["item_name", "rq_type", "dist", "partners", "revenue", "item_price", "scenario"]
|
||||
counts = {"train": 0, "test": 0}
|
||||
label_dist = {}
|
||||
with open(HERE / "data" / "train.csv", "w", encoding="utf-8-sig", newline="") as ftr, \
|
||||
open(HERE / "data" / "test.csv", "w", encoding="utf-8-sig", newline="") as fte:
|
||||
wtr, wte = csv.DictWriter(ftr, fields), csv.DictWriter(fte, fields)
|
||||
wtr.writeheader(), wte.writeheader()
|
||||
for name in names:
|
||||
for _ in range(args.per_name):
|
||||
feat = sample_features(rng)
|
||||
label = scenario_label(feat["rq_type"], feat["dist"],
|
||||
feat["partners"], feat["revenue"])
|
||||
row = {"item_name": name, **feat, "scenario": label}
|
||||
label_dist[label] = label_dist.get(label, 0) + 1
|
||||
if name in test_names:
|
||||
wte.writerow(row); counts["test"] += 1
|
||||
else:
|
||||
wtr.writerow(row); counts["train"] += 1
|
||||
|
||||
print(json.dumps({"품목명": len(names), "train": counts["train"], "test": counts["test"],
|
||||
"라벨분포": label_dist, "seed": args.seed}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 품목별 협상 시나리오 분류 — 독립 실행 채점기 (표준 라이브러리만).
|
||||
|
||||
입력: data/predictions.csv — 헤더 y_true,y_pred (분류기 test set 예측 결과)
|
||||
사용: python run.py [--input data/predictions.csv] [--target 96]
|
||||
산식: macro-F1 (클래스별 F1 단순 평균) — micro-F1(=accuracy) 병기
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--input", default=str(HERE / "data" / "predictions.csv"))
|
||||
ap.add_argument("--target", type=float, default=96.0)
|
||||
args = ap.parse_args()
|
||||
|
||||
with open(args.input, encoding="utf-8-sig") as f:
|
||||
rows = list(csv.DictReader(f))
|
||||
y_true = [r["y_true"].strip() for r in rows]
|
||||
y_pred = [r["y_pred"].strip() for r in rows]
|
||||
|
||||
tp, fp, fn = defaultdict(int), defaultdict(int), defaultdict(int)
|
||||
with open(HERE / "detail.jsonl", "w", encoding="utf-8") as df:
|
||||
for i, (t, p) in enumerate(zip(y_true, y_pred)):
|
||||
if t == p:
|
||||
tp[t] += 1
|
||||
else:
|
||||
fp[p] += 1
|
||||
fn[t] += 1
|
||||
df.write(json.dumps({"i": i, "y_true": t, "y_pred": p, "정답": t == p},
|
||||
ensure_ascii=False) + "\n")
|
||||
|
||||
per_class, f1s = {}, []
|
||||
for c in sorted(set(y_true) | set(y_pred)):
|
||||
prec = tp[c] / (tp[c] + fp[c]) if tp[c] + fp[c] else 0.0
|
||||
rec = tp[c] / (tp[c] + fn[c]) if tp[c] + fn[c] else 0.0
|
||||
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
|
||||
per_class[c] = {"precision": round(prec, 4), "recall": round(rec, 4),
|
||||
"f1": round(f1, 4), "support": y_true.count(c)}
|
||||
f1s.append(f1)
|
||||
|
||||
macro_f1 = round(100 * sum(f1s) / len(f1s), 2) if f1s else 0.0
|
||||
micro_f1 = round(100 * sum(1 for t, p in zip(y_true, y_pred) if t == p) / len(y_true), 2) \
|
||||
if y_true else 0.0
|
||||
|
||||
out = {
|
||||
"n": len(y_true),
|
||||
"산식": "macro-F1 (클래스별 F1 단순 평균) — 불균형 대비 보수적 채점",
|
||||
"macro_f1_pct": macro_f1,
|
||||
"micro_f1_pct(accuracy)": micro_f1,
|
||||
"클래스별": per_class,
|
||||
"target_pct": args.target,
|
||||
"verdict": "PASS" if macro_f1 >= args.target else "FAIL",
|
||||
}
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 시나리오 분류기 — Pytorch 학습·추론 (평가환경 명시 프레임워크).
|
||||
|
||||
모델: 품목명 문자 임베딩(mean-pool) + 구조 피처 → MLP → 4클래스
|
||||
- 문자 임베딩 32차원, 은닉 64, CrossEntropy, Adam
|
||||
- 시드 고정(재현성), CPU 학습 (수 초 내 수렴)
|
||||
|
||||
사용: python train.py [--epochs 12] [--seed 926]
|
||||
출력: data/predictions.csv (y_true,y_pred — 채점기 run.py 입력), model.pt
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
CLASSES = ["Scenario_A", "Scenario_B", "Scenario_C", "Scenario_D"]
|
||||
DISTS = {"R": 0, "W": 1, "M": 2}
|
||||
RQ_TYPES = {"재협상": 0, "재견적": 1}
|
||||
MAX_NAME_LEN = 40
|
||||
|
||||
|
||||
def load_rows(path):
|
||||
with open(path, encoding="utf-8-sig") as f:
|
||||
return list(csv.DictReader(f))
|
||||
|
||||
|
||||
def build_vocab(rows):
|
||||
chars = set()
|
||||
for r in rows:
|
||||
chars.update(r["item_name"][:MAX_NAME_LEN])
|
||||
vocab = {c: i + 2 for i, c in enumerate(sorted(chars))} # 0=pad, 1=unk
|
||||
return vocab
|
||||
|
||||
|
||||
def encode(rows, vocab):
|
||||
xs_name, xs_feat, ys = [], [], []
|
||||
for r in rows:
|
||||
name = r["item_name"][:MAX_NAME_LEN]
|
||||
ids = [vocab.get(c, 1) for c in name] + [0] * (MAX_NAME_LEN - len(name))
|
||||
xs_name.append(ids)
|
||||
dist_onehot = [0.0, 0.0, 0.0]
|
||||
dist_onehot[DISTS[r["dist"]]] = 1.0
|
||||
rq_onehot = [0.0, 0.0]
|
||||
rq_onehot[RQ_TYPES[r["rq_type"]]] = 1.0
|
||||
# 매출구간: 엔진 상태계(RevenueRange)와 동일한 이산화 — ≤1,000만 / ≤3,000만 / 초과
|
||||
rev = float(r["revenue"])
|
||||
rev_band = [0.0, 0.0, 0.0]
|
||||
rev_band[0 if rev <= 10_000_000 else (1 if rev <= 30_000_000 else 2)] = 1.0
|
||||
xs_feat.append([
|
||||
math.log10(rev),
|
||||
math.log10(float(r["item_price"])),
|
||||
float(r["partners"]) / 5.0,
|
||||
*rev_band, *dist_onehot, *rq_onehot,
|
||||
])
|
||||
ys.append(CLASSES.index(r["scenario"]))
|
||||
return (torch.tensor(xs_name, dtype=torch.long),
|
||||
torch.tensor(xs_feat, dtype=torch.float32),
|
||||
torch.tensor(ys, dtype=torch.long))
|
||||
|
||||
|
||||
class ScenarioClassifier(nn.Module):
|
||||
def __init__(self, vocab_size, n_feat, emb_dim=32, hidden=64):
|
||||
super().__init__()
|
||||
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(emb_dim + n_feat, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, len(CLASSES)),
|
||||
)
|
||||
|
||||
def forward(self, name_ids, feats):
|
||||
mask = (name_ids != 0).unsqueeze(-1).float()
|
||||
emb = (self.emb(name_ids) * mask).sum(1) / mask.sum(1).clamp(min=1.0)
|
||||
return self.mlp(torch.cat([emb, feats], dim=1))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--epochs", type=int, default=12)
|
||||
ap.add_argument("--batch", type=int, default=128)
|
||||
ap.add_argument("--lr", type=float, default=1e-3)
|
||||
ap.add_argument("--seed", type=int, default=926)
|
||||
args = ap.parse_args()
|
||||
|
||||
random.seed(args.seed)
|
||||
torch.manual_seed(args.seed)
|
||||
|
||||
train_rows = load_rows(HERE / "data" / "train.csv")
|
||||
test_rows = load_rows(HERE / "data" / "test.csv")
|
||||
vocab = build_vocab(train_rows)
|
||||
|
||||
tr_name, tr_feat, tr_y = encode(train_rows, vocab)
|
||||
te_name, te_feat, te_y = encode(test_rows, vocab)
|
||||
|
||||
model = ScenarioClassifier(vocab_size=len(vocab) + 2, n_feat=tr_feat.shape[1])
|
||||
opt = torch.optim.Adam(model.parameters(), lr=args.lr)
|
||||
loss_fn = nn.CrossEntropyLoss()
|
||||
|
||||
n = len(tr_y)
|
||||
for epoch in range(args.epochs):
|
||||
model.train()
|
||||
perm = torch.randperm(n)
|
||||
total = 0.0
|
||||
for i in range(0, n, args.batch):
|
||||
idx = perm[i:i + args.batch]
|
||||
opt.zero_grad()
|
||||
out = model(tr_name[idx], tr_feat[idx])
|
||||
loss = loss_fn(out, tr_y[idx])
|
||||
loss.backward()
|
||||
opt.step()
|
||||
total += loss.item() * len(idx)
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
acc = (model(te_name, te_feat).argmax(1) == te_y).float().mean().item()
|
||||
print(f"epoch {epoch + 1:2d} loss {total / n:.4f} test_acc {acc:.4f}", flush=True)
|
||||
|
||||
# 추론 → 채점기 입력(predictions.csv) 저장
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
preds = model(te_name, te_feat).argmax(1).tolist()
|
||||
with open(HERE / "data" / "predictions.csv", "w", encoding="utf-8-sig", newline="") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["y_true", "y_pred"])
|
||||
for t, p in zip(te_y.tolist(), preds):
|
||||
w.writerow([CLASSES[t], CLASSES[p]])
|
||||
|
||||
torch.save({"state_dict": model.state_dict(), "vocab": vocab,
|
||||
"classes": CLASSES, "seed": args.seed}, HERE / "model.pt")
|
||||
print(json.dumps({"train": len(train_rows), "test": len(test_rows),
|
||||
"vocab": len(vocab), "torch": torch.__version__,
|
||||
"출력": "data/predictions.csv, model.pt"}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑩ 실시간 페르소나 정확도 — 집계기 (2026-08-28 확정 설계).
|
||||
|
||||
계획서 산식 그대로:
|
||||
정확도 = 1 − mean(시나리오별 mean(|실제 긴장도 − 예측 긴장도|)) (시나리오 = 협상 세션)
|
||||
|
||||
정의 (확정):
|
||||
- 실제 긴장도 (사후, 하네스 가격 기록으로 산출) = clip((제안가 − 목표가) / (초기제안가 − 목표가))
|
||||
- 예측 긴장도 (서버 실시간 계측) = 단계 변수인 지표점수(1~99 정수)에서 역산한 추정치.
|
||||
이 수치가 페르소나(저/중/고 3구간) 적용에 실제로 사용된다 — 계획서 "수치에 따라 페르소나 적용".
|
||||
지표점수의 정수 양자화 때문에 실제값과 독립적인 오차가 존재한다 (측정 건전성 근거).
|
||||
|
||||
병합: (session_id, iteration) — 서버 로그의 신형 행(persona 필드 보유)만 사용, 중복 키는 최신 우선.
|
||||
|
||||
사용:
|
||||
python aggregate.py --details "../01_win_rate/본측정_20260828/detail_*.jsonl"
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
DEFAULT_TENSION = HERE.parent.parent / "server" / "data" / "tension_log.jsonl"
|
||||
|
||||
|
||||
def clip01(v: float) -> float:
|
||||
return max(0.0, min(1.0, v))
|
||||
|
||||
|
||||
def load_predicted(path: str):
|
||||
"""(session_id, iteration) → {predicted, persona}. 신형 행만, 중복은 최신 우선."""
|
||||
pred = {}
|
||||
for line in Path(path).read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
r = json.loads(line)
|
||||
if "persona" not in r: # 구형(잠정 산식 시절) 행 제외
|
||||
continue
|
||||
pred[(r["session_id"], r["iteration"])] = r
|
||||
return pred
|
||||
|
||||
|
||||
def actual_entries(detail_row: dict):
|
||||
"""하네스 detail 한 건에서 (iteration, 실제 긴장도) 재구성 —
|
||||
동적 스텝 진입(res_step == '가격협상') 시점의 제안가 기준."""
|
||||
target = detail_row.get("target")
|
||||
initial = detail_row.get("initial_offer")
|
||||
if not target or not initial or float(initial) <= float(target):
|
||||
return None # 긴장도 정의 불가 (초기제안가 ≤ 목표가)
|
||||
out = []
|
||||
k = 0
|
||||
for rd in detail_row.get("rounds", []):
|
||||
if rd.get("res_step") == "가격협상" and rd.get("req_price") is not None:
|
||||
actual = clip01((float(rd["req_price"]) - float(target))
|
||||
/ (float(initial) - float(target)))
|
||||
out.append((k, actual))
|
||||
k += 1
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--tension-log", default=str(DEFAULT_TENSION))
|
||||
ap.add_argument("--details", required=True,
|
||||
help="하네스 detail 파일 glob (예: '../01_win_rate/본측정_*/detail_*.jsonl')")
|
||||
ap.add_argument("--target", type=float, default=96.0)
|
||||
args = ap.parse_args()
|
||||
|
||||
pred = load_predicted(args.tension_log)
|
||||
|
||||
session_diffs = {}
|
||||
persona_counter = Counter()
|
||||
matched = missing = undefined_sessions = 0
|
||||
detail_out = []
|
||||
for path in sorted(glob.glob(args.details)):
|
||||
for line in Path(path).read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
row = json.loads(line)
|
||||
if str(row.get("outcome", "")).startswith("오류"):
|
||||
continue
|
||||
entries = actual_entries(row)
|
||||
if entries is None:
|
||||
undefined_sessions += 1
|
||||
continue
|
||||
session = f"EVAL-{row['case_id']}"
|
||||
for k, actual in entries:
|
||||
p = pred.get((session, k))
|
||||
if p is None:
|
||||
missing += 1
|
||||
continue
|
||||
matched += 1
|
||||
diff = abs(p["predicted"] - actual)
|
||||
session_diffs.setdefault(session, []).append(diff)
|
||||
persona_counter[p["persona"]] += 1
|
||||
detail_out.append({"session_id": session, "iteration": k,
|
||||
"predicted": p["predicted"], "actual": round(actual, 4),
|
||||
"diff": round(diff, 4), "indicator": p.get("indicator"),
|
||||
"persona": p["persona"]})
|
||||
|
||||
session_means = {s: sum(d) / len(d) for s, d in session_diffs.items()}
|
||||
overall = (sum(session_means.values()) / len(session_means)) if session_means else None
|
||||
accuracy_pct = round(100 * (1 - overall), 2) if overall is not None else None
|
||||
|
||||
out = {
|
||||
"산식": "1 − mean(시나리오별 mean(|실제 − 예측|)) — 계획서 원문 산식 (시나리오=세션)",
|
||||
"예측": "서버 실시간: 지표점수(1~99)→긴장도 역산 추정치 (페르소나 적용에 사용된 수치)",
|
||||
"실제": "사후: clip((제안가−목표가)/(초기제안가−목표가)) — 하네스 가격 기록 기준",
|
||||
"표본": {"세션": len(session_means), "매칭": matched, "미매칭": missing,
|
||||
"정의불가_세션(초기제안가≤목표가)": undefined_sessions},
|
||||
"페르소나_적용분포": dict(persona_counter),
|
||||
"accuracy_pct": accuracy_pct,
|
||||
"target_pct": args.target,
|
||||
"verdict": ("PASS" if accuracy_pct is not None and accuracy_pct >= args.target
|
||||
else "FAIL"),
|
||||
}
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
with open(HERE / "detail.jsonl", "w", encoding="utf-8") as f:
|
||||
for r in detail_out:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user