⑧ 최저가 탐색 개선 + 로컬 측정 산출물 정리

■ ⑧ 개선 (89/100, 오매칭 0건 — 목표 95% 미달, 1,000건 골든셋 확보 후 재측정 예정)
- gsshop.py: 2026-09-07 사이트 개편 대응. 서버렌더 article.prd-item 카드가
  사라지고 스크립트 내 prdList JSON 으로 바뀌어, 09-01부터 200 응답에 0건을
  반환하며 조용히 2몰로 돌고 있었다. JSON 을 직접 읽도록 재작성하고,
  prdList 배열 자체가 없으면 경고 로그를 남겨 같은 사고를 재발 방지.
- identity.py: 브랜드 별칭 4쌍(sony·bose·canon·pilot) — 정답 후보가 AI 100점을
  받고도 brand veto 단독으로 죽던 건. 더해 veto 3종 신설:
  accessory(본품↔시계줄·보호필름), condition(중고·전시), qty(묶음↔단품).
  '호환'·'보호'는 제외 — 키워드 나열형 정품 상품명을 오폭한다.
- 측정 경과: 83 → 90(오매칭 6 포함) → 89(오매칭 0). 실질 84 → 89.
  본측정_azure_20260907{,_수정전,_게이트강화전}/ 에 3단계 결과 보존.

■ 로컬 측정 산출물 23개 삭제
②③⑥⑦⑨⑩의 result.json·meta.json·detail.jsonl·predictions.csv.
정본 수치는 results/ 에, 원본은 Azure VM 에 있고 집계기 재실행으로 복원된다.
본측정* 폴더(①⑧⑨ 원자료)와 입력 데이터는 유지.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014sLpiFCT7Lj78iLwPbVx7a
This commit is contained in:
민헌andClaude Opus 5 committed 2026-09-07 15:49:53 +09:00
1 parent 97aeff6ac4
commit 9b2f49eb40
31 files changed
+5071 -5631

No files matched your search

