"""수집 어댑터 계약 — '어디서 긁어오든 결과 모양은 하나' 를 강제한다. 어댑터는 URL 하나를 받아 RawSource 하나를 돌려준다. 그 안에는 원문과 함께 **출처(source_url)** 가 반드시 들어 있다. 수집된 값이 fact 로 넘어갈 때 출처 없이 넘어가면 그 사실은 검증도 추적도 불가능해지기 때문에, 여기서 구조적으로 막는다(RawSource 가 생성 시점에 모든 fact/media 에 출처를 찍는다). 어댑터를 늘리는 방법은 registry.py 에 등록하는 것뿐이다. 이 파일은 계약만 정의한다. """ from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Optional, Protocol, runtime_checkable from common.enums import LinkChannel, PlaceCategory # ---- 도메인 예외 ----------------------------------------------------------- class CollectError(RuntimeError): """수집 계층 공통 예외.""" class AdapterNotFound(CollectError): """이 URL 을 처리할 어댑터가 없다. → ErrorType.COLLECT_ADAPTER_NOT_FOUND""" class AdapterDisabled(CollectError): """어댑터는 존재하나 이 환경에서 꺼져 있다(법무 검토 전 등). → ErrorType.COLLECT_ADAPTER_DISABLED""" class FetchFailed(CollectError): """가져오기 자체가 실패했다(네트워크·파싱). → ErrorType.COLLECT_FETCH_FAILED""" # ---- 수집 결과 구성요소 ----------------------------------------------------- @dataclass class CollectedFact: """수집된 fact 후보 1건. scope='place' 면 사업장 단위, 'unit' 이면 객실·메뉴·프로그램 단위다. unit 단위는 같은 key 가 단위 수만큼 반복되므로(A동 기준인원 / B동 기준인원) dict 가 아니라 리스트로 모은다. unit_name 은 place.units.name 과 맞춰 매핑하는 힌트다. source_url 은 RawSource 가 생성 시점에 찍어준다 — 비워둔 채로 만들어도 출처 없이 흘러가지 않는다. """ key: str value: Optional[str] scope: str = "place" # place | unit unit_name: Optional[str] = None # scope='unit' 일 때 어느 단위 것인지 source_url: str = "" # RawSource.__post_init__ 이 채운다 def __post_init__(self): if self.scope not in ("place", "unit"): raise CollectError(f"CollectedFact.scope 값 오류: {self.scope} (place|unit)") if self.scope == "unit" and not self.unit_name: raise CollectError(f"unit 스코프 fact 는 unit_name 이 필요하다: key={self.key}") @dataclass class CollectedMedia: """수집된 사진 1장. origin_url 은 ★ 반드시 남긴다 — 크롤링 이미지의 재게시 권리가 미결이라(docs/DECISIONS.md 1-2), 결론에 따라 출처별로 걸러낼 수 있어야 한다. label 은 Gemini Vision 이 확정하기 전의 후보 라벨(페이지에서 주운 캡션 등)일 뿐이다. license 는 **출처가 라이선스를 명시한 경우에만** 채운다(예: TourAPI 의 공공누리 `Type1`/`Type3`). ★ 왜 필요한가 — 공공누리 제3·4유형은 **변경 금지**다. 크롭·리사이즈도 변형에 해당할 수 있어 썸네일을 만들면 조건을 어긴다. 어느 사진이 손대면 안 되는 사진인지는 수집 시점에만 알 수 있으므로 여기서 들고 나간다. 값이 None 이면 '라이선스 미상' 이며, 재게시 판단은 여전히 1-2 결론을 따른다. """ origin_url: str label: Optional[str] = None unit_name: Optional[str] = None source_url: str = "" # RawSource.__post_init__ 이 채운다 license: Optional[str] = None # 출처가 밝힌 이용 조건 코드. 미상이면 None def __post_init__(self): if not (self.origin_url or "").strip(): raise CollectError("CollectedMedia.origin_url 이 비었다 — 출처 없는 사진은 담지 않는다") @dataclass class RawSource: """어댑터 1회 수집 결과. ok=False 면 error 만 의미가 있다(facts/media 는 비어 있다). 부분 실패도 결과로 돌려주고 예외를 던지지 않는 것이 기본이다 — 채널 하나가 막혀도 나머지 수집은 이어져야 한다. """ url: str adapter_id: str channel: LinkChannel = LinkChannel.ETC fetched_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc).replace(tzinfo=None)) ok: bool = True error: Optional[str] = None html: Optional[str] = None # 원문(디버깅·재파싱용) text: Optional[str] = None # 태그 걷어낸 본문 facts: list[CollectedFact] = field(default_factory=list) media: list[CollectedMedia] = field(default_factory=list) # ★ 수집 중 **그 채널이 스스로 알려준** 예약 주소. 우리가 만든 주소가 아니다. # 네이버 플레이스 응답의 naverBookingUrl 이 여기 실린다 — 발행본의 "예약" 버튼이 # 플레이스 홈(한 번 더 눌러야 한다)이나 검색 결과가 아니라 예약 화면으로 바로 가게 하는 값. booking_url: Optional[str] = None def __post_init__(self): if not (self.url or "").strip(): raise CollectError("RawSource.url 이 비었다 — 출처 없는 수집 결과는 만들 수 없다") if not (self.adapter_id or "").strip(): raise CollectError("RawSource.adapter_id 가 비었다") # ★ 출처 강제: 개별 항목이 출처를 안 들고 있으면 여기서 찍는다. # fact 로 변환될 때 source_url 이 비면 FACT_SOURCE_REQUIRED 로 거부되므로, # 그 전에 구조가 보장한다. for item in (*self.facts, *self.media): if not item.source_url: item.source_url = self.url @property def source_url(self) -> str: """이 결과 전체의 출처. facts/media 의 source_url 과 같은 값이다.""" return self.url def fact_map(self) -> dict: """사업장 단위 fact 만 {key: value} 로. 단위 스코프는 key 가 겹치므로 제외한다.""" return {f.key: f.value for f in self.facts if f.scope == "place"} def unit_names(self) -> list[str]: """수집된 단위(객실·메뉴·프로그램) 이름 목록 — 등록 순서 유지.""" seen: list[str] = [] for f in self.facts: if f.scope == "unit" and f.unit_name and f.unit_name not in seen: seen.append(f.unit_name) return seen @classmethod def failure(cls, url: str, adapter_id: str, error: str, channel: LinkChannel = LinkChannel.ETC) -> "RawSource": """실패 결과. 호출측이 예외 처리 없이 ok 만 보고 넘어갈 수 있게 한다.""" return cls(url=url, adapter_id=adapter_id, channel=channel, ok=False, error=error) # ---- 어댑터 계약 ----------------------------------------------------------- @runtime_checkable class SourceAdapter(Protocol): """수집 소스 어댑터. id : 레지스트리 키이자 로그 식별자 can_handle : 이 URL 을 처리할 수 있는가(부수효과 없이 즉시 판정) fetch : 실제 수집. 실패는 RawSource.failure 로 돌려주는 것이 기본이고, 호출 자체가 불가능한 경우(꺼진 어댑터 등)에만 예외를 던진다 """ id: str def can_handle(self, url: str) -> bool: ... async def fetch(self, url: str, category: Optional[PlaceCategory] = None) -> RawSource: ...