+52 -37
View File
@@ -5,20 +5,21 @@ Product(name·brand·offers.price·image)로 온다. 주의: GS샵은 홈쇼핑
(단독 구성)이 많아, 읽은 상품이 다른 몰에 없는 게 정상일 수 있다 — 그건 파서가
아니라 검색 결과(NO_MATCH)가 말할 사실이다.
검색은 **모바일 표면**(m.gsshop.com/search/searchSect.gs)을 쓴다 — PC 검색 경로는
405 를 주지만 모바일은 article.prd-item 카드가 서버렌더로 온다(브랜드·판매가·배송·
평점·상품평 수까지). 직영몰이라 mall_name 은 "GS샵" 고정이다.
검색은 **모바일 표면**(m.gsshop.com/search/searchSect.gs)을 쓴다 — PC 검색 경로는 405 다.
2026-09-07 개편으로 서버렌더 article.prd-item 카드가 사라지고 스크립트에 박힌 `prdList`
JSON 배열로 바뀌었다(브랜드·판매가·평점·상품평 수까지 구조화되어 옴). 마크업 변경에
둔감하도록 JSON 을 직접 읽는다. 직영몰이라 mall_name 은 "GS샵" 고정이다.
"""
import json
import logging
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
from prism_core.util import parse_price
_PRDID = re.compile(r"[?&]prdid=(\d+)")
@@ -45,45 +46,59 @@ def parse(html: str, url: str) -> ResolvedProduct | None:
# ── 검색 ────────────────────────────────────────────────────────────────────
_SEARCH_URL = "https://m.gsshop.com/search/searchSect.gs?tq={q}"
_RATING = re.compile(r"([\d.]+)\s*점")
_REVIEWS = re.compile(r"\(([\d,]+)\s*건\)")
_PRDLIST = re.compile(r'"prdList"\s*:\s*\[')
_log = logging.getLogger(__name__)
def _prdlist(html: str) -> list[dict] | None:
"""스크립트에 박힌 `"prdList": [...]` 배열을 대괄호 균형으로 잘라 파싱.
None = 배열 자체를 못 찾음(구조 변경 의심), [] = 검색 결과가 없음."""
m = _PRDLIST.search(html)
if not m:
return None
start = html.index("[", m.start())
depth = 0
for i in range(start, len(html)):
if html[i] == "[":
depth += 1
elif html[i] == "]":
depth -= 1
if depth == 0:
try:
items = json.loads(html[start:i + 1])
except ValueError:
return None
return [x for x in items if isinstance(x, dict)]
return None
def parse_search(html: str) -> list[NormalizedProduct]:
"""모바일 검색의 article.prd-item 카드 → NormalizedProduct."""
"""모바일 검색의 prdList JSON → NormalizedProduct."""
items = _prdlist(html)
if items is None:
# 200 응답인데 배열조차 없으면 사이트 개편을 의심해야 한다
# — 조용히 2몰로 도는 사고(2026-09-01~07 실측) 방지
_log.warning("gsshop prdList 없음 (응답 %d바이트) — 페이지 구조 변경 가능성", len(html))
return []
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:
for item in items:
price = item.get("salePrice") or item.get("basePrice")
name = str(item.get("productName") or "").strip()
if not price or not name:
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")
brand = str(item.get("brandNm") or "").strip()
rating = item.get("reviewAverage")
reviews = item.get("reviewCount")
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,
name=f"{brand} {name}".strip(),
price=int(price),
detail_url=(item.get("linkUrl") or "") or None,
external_id=str(item["productCd"]) if item.get("productCd") else None,
image_url=(item.get("imageUrl") or "") or 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,
rating=float(rating) if isinstance(rating, (int, float)) and rating else None,
review_count=int(reviews) if isinstance(reviews, (int, float)) else None,
))
return out
@@ -28,6 +28,8 @@ _BRAND_PAIRS = [
("3m", "쓰리엠"), ("anker", "앤커"), ("corsair", "커세어"),
("epson", "엡손"), ("sandisk", "샌디스크"), ("cuckoo", "쿠쿠"),
("balmuda", "발뮤다"), ("hp", "에이치피"), ("aula", "아울라"),
# 2026-09-07 추가 — 정답 후보(AI 100점)가 brand veto 단독으로 죽던 4건
("sony", "소니"), ("bose", "보스"), ("canon", "캐논"), ("pilot", "파이롯트"),
]
_BRAND_ALIASES: dict = {}
for _en, _ko in _BRAND_PAIRS:
@@ -49,6 +51,17 @@ _VARIANTS_KO = {v for v in _VARIANT_CANON if not v.isascii()}
# 한국어 수량·등급 접미 표현 — 숫자+접미 전체일치면 규격으로 분류 (모델 토큰 아님):
# '2세대'·'6인용'·'12캔'·'1급' 이 모델로 오분류되면 표기 생략 후보가 전부 죽는다.
_KO_COUNT_RE = re.compile(r"^\d+(세대|인용|캔|급|단|구|도|번|차)$")
# 본품 검색에 딸려 오는 부속품 어휘 — 타겟에 없고 후보에만 있으면 다른 물건이다.
# (2026-09-07 실측: 애플워치 SE → '메탈 스트랩 … 시계줄', K380 키보드 → '외부보호필름 세트')
# '호환'·'보호'는 넣지 않는다 — '높은호환성' 같은 키워드 나열형 정품 상품명을 오폭한다.
_ACCESSORY = ("케이스", "커버", "필름", "스트랩", "시계줄", "파우치", "거치대",
"캡슐", "리필", "액세서리")
# 상품 상태 — 신품 최저가를 묻는 지표에서 중고·전시품은 같은 물건이 아니다.
_CONDITION = ("중고", "전시", "리퍼")
# 묶음 수량 — '5개입'을 물었는데 단품이 오면 가격이 몇 분의 일로 집계된다.
# 긴 단위를 먼저 잡아야 '5개입'이 '5개'로 잘리지 않는다.
_QTY_RE = re.compile(r"(\d+)\s*(개입|세트|캔|병|매|포|롤|팩|입|장|개)")
_DIGIT_LETTER_RE = re.compile(r"^\d+[a-z]$") # '4k'·'8k' 류 해상도 표기 — 식별력 없음
@@ -143,6 +156,7 @@ def veto(target_text: str, cand_name: str) -> list[str]:
"""타겟과 후보가 동일 상품일 수 없는 결정적 근거 목록. 빈 리스트 = 통과.
반환 사유: brand / model:<tok> / var-miss:<v> / var-extra:<v> / spec:<unit>
/ accessory:<w> / condition:<w> / qty:<n단위>
"""
reasons = []
cj = _joined(cand_name)
@@ -165,6 +179,19 @@ def veto(target_text: str, cand_name: str) -> list[str]:
if not _variant_present(v, target_text):
reasons.append(f"var-extra:{v}")
for w in _ACCESSORY:
if w in cand_name and w not in target_text:
reasons.append(f"accessory:{w}")
break
for w in _CONDITION:
if w in cand_name and w not in target_text:
reasons.append(f"condition:{w}")
break
t_qty = {n + u for n, u in _QTY_RE.findall(target_text)}
if t_qty and not (t_qty & {n + u for n, u in _QTY_RE.findall(cand_name)}):
reasons.append(f"qty:{sorted(t_qty)[0]}")
t_specs, c_specs = _specs(target_text), _specs(cand_name)
for unit, t_vals in t_specs.items():
c_vals = c_specs.get(unit)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff