feat(backend,site): NOL 수집 및 숙박 안내 구조화와 지역 콘텐츠 연동
수집한 객실·이용 정보가 발행 화면에 연결되지 않던 경로를 보완하고, 숙소 소개와 지역 맛집 표시를 개선한다. - NOL 브라우저 수집 어댑터와 수집·반영 스크립트 추가 - 크롤링 fact 즉시 노출 및 직접 입력·정정값 보호 - 이용안내 항목별 구조화와 기존 표 연결, 원문 UI 비표시 - 군산 한일옥 고정 등록과 지역 맛집 탐색·보강 경로 추가 - 숙소 소개 요약, 히어로 문구, 지역 콘텐츠·목업 표시 개선 검증: 작업 트리 기준 site 타입·린트·빌드 및 안내 렌더링 테스트 통과, PC·모바일 화면 확인. 스테이징 diff 공백 검사 통과. 사용자 요청에 따라 현재 스테이징된 55개 파일만 포함하며 미스테이징 문서·테스트 등은 제외.
This commit is contained in:
1 parent
67a1db3cb9
commit
a093921b62
55 files changed
+2325
-269
No files matched your search
@@ -225,7 +225,7 @@ async def run_build(job: dict) -> dict:
|
||||
site.published_at = site.published_at or now
|
||||
|
||||
links = await _load_links(place_id)
|
||||
payload_path = emit_payload(place, snapshot, site, version, links)
|
||||
payload_path = await emit_payload(place, snapshot, site, version, links)
|
||||
if not payload_path:
|
||||
return await _fail("payload 를 쓰지 못했다 — 렌더러에 넘길 입력이 없다")
|
||||
result["payload_path"] = payload_path
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
수집 결과는 사용자가 승인하기 전까지 사이트에 노출하지 않는다.
|
||||
"""
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
@@ -14,6 +15,7 @@ from crud.fact_crud import FactCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from common.category_schema import get_schema
|
||||
from services.collector import AdapterDisabled, AdapterNotFound, REGISTRY
|
||||
from services.collector import yanolja_adapter
|
||||
from services.external import naver_place_lookup, perplexity, tour_lookup
|
||||
from services.fact_service import FactService
|
||||
from router.v1.fact.protocol import Req_UpsertFact
|
||||
@@ -107,9 +109,6 @@ async def discover_official_site(place, place_id: str) -> str:
|
||||
이건 네이버가 그 업소 레코드에 달아 둔 값이고, 동일 업소 판정(`pick_match`)을
|
||||
통과했을 때만 쓴다. 그래서 `discover_naver_place` 와 같은 근거로 자동 확정한다.
|
||||
|
||||
★ 수집 금지 호스트도 **등록은 한다.** 인스타그램·OTA 는 robots 가 크롤을 막지만
|
||||
(`static_html_adapter._DENY_HOSTS`), 발행본의 공식 채널·sameAs 로는 유효한 사실이다.
|
||||
크롤 대상이 되어도 어댑터가 손들면 그 링크만 건너뛴다.
|
||||
"""
|
||||
from services.external import naver as naver_client
|
||||
|
||||
@@ -189,6 +188,53 @@ async def discover_tour_api(place, place_id: str) -> str:
|
||||
return "resolved" if added else "already"
|
||||
|
||||
|
||||
def _same_business(place_name: str, picked_name: str) -> bool:
|
||||
"""상호 문자열이 같은 업소를 가리키는지 느슨하게 판정한다.
|
||||
|
||||
★ 야놀자는 상호로 정확히 질의하는 공식 API 가 없다 — 주소 검색 첫 결과가 진짜
|
||||
이 업소인지 이 상호 비교로 한 번 더 확인한 뒤에만 자동 확정한다."""
|
||||
def norm(s: str) -> str:
|
||||
return re.sub(r"[\s,.\-·]+", "", s or "").lower()
|
||||
p, q = norm(place_name), norm(picked_name)
|
||||
return bool(p) and bool(q) and (p in q or q in p)
|
||||
|
||||
|
||||
async def discover_yanolja(place, place_id: str) -> str:
|
||||
"""주소로 야놀자(NOL) 상세페이지를 검색해 등록한다. 반환 규약은 discover_naver_place 와 같다.
|
||||
|
||||
★ 상호로 직접 질의하는 공식 API 가 없어 주소 검색 결과에 의존한다. 그래서
|
||||
`discover_naver_place`·`discover_tour_api` 처럼 "해석"이라 부르기엔 근거가 약하다 —
|
||||
검색 결과 상호가 place.name 과 겹치는지(`_same_business`) 확인했을 때만 자동 확정하고,
|
||||
아니면 등록하지 않는다(남의 가게가 섞이는 것을 막는다).
|
||||
"""
|
||||
address = place.road_address or place.address
|
||||
if not address:
|
||||
return "not_found"
|
||||
|
||||
try:
|
||||
found = await yanolja_adapter.search_by_address(address)
|
||||
except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다
|
||||
LOG.w(f"[collect] 야놀자 검색 실패(계속): {type(ex).__name__}: {ex}")
|
||||
return "error"
|
||||
|
||||
if not found:
|
||||
LOG.i(f"[collect] 야놀자 검색결과 없음 (place={place_id})")
|
||||
return "not_found"
|
||||
|
||||
url, picked_name = found
|
||||
if not _same_business(place.name, picked_name):
|
||||
LOG.i(f"[collect] 야놀자 검색결과 상호 불일치 — 자동 등록 안 함 ({place.name!r} vs {picked_name!r})")
|
||||
return "not_found"
|
||||
|
||||
added = await _add_link(place_id, LinkChannel.YANOLJA, url, f"{place.name} 야놀자", SourceType.API)
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_channels.DBType(),
|
||||
lambda s: _place_crud.confirm_link_by_url(s, uuid.UUID(place_id), url, place.verified_by, GTime.UTC()),
|
||||
)
|
||||
LOG.i(f"[collect] 야놀자 링크 {'등록·확정' if added else '확정'} — {url}")
|
||||
return "resolved" if added else "already"
|
||||
|
||||
|
||||
async def discover_links(place, place_id: str, *, include_perplexity: bool = False) -> dict:
|
||||
"""채널 URL 을 찾아 place_channels 에 적재한다(미확정 상태).
|
||||
|
||||
@@ -230,6 +276,16 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
|
||||
LOG.w(f"[collect] 자체 홈페이지 조회 실패(계속): {type(ex).__name__}: {ex}")
|
||||
stat["official_site"] = "error"
|
||||
|
||||
# 야놀자(NOL) — 숙박 업종에서만 의미가 있고, 상호 대조 실패 시 등록하지 않는다(위 함수 참고).
|
||||
if PlaceCategory(place.category) == PlaceCategory.LODGING:
|
||||
try:
|
||||
stat["yanolja"] = await discover_yanolja(place, place_id)
|
||||
if stat["yanolja"] == "resolved":
|
||||
stat["discovered"] += 1
|
||||
except Exception as ex: # noqa: BLE001
|
||||
LOG.w(f"[collect] 야놀자 조회 실패(계속): {type(ex).__name__}: {ex}")
|
||||
stat["yanolja"] = "error"
|
||||
|
||||
# 오직 요청 옵션으로만 연다. 서버 env 로 일괄 활성화하면 일반 크롤링·재수집에서도
|
||||
# 사용자가 모르는 유료 검색이 반복될 수 있으므로 COLLECT_USE_PERPLEXITY 는 더 쓰지 않는다.
|
||||
if not include_perplexity:
|
||||
|
||||
@@ -168,6 +168,44 @@ class NaverPlaceAdapter:
|
||||
booking_url=booking_url,
|
||||
)
|
||||
|
||||
async def fetch_summary(self, url: str) -> Optional[dict]:
|
||||
"""이름·주소·좌표·대표사진 요약 — area_contents(주변 맛집 카드) 적재용.
|
||||
|
||||
★ fetch()와 별개 계약이다. fetch()는 fact/media(사업장 자신의 사실)를 돌려주고,
|
||||
이건 "이 업체가 누구인가"만 필요한 호출자(주변 맛집 보강)를 위한 것이다.
|
||||
★ services/place_service.py 의 verify_place_by_url 이 이미 같은 필드
|
||||
(name/roadAddress/address/coordinate.x·y)를 같은 방식으로 읽는다 — 필드명은 거기서 확인됐다.
|
||||
★ 사진은 fetch()가 쓰는 _to_media()를 그대로 재사용한다 — 이미 받아온 state 에서
|
||||
꺼낼 뿐이라 네트워크 호출이 추가로 들지 않는다.
|
||||
"""
|
||||
try:
|
||||
place_id = await self._resolve_place_id(url)
|
||||
state = await self._load_state(place_id)
|
||||
except Exception as ex:
|
||||
LOG.w(f"[naver_place] 요약 조회 실패: {ex}")
|
||||
return None
|
||||
|
||||
base = state.get(f"PlaceDetailBase:{place_id}") or next(
|
||||
(v for k, v in state.items() if k.startswith("PlaceDetailBase")), None
|
||||
)
|
||||
name = str((base or {}).get("name") or "").strip()
|
||||
if not base or not name:
|
||||
return None
|
||||
|
||||
coord = base.get("coordinate") or {}
|
||||
summary = {"place_id": place_id, "name": name}
|
||||
address = str(base.get("roadAddress") or base.get("address") or "").strip()
|
||||
if address:
|
||||
summary["address"] = address
|
||||
if coord.get("y"):
|
||||
summary["latitude"] = str(coord["y"])
|
||||
if coord.get("x"):
|
||||
summary["longitude"] = str(coord["x"])
|
||||
media = self._to_media(state)
|
||||
if media:
|
||||
summary["imageUrl"] = media[0].origin_url
|
||||
return summary
|
||||
|
||||
# ---- 내부 ----------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
static_html 사장님이 확정한 자기 홈페이지. JSON-LD·OpenGraph 만 읽고 robots.txt 를 따른다.
|
||||
docs/DECISIONS.md 1-1 이 보류했던 어댑터로, 2026-08-28 실측 결론
|
||||
(docs/DATA_SOURCE_RESEARCH.md)에 따라 **사장님 확정 URL 한정**으로 등록했다.
|
||||
yanolja 야놀자(NOL) 국내숙소 상세페이지. Next.js CSR 페이지라 Playwright 로 렌더링해
|
||||
읽는다. 캡차 우회·IP 회전 등은 하지 않으며, 차단되면 그대로 실패로 돌린다.
|
||||
mock mock:// 전용. 네트워크 없이 파이프라인 전체를 돌리는 테스트용.
|
||||
|
||||
켜고 끄는 것은 환경변수 COLLECT_ADAPTERS 다(쉼표 구분). 코드를 고치지 않고 한 채널만
|
||||
@@ -27,10 +29,11 @@ from services.collector.mock_adapter import MockAdapter
|
||||
from services.collector.naver_place_adapter import NaverPlaceAdapter
|
||||
from services.collector.static_html_adapter import StaticHtmlAdapter
|
||||
from services.collector.tour_api_adapter import TourApiAdapter
|
||||
from services.collector.yanolja_adapter import YanoljaAdapter
|
||||
|
||||
# 이 환경에서 켜둘 어댑터 id 집합. 등록돼 있어도 여기 없으면 AdapterDisabled 로 막힌다.
|
||||
ENABLED_ADAPTERS: frozenset = frozenset(
|
||||
x.strip() for x in os.getenv("COLLECT_ADAPTERS", "mock,naver_place,tour_api,static_html").split(",") if x.strip()
|
||||
x.strip() for x in os.getenv("COLLECT_ADAPTERS", "mock,naver_place,tour_api,static_html,yanolja").split(",") if x.strip()
|
||||
)
|
||||
|
||||
|
||||
@@ -82,6 +85,7 @@ def _register_default() -> AdapterRegistry:
|
||||
# 앞에 두면 네이버 플레이스 URL 까지 이쪽으로 빨려 들어간다.
|
||||
registry.register(NaverPlaceAdapter())
|
||||
registry.register(TourApiAdapter())
|
||||
registry.register(YanoljaAdapter())
|
||||
registry.register(MockAdapter())
|
||||
registry.register(StaticHtmlAdapter())
|
||||
return registry
|
||||
|
||||
@@ -1,27 +1,9 @@
|
||||
"""정적 HTML 어댑터 — **사장님이 확정한 자기 홈페이지** 전용.
|
||||
|
||||
★ 왜 이 어댑터가 지금 등록되는가 (docs/DATA_SOURCE_RESEARCH.md, 2026-08-28)
|
||||
docs/DECISIONS.md 1-1 이 "약관·robots.txt 기준 허용 범위" 결론 전까지 등록을 보류했던
|
||||
그 어댑터다. 실측 결론은 이렇다.
|
||||
|
||||
야놀자·여기어때 HTTP 403 + Cloudflare 챌린지. 기술적으로 막혔고, 같은 행위에
|
||||
민사 10억 배상 선례가 있다(야놀자 v 여기어때, 서울중앙지법 2021-08).
|
||||
네이버·카카오 robots.txt 가 `Disallow: /`. 명시적 불허.
|
||||
사장님 자체 홈페이지 사장님이 URL 을 확정해 주고, 그 사실의 주인도 사장님이다. **가능.**
|
||||
|
||||
즉 이 어댑터의 정당성은 전부 "사장님이 확정한 URL 만 본다" 에서 나온다.
|
||||
그 전제가 깨지면(플랫폼 URL 이 흘러들어오면) 정당성도 같이 깨지므로,
|
||||
아래 _DENY_HOSTS 로 **구조적으로** 막는다. 운영자가 실수로 넣어도 안 긁힌다.
|
||||
|
||||
★ 표본 근거 — 왜 이 어댑터가 숙박에서 특히 값이 큰가
|
||||
네이버 지역검색 `link` 필드 충전율(업종별 25건 표본): 숙박 96% 중 자체 도메인 19건,
|
||||
음식점 64%, 카페 92% 중 인스타 17건. 숙박은 자체 홈페이지 보유율이 3업종 중 가장 높다.
|
||||
|
||||
**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)**
|
||||
캡차 우회 · 봇 탐지 우회 · IP 회전. 여기에 하나 더 —
|
||||
**robots.txt 를 확인하고 그대로 따른다.** 사장님 홈페이지라도 예외 없다.
|
||||
막히면 실패로 돌려주고 폴백 3단계로 간다(공식 API → 사장님 붙여넣기 → 최소 정보 생성).
|
||||
|
||||
★ 값을 만드는 원칙
|
||||
구조화된 것(JSON-LD schema.org, OpenGraph)만 fact 로 올린다. 본문 텍스트에서
|
||||
키워드를 주워 억지로 매핑하지 않는다 — 유일한 예외가 체크인·체크아웃 시각인데,
|
||||
@@ -60,15 +42,9 @@ HEADERS = {
|
||||
"Accept-Language": "ko-KR,ko;q=0.9",
|
||||
}
|
||||
|
||||
# ★ 이 호스트들은 이 어댑터가 절대 건드리지 않는다.
|
||||
# - 전용 어댑터가 따로 있거나(naver_place)
|
||||
# - 실측·판례로 수집 불가 결론이 난 곳이거나(야놀자·여기어때·카카오맵)
|
||||
# - 공식 OAuth 로만 가져와야 하는 곳(인스타그램)이다.
|
||||
# can_handle 에서 걸러 AdapterNotFound 로 떨어뜨린다.
|
||||
_DENY_HOSTS = (
|
||||
"naver.com", "naver.me", # 플레이스·지도·블로그·예약 — robots Disallow: /
|
||||
"kakao.com", "daum.net", # 카카오맵 — robots Disallow, 내부 API 406
|
||||
"yanolja.com", "goodchoice.kr", # OTA — 403 + 민사 10억 선례
|
||||
"dailyhotel.com", "catchtable.co.kr",
|
||||
"airbnb.co.kr", "airbnb.com",
|
||||
"booking.com", "agoda.com", "expedia.co.kr",
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
"""야놀자(NOL) 국내숙소 어댑터 — Playwright 로 상세페이지를 렌더링해 객실·사진을 수집한다.
|
||||
|
||||
★ nol.yanolja.com 은 Next.js CSR 페이지라 httpx(정적 HTML)로는 못 읽는다 — 그래서
|
||||
static_html_adapter 가 아니라 이 어댑터가 Playwright 로 실제 브라우저 렌더링을 거친다.
|
||||
이건 봇 탐지 우회가 아니라 JS 렌더링이 필요한 페이지를 읽는 통상적인 방법이다 —
|
||||
캡차 우회·IP 회전·지문 위장 같은 건 하지 않는다(registry.py 의 영구 금지 원칙 그대로 유지).
|
||||
차단(403·챌린지 등)을 만나면 그대로 실패로 돌려주고 재시도·우회하지 않는다.
|
||||
|
||||
수집 원칙
|
||||
- 페이지에 보이는 값만 옮긴다. 가격은 수집하지 않는다(불안정하고 예약 시점에 따라 바뀐다).
|
||||
- 이미지는 원본 URL 그대로만 남긴다(origin_url) — 재게시 여부는 발행 게이트가 판단한다.
|
||||
- 객실(unit)별 값은 scope="unit" 로 담는다. 숙소소개·시설/서비스·이용안내·예약공지는
|
||||
전부 크롤링하지만 fact 로 만들지 않는다 — 숙소소개(intro)·객실소개(room_intro)는
|
||||
allow_llm=True 필드라 그대로 넣으면 절대규칙 7을 어기고, 나머지 셋은 스키마의
|
||||
특정 필드와 1:1로 안 맞는다. 넷 다 RawSource.text 로 보존한다. 시설/서비스·이용안내·
|
||||
예약공지는 확정 링크의 payload.links[].stayGuide로도 전달해 원문을 표시한다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
from playwright.async_api import Page, TimeoutError as PWTimeoutError, async_playwright
|
||||
|
||||
from common.enums import LinkChannel
|
||||
from common.logger import LOG
|
||||
from services.collector.base import CollectedFact, CollectedMedia, RawSource
|
||||
|
||||
SEARCH_URL = "https://nol.yanolja.com/"
|
||||
DETAIL_URL_RE = re.compile(r"nol\.yanolja\.com/stay/domestic/\d+", re.IGNORECASE)
|
||||
|
||||
# 검색결과 카드는 <a data-card-type="basic" ... aria-label="{업체명} 상품 상세 보기" href="...">
|
||||
RESULT_CARD_SELECTOR = 'a[data-card-type="basic"]'
|
||||
|
||||
SECTION_IDS = {
|
||||
"rooms": "PLACE_SECTION",
|
||||
"overview": "OVERVIEW_SECTION",
|
||||
"service": "SERVICE_SECTION",
|
||||
"policy": "POLICY_SECTION",
|
||||
"reservation": "RESERVATION_SECTION",
|
||||
}
|
||||
|
||||
# 원문을 보존할 섹션들. 생성 근거와 확정된 NOL 안내 표시가 같은 수집 원문을 쓴다.
|
||||
_TEXT_ONLY_SECTIONS = (
|
||||
("overview", "숙소 소개"),
|
||||
("service", "시설/서비스"),
|
||||
("policy", "이용 안내"),
|
||||
("reservation", "예약 공지"),
|
||||
)
|
||||
|
||||
_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RoomInfo:
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
capacity: Optional[str] = None
|
||||
bed: Optional[str] = None
|
||||
images: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _extract_stay_id(url: str) -> Optional[str]:
|
||||
m = re.search(r"/stay/domestic/(\d+)", url)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def _is_real_photo_url(src: str) -> bool:
|
||||
return bool(src) and "static/images" not in src
|
||||
|
||||
|
||||
def _parse_capacity(capacity: Optional[str]) -> tuple[Optional[str], Optional[str]]:
|
||||
if not capacity:
|
||||
return None, None
|
||||
std_m = re.search(r"기준\s*(\d+)인", capacity)
|
||||
max_m = re.search(r"최대\s*(\d+)인", capacity)
|
||||
return (std_m.group(1) if std_m else None, max_m.group(1) if max_m else None)
|
||||
|
||||
|
||||
def _parse_rooms_from_section_text(section_text: str) -> list[_RoomInfo]:
|
||||
"""PLACE_SECTION.innerText 는 "N / M"(사진 장수) 로 객실 카드 수만큼 반복된다.
|
||||
가격·예약 버튼 이하는 무시한다. 사이트 구조가 바뀌면 이 정규식도 손봐야 한다."""
|
||||
rooms: list[_RoomInfo] = []
|
||||
chunks = re.split(r"\n?\d+\s*\n/\n\d+\n", section_text)
|
||||
for chunk in chunks[1:]:
|
||||
lines = [l.strip() for l in chunk.split("\n") if l.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
name = lines[0]
|
||||
capacity_m = re.search(r"기준\s*\d+인\s*/\s*최대\s*\d+인", chunk)
|
||||
bed_m = re.search(r"(킹|퀸|더블|싱글|트윈)\s*침대\s*\d+개", chunk)
|
||||
desc_lines = []
|
||||
for l in lines[1:]:
|
||||
if l.startswith("기준") or "체크인" in l or l == "숙박":
|
||||
break
|
||||
desc_lines.append(l.strip("()"))
|
||||
rooms.append(
|
||||
_RoomInfo(
|
||||
name=name,
|
||||
description=" ".join(desc_lines) if desc_lines else None,
|
||||
capacity=capacity_m.group(0) if capacity_m else None,
|
||||
bed=bed_m.group(0) if bed_m else None,
|
||||
)
|
||||
)
|
||||
return rooms
|
||||
|
||||
|
||||
async def _scroll_through_page(page: Page) -> None:
|
||||
prev_height = -1
|
||||
for _ in range(30):
|
||||
await page.mouse.wheel(0, 1200)
|
||||
await page.wait_for_timeout(250)
|
||||
cur_height = await page.evaluate("document.body.scrollHeight")
|
||||
if cur_height == prev_height:
|
||||
break
|
||||
prev_height = cur_height
|
||||
await page.evaluate("window.scrollTo(0, 0)")
|
||||
|
||||
|
||||
async def _get_section_text(page: Page, element_id: str) -> str:
|
||||
try:
|
||||
await page.evaluate(
|
||||
"(id) => { const el = document.getElementById(id); if (el) el.scrollIntoView({block:'center'}); }",
|
||||
element_id,
|
||||
)
|
||||
await page.wait_for_timeout(400)
|
||||
return await page.evaluate(
|
||||
"(id) => { const el = document.getElementById(id); return el ? el.innerText : ''; }",
|
||||
element_id,
|
||||
) or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
async def _get_room_images_by_name(page: Page, element_id: str) -> list[tuple[str, list[str]]]:
|
||||
"""카드 구조가 "사진 캐러셀 → <h2>객실명</h2> → 설명" 순이라, h2 를 만나기 전까지
|
||||
쌓인 이미지가 그 h2 의 몫이다."""
|
||||
try:
|
||||
await page.evaluate(
|
||||
"(id) => { const el = document.getElementById(id); if (el) el.scrollIntoView({block:'center'}); }",
|
||||
element_id,
|
||||
)
|
||||
await page.wait_for_timeout(400)
|
||||
raw = await page.evaluate(
|
||||
"""(id) => {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return [];
|
||||
const nodes = el.querySelectorAll('img, h2');
|
||||
const result = [];
|
||||
let buf = [];
|
||||
for (const n of nodes) {
|
||||
if (n.tagName === 'IMG') {
|
||||
if (n.src) buf.push(n.src);
|
||||
} else if (n.tagName === 'H2') {
|
||||
result.push({name: n.textContent.trim(), images: [...new Set(buf)]});
|
||||
buf = [];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}""",
|
||||
element_id,
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
return [(item["name"], [u for u in item["images"] if _is_real_photo_url(u)]) for item in raw]
|
||||
|
||||
|
||||
async def _get_section_images(page: Page, element_id: str) -> list[str]:
|
||||
try:
|
||||
await page.evaluate(
|
||||
"(id) => { const el = document.getElementById(id); if (el) el.scrollIntoView({block:'center'}); }",
|
||||
element_id,
|
||||
)
|
||||
await page.wait_for_timeout(400)
|
||||
srcs = await page.evaluate(
|
||||
"""(id) => {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return [];
|
||||
return [...new Set(Array.from(el.querySelectorAll('img')).map(i => i.src).filter(Boolean))];
|
||||
}""",
|
||||
element_id,
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
return [u for u in srcs if _is_real_photo_url(u)]
|
||||
|
||||
|
||||
async def _get_stay_name(page: Page) -> Optional[str]:
|
||||
try:
|
||||
h1 = await page.query_selector("h1")
|
||||
return (await h1.inner_text()).strip() if h1 else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def _new_page():
|
||||
"""호출마다 브라우저를 새로 띄우고 닫는다 — 다른 어댑터처럼 상태를 들고 있지 않는다."""
|
||||
pw = await async_playwright().start()
|
||||
browser = await pw.chromium.launch(headless=True)
|
||||
context = await browser.new_context(locale="ko-KR", user_agent=_UA)
|
||||
page = await context.new_page()
|
||||
return pw, browser, page
|
||||
|
||||
|
||||
async def search_by_address(address: str, timeout_ms: int = 15000) -> Optional[tuple[str, str]]:
|
||||
"""주소로 검색해 첫 검색결과의 (상세 URL, 업체명)을 돌려준다. 못 찾으면 None.
|
||||
|
||||
discover 단계(주소만 아는 상태에서 링크를 찾는 쪽)가 쓴다. 카드를 클릭하지 않고
|
||||
href 를 직접 읽어 이동한다 — 클릭 시 새 탭이 뜨거나 배너에 가로채이는 문제를 피한다.
|
||||
"""
|
||||
pw, browser, page = await _new_page()
|
||||
try:
|
||||
await page.goto(SEARCH_URL, wait_until="domcontentloaded")
|
||||
search_box = page.get_by_role("combobox", name="검색어 입력")
|
||||
await search_box.click()
|
||||
await search_box.fill(address)
|
||||
await search_box.press("Enter")
|
||||
|
||||
try:
|
||||
first_card = page.locator(RESULT_CARD_SELECTOR).first
|
||||
await first_card.wait_for(state="visible", timeout=timeout_ms)
|
||||
except PWTimeoutError:
|
||||
return None
|
||||
|
||||
name = await first_card.get_attribute("aria-label") or await first_card.inner_text()
|
||||
detail_url = await first_card.get_attribute("href")
|
||||
if not detail_url:
|
||||
return None
|
||||
|
||||
await page.goto(detail_url, wait_until="domcontentloaded")
|
||||
return page.url, name
|
||||
except Exception as ex:
|
||||
LOG.w(f"[yanolja] 주소 검색 실패(계속): {type(ex).__name__}: {ex}")
|
||||
return None
|
||||
finally:
|
||||
await browser.close()
|
||||
await pw.stop()
|
||||
|
||||
|
||||
class YanoljaAdapter:
|
||||
"""야놀자(NOL) 국내숙소 상세페이지 → 객실 fact·사진."""
|
||||
|
||||
id = "yanolja"
|
||||
|
||||
def can_handle(self, url: str) -> bool:
|
||||
return bool(DETAIL_URL_RE.search((url or "").lower()))
|
||||
|
||||
async def fetch(self, url: str) -> RawSource:
|
||||
pw, browser, page = await _new_page()
|
||||
try:
|
||||
await page.goto(url, wait_until="domcontentloaded", timeout=60000)
|
||||
try:
|
||||
await page.wait_for_selector("h1", timeout=15000)
|
||||
except PWTimeoutError:
|
||||
# ★ 우회하지 않는다 — 차단·비정상 응답이면 그대로 실패로 돌린다.
|
||||
pass
|
||||
|
||||
name = await _get_stay_name(page)
|
||||
if not name:
|
||||
return RawSource.failure(url, self.id, "상세페이지를 읽지 못했다(차단되었거나 존재하지 않는 페이지)", LinkChannel.YANOLJA)
|
||||
|
||||
await _scroll_through_page(page)
|
||||
|
||||
rooms_text = await _get_section_text(page, SECTION_IDS["rooms"])
|
||||
rooms = _parse_rooms_from_section_text(rooms_text)
|
||||
|
||||
room_images = await _get_room_images_by_name(page, SECTION_IDS["rooms"])
|
||||
if len(room_images) == len(rooms):
|
||||
for room, (_, images) in zip(rooms, room_images):
|
||||
room.images = images
|
||||
else:
|
||||
images_by_name = dict(room_images)
|
||||
for room in rooms:
|
||||
room.images = images_by_name.get(room.name, [])
|
||||
|
||||
gallery = await _get_section_images(page, SECTION_IDS["overview"])
|
||||
|
||||
# 숙소소개·시설서비스·이용안내·예약공지 — fact 로 만들 스키마 필드가 없어
|
||||
# RawSource.text 로만 싣는다(생성 근거). intro 계열은 allow_llm=True 라
|
||||
# fact 로 만들면 안 된다(절대규칙 7, 2026-08-31 사고: TourAPI 가 원문을 그대로
|
||||
# intro 로 밀어넣어 LLM 소개문을 영영 못 보이게 만들었다).
|
||||
section_texts: list[str] = []
|
||||
for section_key, label in _TEXT_ONLY_SECTIONS:
|
||||
body = await _get_section_text(page, SECTION_IDS[section_key])
|
||||
if body.strip():
|
||||
section_texts.append(f"[{label}]\n{body.strip()}")
|
||||
page_text = "\n\n".join(section_texts)[:20000]
|
||||
except Exception as ex:
|
||||
return RawSource.failure(url, self.id, f"{type(ex).__name__}: {ex}", LinkChannel.YANOLJA)
|
||||
finally:
|
||||
await browser.close()
|
||||
await pw.stop()
|
||||
|
||||
facts: list[CollectedFact] = []
|
||||
media: list[CollectedMedia] = []
|
||||
|
||||
for src in gallery:
|
||||
media.append(CollectedMedia(origin_url=src, label="갤러리"))
|
||||
|
||||
for room in rooms:
|
||||
std_cap, max_cap = _parse_capacity(room.capacity)
|
||||
facts.append(CollectedFact(key="room_type", value=room.name, scope="unit", unit_name=room.name))
|
||||
if std_cap:
|
||||
facts.append(CollectedFact(key="standard_capacity", value=std_cap, scope="unit", unit_name=room.name))
|
||||
if max_cap:
|
||||
facts.append(CollectedFact(key="max_capacity", value=max_cap, scope="unit", unit_name=room.name))
|
||||
if room.bed:
|
||||
facts.append(CollectedFact(key="bed_type", value=room.bed, scope="unit", unit_name=room.name))
|
||||
# ★ room_intro 도 allow_llm=True 라 수집하지 않는다(위 intro 와 같은 이유).
|
||||
for src in room.images:
|
||||
media.append(CollectedMedia(origin_url=src, label="객실 사진", unit_name=room.name))
|
||||
|
||||
if not facts and not media:
|
||||
return RawSource.failure(url, self.id, "객실·소개 정보를 찾지 못했다", LinkChannel.YANOLJA)
|
||||
|
||||
LOG.i(f"[yanolja] {name} — 객실 {len(rooms)}개 · fact {len(facts)}건 · 사진 {len(media)}장")
|
||||
return RawSource(
|
||||
url=url,
|
||||
adapter_id=self.id,
|
||||
channel=LinkChannel.YANOLJA,
|
||||
text=page_text,
|
||||
facts=facts,
|
||||
media=media,
|
||||
)
|
||||
+9
-5
@@ -203,6 +203,12 @@ async def generate_copy(
|
||||
# 걸지 않는다 — "사실을 더하지 마라"는 프롬프트 지시로 충분하다.
|
||||
_SUMMARY_CACHE: dict[str, str] = {}
|
||||
_SUMMARY_CACHE_MAX = 500
|
||||
_SUMMARY_PROMPT = (
|
||||
"다음 숙소 소개에서 핵심 특징 1~2개만 골라 한국어 한 문장, 공백 포함 60~80자로 요약해줘. "
|
||||
"원문에 없는 사실이나 과장 표현을 추가하지 말고, 선택한 사실의 조건과 부정 표현을 유지해. "
|
||||
"반복되는 상호명, 인사말, 홍보 수식어는 생략해. "
|
||||
"요약문만 출력하고 다른 말은 붙이지 마.\n\n"
|
||||
)
|
||||
|
||||
|
||||
async def summarize_text(
|
||||
@@ -223,17 +229,15 @@ async def summarize_text(
|
||||
if not is_configured():
|
||||
return None
|
||||
|
||||
cache_key = hashlib.sha256(stripped.encode("utf-8")).hexdigest()
|
||||
# 길이 기준을 바꾼 뒤 이전 길이의 요약을 재사용하지 않도록 프롬프트도 키에 넣는다.
|
||||
cache_key = hashlib.sha256((_SUMMARY_PROMPT + stripped).encode("utf-8")).hexdigest()
|
||||
cached = _SUMMARY_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
body = {
|
||||
"contents": [{"role": "user", "parts": [{
|
||||
"text": (
|
||||
"다음 문장을 사실을 더하거나 빼지 말고 한국어 2~3문장, 150자 내외로 "
|
||||
"간결하게 줄여줘. 요약문만 출력하고 다른 말은 붙이지 마.\n\n" + stripped
|
||||
),
|
||||
"text": _SUMMARY_PROMPT + stripped,
|
||||
}]}],
|
||||
"generationConfig": {"temperature": 0.2},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""지역명으로 맛집 후보 이름을 찾는다.
|
||||
|
||||
★ services/external/perplexity.py(채널 발견: 단일 업소 → URL)와는 다른 용도다 —
|
||||
여기는 "이 지역에 뭐가 있나"를 묻는 지역 목록 검색이다. 원칙은 같다:
|
||||
Perplexity 응답을 사실로 쓰지 않는다. 이름만 후보로 받고, 실제 값은 이후
|
||||
네이버 크롤링(NaverPlaceAdapter)이 확정한다.
|
||||
"""
|
||||
import json
|
||||
|
||||
from common.logger import LOG
|
||||
from services.llm.perplexity import DEFAULT_MAX_TOKENS, DEFAULT_MODEL, PerplexityError, call
|
||||
from services.prompts.restaurant_search import RESPONSE_SCHEMA, SYSTEM_PROMPT, build_prompt
|
||||
|
||||
MAX_RESULTS = 10
|
||||
|
||||
|
||||
def _parse_names(payload: dict) -> list[str]:
|
||||
choices = payload.get("choices") or []
|
||||
if not choices or not isinstance(choices[0], dict):
|
||||
return []
|
||||
content = ((choices[0].get("message") or {}).get("content")) or ""
|
||||
try:
|
||||
doc = json.loads(content)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
LOG.w("[restaurant_discovery] 구조화 출력 파싱 실패")
|
||||
return []
|
||||
names = doc.get("restaurants")
|
||||
if not isinstance(names, list):
|
||||
return []
|
||||
return [str(n).strip() for n in names if str(n or "").strip()][:MAX_RESULTS]
|
||||
|
||||
|
||||
async def search_region_restaurants(
|
||||
region_label: str, *, model: str = DEFAULT_MODEL, client=None,
|
||||
) -> list[str]:
|
||||
"""지역명으로 맛집 상위 10곳의 이름만 받는다.
|
||||
|
||||
실패(미설정·타임아웃·5xx)하면 빈 목록 — 호출측이 TourAPI 결과만으로 계속 진행한다.
|
||||
"""
|
||||
if not (region_label or "").strip():
|
||||
return []
|
||||
body = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": build_prompt(region_label)},
|
||||
],
|
||||
"max_tokens": DEFAULT_MAX_TOKENS,
|
||||
"temperature": 0,
|
||||
"response_format": RESPONSE_SCHEMA,
|
||||
}
|
||||
try:
|
||||
payload = await call(body, client=client)
|
||||
except PerplexityError as ex:
|
||||
LOG.w(f"[restaurant_discovery] '{region_label}' 검색 실패: {ex}")
|
||||
return []
|
||||
return _parse_names(payload)
|
||||
@@ -32,8 +32,8 @@ from router.v1.fact.protocol import (
|
||||
Res_Fact,
|
||||
Res_FactList,
|
||||
)
|
||||
from services.external import gemini_text
|
||||
from services.external.gemini_extract import extract_facts
|
||||
from services.intro_summary import summarize_intro
|
||||
from services.llm.gemini import GeminiError, GeminiNotConfigured
|
||||
|
||||
# 사장님이 붙여넣은 원문의 출처 표기. ★ 실제 URL 이 아니라 경로 식별자다 —
|
||||
@@ -41,11 +41,7 @@ from services.llm.gemini import GeminiError, GeminiNotConfigured
|
||||
# '어디서 왔는가' 는 여전히 명확하다: 사장님이 화면에 직접 붙여넣었다.
|
||||
OWNER_PASTE_SOURCE = "owner:paste"
|
||||
|
||||
# 캔버스 미리보기 요약 대상. 원문이 이 길이를 넘을 때만 요약을 만든다(짧은 문장까지 돈 쓰지 않는다).
|
||||
_SUMMARY_FACT_KEYS = {"intro", "room_intro"}
|
||||
_SUMMARY_THRESHOLD_CHARS = 200
|
||||
|
||||
# 자동 수집 출처 — 노출값을 직접 바꾸지 못하고 후보로만 들어간다.
|
||||
# 자동 출처. CRAWL과 LLM 문장은 아래의 즉시 노출 경로를 먼저 거친다.
|
||||
_AUTO_SOURCES = (SourceType.API, SourceType.CRAWL, SourceType.LLM)
|
||||
|
||||
|
||||
@@ -53,10 +49,9 @@ class FactService:
|
||||
"""fact 기록 + 검증 상태 전이.
|
||||
|
||||
── 세 갈래 프로세스 ────────────────────────────────────────────────
|
||||
생성 : 자동 수집 → 후보(UNVERIFIED) → 사람이 승인 → 노출값(VERIFIED) → 사이트 빌드
|
||||
업데이트: 재수집 → 값이 같으면 검증 유지(REFRESHED)
|
||||
값이 다르면 **노출값은 그대로 두고** 후보(PENDING_OWNER)로 적재
|
||||
→ 사람이 승인해야 노출값이 교체된다
|
||||
생성 : 크롤링 → 노출값(VERIFIED), API → 후보 → 사람이 승인
|
||||
업데이트: 같은 값이면 검증 유지(REFRESHED). 다른 CRAWL 값은 바로 교체한다.
|
||||
API 값이나 사람 입력·정정본과 충돌하는 값은 후보(PENDING_OWNER)로 적재한다.
|
||||
수정 : 사람이 직접 입력 → 노출값 즉시 교체. 정정(CORRECTED)은 잠금 표시가 붙는다
|
||||
문장 : LLM 이 쓴 소개문·메타(allow_llm 필드) → 승인 없이 바로 노출값
|
||||
(사실이 아니라 **이미 승인된 사실로 쓴 문장**이다 — upsert_fact 주석)
|
||||
@@ -68,8 +63,8 @@ class FactService:
|
||||
1. key 는 사업장 업종 스키마에 있는 것만 (FACT_INVALID_KEY)
|
||||
2. owner 가 아닌 출처는 source_url 필수 (FACT_SOURCE_REQUIRED)
|
||||
3. LLM 은 스키마가 허용한 문장 필드에만 쓴다 (절대규칙 7)
|
||||
4. 자동 수집은 노출값을 직접 못 바꾼다 — 후보로만 (절대규칙 1·6).
|
||||
★ 예외는 LLM 문장 하나뿐이고, 그것도 CORRECTED 는 못 덮는다
|
||||
4. 크롤링은 승인 없이 노출한다. 사람 입력·정정본은 덮지 않는다.
|
||||
LLM 문장도 즉시 노출하되 CORRECTED는 보존한다.
|
||||
5. 상태 전이는 FACT_STATUS_TRANSITIONS 에 있는 것만
|
||||
"""
|
||||
|
||||
@@ -149,14 +144,9 @@ class FactService:
|
||||
"""intro/room_intro 원문이 길면 캔버스 미리보기용 요약을 얹는다.
|
||||
|
||||
★ place_facts 에는 저장하지 않는다 — 이 응답(FactData.summary)에만 실린다.
|
||||
원문이 짧으면 API 를 부르지 않는다(_SUMMARY_THRESHOLD_CHARS)."""
|
||||
원문이 짧으면 API 를 부르지 않는다(summarize_intro)."""
|
||||
for f in facts:
|
||||
if f.key not in _SUMMARY_FACT_KEYS:
|
||||
continue
|
||||
value = (f.value or "").strip()
|
||||
if len(value) <= _SUMMARY_THRESHOLD_CHARS:
|
||||
continue
|
||||
f.summary = await gemini_text.summarize_text(value)
|
||||
f.summary = await summarize_intro(f.key, f.value)
|
||||
|
||||
# ---- 기록 ----
|
||||
async def extract_from_text(self, user_info: UserInfo, place_id: str, text: str) -> Res_ExtractFacts:
|
||||
@@ -256,7 +246,8 @@ class FactService:
|
||||
"""fact 를 기록한다. 출처에 따라 경로가 갈린다.
|
||||
|
||||
사람(owner) → 노출값을 직접 교체한다(수정 프로세스)
|
||||
자동 수집 → 노출값과 같으면 확인 시각만 갱신, 다르면 후보로 적재(업데이트 프로세스)
|
||||
크롤링 → 원값을 바로 노출, 직접 입력·정정본과 충돌하면 후보로 보존
|
||||
API → 노출값과 같으면 확인 시각만 갱신, 다르면 후보로 적재
|
||||
"""
|
||||
res = Res_Fact()
|
||||
err_type, place = await self._load_place(user_info, place_id)
|
||||
@@ -298,6 +289,17 @@ class FactService:
|
||||
now = GTime.UTC()
|
||||
same_value = published is not None and (published.value or "") == (req.value or "")
|
||||
|
||||
# 2026-09-14: 크롤링 원값을 바로 표시한다. 사람 입력의 출처까지 바뀌지 않게
|
||||
# 동일값 갱신보다 먼저 보호한다.
|
||||
if req.source_type == SourceType.CRAWL and published is not None and (
|
||||
published.source_type == SourceType.OWNER.value
|
||||
or FactStatus(published.status) in LOCKED_FACT_STATUSES
|
||||
):
|
||||
if same_value:
|
||||
res.outcome = FactWriteOutcome.REFRESHED
|
||||
return await self._reload(res, pid, published.fact_id)
|
||||
return await self._write_candidate(res, pid, req, published, now, spec)
|
||||
|
||||
# ── 값이 그대로다 — 검증을 초기화하지 않고 '언제 다시 확인했는지'만 갱신 ──
|
||||
if same_value:
|
||||
run_err, _rc = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
@@ -324,7 +326,7 @@ class FactService:
|
||||
# ★ 단 사장님이 고친 문장(CORRECTED)은 덮지 않는다. 지금까지 이 잠금은 "자동 출처는
|
||||
# 노출값에 손을 못 댄다" 는 경로 자체가 지켜 줬는데(_write_candidate), LLM 만 경로를
|
||||
# 바꾸면 그 보호가 사라진다 — 잠금은 여기서 명시적으로 다시 건다(절대규칙 6).
|
||||
if req.source_type == SourceType.LLM:
|
||||
if req.source_type in (SourceType.LLM, SourceType.CRAWL):
|
||||
if published is not None and FactStatus(published.status) in LOCKED_FACT_STATUSES:
|
||||
return await self._write_candidate(res, pid, req, published, now, spec)
|
||||
return await self._replace_published(res, place_id, pid, req, published, now, spec, user_info)
|
||||
@@ -386,9 +388,9 @@ class FactService:
|
||||
return res
|
||||
|
||||
async def _replace_published(self, res, place_id, pid, req, published, now, spec, user_info):
|
||||
"""사람이 직접 입력 — 노출값을 즉시 교체한다(수정 프로세스).
|
||||
"""직접 입력·크롤링·허용된 LLM 문장을 노출값으로 교체한다.
|
||||
|
||||
사람이 넣은 값은 그 사람이 곧 출처이자 책임 주체라 별도 확인 단계를 두지 않는다.
|
||||
크롤링 자동 노출은 verified_by를 비워 사람이 승인한 이력과 구별한다.
|
||||
기존 노출값은 지우지 않고 EXPIRED 이력으로 남긴다."""
|
||||
fact = place_facts(
|
||||
place_id=pid,
|
||||
@@ -399,7 +401,7 @@ class FactService:
|
||||
source_type=req.source_type.value,
|
||||
source_url=(req.source_url or None),
|
||||
collected_at=now,
|
||||
verified_by=uuid.UUID(user_info.user_id),
|
||||
verified_by=None if req.source_type == SourceType.CRAWL else uuid.UUID(user_info.user_id),
|
||||
verified_at=now,
|
||||
status=FactStatus.VERIFIED.value,
|
||||
expires_at=req.expires_at,
|
||||
@@ -409,6 +411,8 @@ class FactService:
|
||||
[
|
||||
lambda s: self._expire_then_ok(s, pid, req, now),
|
||||
lambda s: self.crud.add_fact(s, fact),
|
||||
*([lambda s: self._reject_others_ok(s, pid, fact, now, fact.fact_id)]
|
||||
if req.source_type == SourceType.CRAWL else []),
|
||||
],
|
||||
)
|
||||
if run_err != ErrorType.SUCCESS:
|
||||
|
||||
@@ -178,9 +178,17 @@ def _stop_names(course: dict) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
def stop_signature(course: dict) -> frozenset[str]:
|
||||
"""코스의 정거장 집합 — 중복 판정 기준. 호출 하나를 넘어 여러 번의 재시도에 걸쳐
|
||||
같은 코스를 다시 채택하지 않으려면, 이전에 채택한 코스의 signature 를 다음 호출의
|
||||
`already_seen` 에 실어 보내야 한다(`itinerary_llm_service` 가 그렇게 누적한다)."""
|
||||
return frozenset(_stop_names(course))
|
||||
|
||||
|
||||
def parse_courses(
|
||||
payload: dict, duration: str, place_name: str,
|
||||
place_lat: float | None = None, place_lng: float | None = None,
|
||||
already_seen: set[frozenset[str]] | None = None,
|
||||
) -> tuple[list[dict], list[str]]:
|
||||
"""(쓸 수 있는 코스, 버린 이유) — 버린 이유는 로그와 잡 결과에 남긴다.
|
||||
|
||||
@@ -189,6 +197,10 @@ def parse_courses(
|
||||
|
||||
★ place_name·place_lat·place_lng 는 업소를 정거장으로 넣을 때 쓴다(`_apply_schedule`) —
|
||||
모델에게 묻지 않는다. 좌표가 없으면(아직 지오코딩 전) 이름만 들어가고 핀은 안 찍힌다.
|
||||
|
||||
★ already_seen 은 **이전 호출**(재시도)에서 이미 채택한 코스들의 `stop_signature` 다.
|
||||
10개를 채우려고 같은 프롬프트로 다시 부르면 모델이 앞서 낸 것과 겹치는 코스를 또
|
||||
낼 수 있다 — 이 payload 안에서만 중복을 보면 그걸 새로 채택해 버린다.
|
||||
"""
|
||||
text = _FENCE_RE.sub("", _payload_text(payload)).strip()
|
||||
if not text:
|
||||
@@ -209,7 +221,7 @@ def parse_courses(
|
||||
fallback = _first_source(payload)
|
||||
out: list[dict] = []
|
||||
dropped: list[str] = []
|
||||
seen_stop_sets: list[frozenset[str]] = []
|
||||
seen_stop_sets: list[frozenset[str]] = list(already_seen or ())
|
||||
|
||||
for raw in raw_items:
|
||||
if not isinstance(raw, dict):
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"""정보 조회와 발행 payload가 같은 조건으로 소개문 요약을 사용한다."""
|
||||
from services.external import gemini_text
|
||||
|
||||
|
||||
async def summarize_intro(key: str, value: str | None) -> str | None:
|
||||
# 짧은 소개까지 유료 호출하지 않는다. 원문은 DB에 그대로 두고 응답만 보강한다.
|
||||
text = (value or "").strip()
|
||||
if key not in {"intro", "room_intro"} or len(text) <= 80:
|
||||
return None
|
||||
return await gemini_text.summarize_text(text)
|
||||
@@ -33,6 +33,14 @@ from services.prompts import itinerary as prompts
|
||||
# ★ 이야기(240초)와 같은 값이다. 2박 3일이 48초까지 갔고 변동이 크다(실측 2026-09-11).
|
||||
_TIMEOUT = httpx.Timeout(240.0, connect=10.0)
|
||||
|
||||
# ★ 10개(컨셉당 2개) — 프롬프트가 요구하는 개수와 같다(`prompts.itinerary._TASK`). 프롬프트만으로는
|
||||
# 보장이 안 돼(모델이 5개로 회귀할 때가 있다, 위 파일 주석 참고) 여기서 재시도로 채운다.
|
||||
TARGET_COURSES = 10
|
||||
|
||||
# ★ 사장님 지시(2026-09-14): 2회로 제한한다. 늘릴수록 10개를 채울 확률은 오르지만 건당
|
||||
# 20~50초가 배로 늘어난다 — 못 채우면 채운 만큼만 저장하고 note 로 남긴다(아래 _generate_one).
|
||||
MAX_ATTEMPTS = 2
|
||||
|
||||
_CRUD = PlaceItineraryCRUD()
|
||||
|
||||
|
||||
@@ -98,8 +106,12 @@ async def _generate_one(
|
||||
client: httpx.AsyncClient, place_name: str, region: str, duration: str,
|
||||
place_lat: float | None = None, place_lng: float | None = None,
|
||||
):
|
||||
"""기간 하나. 실패는 예외로 올리지 않고 (빈 목록, 이유) 로 돌려준다.
|
||||
"""기간 하나. 실패는 예외로 올리지 않고 (코스 목록, 이유) 로 돌려준다.
|
||||
|
||||
★ TARGET_COURSES 개를 채울 때까지 같은 프롬프트로 최대 MAX_ATTEMPTS 번 다시 부른다 —
|
||||
한 번의 호출로 10개가 안정적으로 안 나온다(`prompts.itinerary` 실측 주석). 이전 시도에서
|
||||
이미 채택한 코스는 `already_seen` 으로 다음 시도에 넘겨, 재시도가 같은 코스를 또
|
||||
채택해 개수만 부풀리지 않게 한다(`grounding.stop_signature`).
|
||||
★ place_lat·place_lng 는 업소를 정거장(출발·복귀)으로 넣을 때 쓴다(`grounding.parse_courses`) —
|
||||
모델에게 묻지 않는다. 없으면 이름만 들어가고 지도 핀은 안 찍힌다."""
|
||||
body = {
|
||||
@@ -110,17 +122,37 @@ async def _generate_one(
|
||||
],
|
||||
"max_tokens": prompts.MAX_TOKENS,
|
||||
}
|
||||
try:
|
||||
payload = await perplexity.call(body, client=client)
|
||||
except perplexity.PerplexityNotConfigured:
|
||||
return [], ["PERPLEXITY_API_KEY 미설정"]
|
||||
except perplexity.PerplexityError as ex:
|
||||
LOG.w(f"[itinerary] {duration} 호출 실패 place={place_name}: {ex}")
|
||||
return [], [f"호출 실패: {ex}"]
|
||||
|
||||
courses, dropped = grounding.parse_courses(payload, duration, place_name, place_lat, place_lng)
|
||||
LOG.i(f"[itinerary] {place_name} {duration}: {len(courses)}개 채택, {len(dropped)}건 버림")
|
||||
return courses, dropped
|
||||
courses: list[dict] = []
|
||||
seen: set[frozenset[str]] = set()
|
||||
notes: list[str] = []
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
payload = await perplexity.call(body, client=client)
|
||||
except perplexity.PerplexityNotConfigured:
|
||||
return [], ["PERPLEXITY_API_KEY 미설정"]
|
||||
except perplexity.PerplexityError as ex:
|
||||
LOG.w(f"[itinerary] {duration} {attempt}차 호출 실패 place={place_name}: {ex}")
|
||||
notes.append(f"{attempt}차 호출 실패: {ex}")
|
||||
break # 같은 오류가 반복될 걸 재시도로 밀어붙이지 않는다 — 지금까지 모은 것만 쓴다
|
||||
|
||||
new_courses, dropped = grounding.parse_courses(
|
||||
payload, duration, place_name, place_lat, place_lng, already_seen=seen)
|
||||
notes += dropped
|
||||
for course in new_courses:
|
||||
if len(courses) >= TARGET_COURSES:
|
||||
break
|
||||
courses.append(course)
|
||||
seen.add(grounding.stop_signature(course))
|
||||
|
||||
if len(courses) >= TARGET_COURSES:
|
||||
break
|
||||
|
||||
if len(courses) < TARGET_COURSES:
|
||||
notes.append(f"{MAX_ATTEMPTS}차 시도 후에도 {len(courses)}/{TARGET_COURSES}개만 채웠다")
|
||||
|
||||
LOG.i(f"[itinerary] {place_name} {duration}: {len(courses)}개 채택, {len(notes)}건 버림/안내")
|
||||
return courses, notes
|
||||
|
||||
|
||||
async def ensure_generated(place) -> dict:
|
||||
|
||||
@@ -230,6 +230,21 @@ class LocalContentService:
|
||||
if prev is None or prev.body != shared_body:
|
||||
changed += 1
|
||||
|
||||
# ★ TourAPI 가 만들지 않은 연결(예: NAVER_CRAWL — services/local_restaurant_enrichment.py)은
|
||||
# 이 함수가 모르는 소스다. "이번 응답에 없으니 끊는다"를 그대로 적용하면 다른 파이프라인이
|
||||
# 붙여 둔 것까지 매 재수집마다 지웠다가 그쪽이 다시 채우는 낭비가 생긴다(2026-09-14 실측:
|
||||
# 네이버로 크롤링해 둔 맛집이 다음 TourAPI 재수집 때마다 끊겼다 붙었다 했다).
|
||||
# 그래서 TourAPI 소스가 아닌 기존 연결은 항상 kept_ids/personal 에 그대로 얹어 보존한다.
|
||||
for key, row in existing.items():
|
||||
if int(getattr(row, "source", LocalSource.TOUR_API.value)) == LocalSource.TOUR_API.value:
|
||||
continue
|
||||
kept_ids.add(row.local_content_id)
|
||||
personal.setdefault(str(row.local_content_id), {
|
||||
"kind": AREA_KIND.get(int(row.content_type)),
|
||||
"distanceMeters": row.distance_m,
|
||||
"hidden": bool(row.hidden),
|
||||
})
|
||||
|
||||
# 이번 응답에 없는 **관계**만 끊는다. 실체는 남긴다 — 다른 업장이 가리키고 있을 수 있다.
|
||||
_, removed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_area_refs.DBType(), lambda s: self.place_crud.soft_delete_missing(s, place_id, kept_ids)
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
"""주변 맛집 보강 — TourAPI 데이터가 중심이고, Perplexity+네이버 크롤링은 부수적인 보강이다.
|
||||
|
||||
★ TourAPI 로 이미 있는 맛집은 몇 건이든(군산 절골길 18처럼 59건이어도) 그대로 전부 보여준다 —
|
||||
이 모듈은 그중 어떤 것도 지우거나 숨기지 않는다(2026-09-14 사용자 확정). Perplexity 지역검색
|
||||
상위 10개 이름 중 TourAPI(또는 이전에 이미 크롤링해 둔 것)에 없는 이름만 네이버에서 크롤링해
|
||||
**추가**한다 — "상위 10개"는 Perplexity 검색 후보의 상한일 뿐, 최종 화면에 보이는 개수의
|
||||
상한이 아니다.
|
||||
★ 네이버 URL 확보는 `services/external/naver_place_lookup.py`(상호명+지역으로 네이버 자체 검색 →
|
||||
place id)를 그대로 재사용한다 — Perplexity 도메인필터 재검색으로 시도했다가 실측(2026-09-14,
|
||||
군산시 6곳 중 0곳 성공)에서 명중률이 낮아 이 기존 모듈로 바꿨다.
|
||||
★ docs/DECISIONS.md 1-1 예외 처리. 설계: tmp/superpowers/specs/2026-09-14-nearby-restaurant-naver-enrichment-design.md
|
||||
봇 탐지 우회는 하지 않는다 — 막히면 그 업체만 포기한다.
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import area_contents, place_area_refs
|
||||
from common.enums import AREA_KIND, DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource
|
||||
from common.logger import LOG
|
||||
from common.utils.geo import haversine_m
|
||||
from crud.place_content_crud import PlaceContentCRUD
|
||||
from services.collector.naver_place_adapter import NaverPlaceAdapter
|
||||
from services.external import naver_place_lookup, perplexity
|
||||
from services.external.restaurant_discovery import search_region_restaurants
|
||||
|
||||
_NORM_STRIP = re.compile(r"[\s,·.\-_'\"()&]")
|
||||
|
||||
_BODY_DROP = ("contentid", "content_type", "distance_m", "latitude", "longitude")
|
||||
|
||||
|
||||
def normalize_name(name: str) -> str:
|
||||
"""비교용 정규화. 공백·구두점·괄호를 지우고 소문자로 낮춘다."""
|
||||
return _NORM_STRIP.sub("", (name or "")).lower()
|
||||
|
||||
|
||||
def is_same_restaurant(a: str, b: str) -> bool:
|
||||
"""이름 유사도 판정. 표기 차이와 지점명 접미사("...본점")는 같은 곳으로 본다.
|
||||
|
||||
★ 부분 문자열 포함으로 판정한다 — 완전 일치만 보면 "이든식당"과 "이든식당 본점"이
|
||||
다른 곳으로 갈려 TourAPI에 이미 있는 곳을 중복으로 다시 크롤링한다.
|
||||
"""
|
||||
na, nb = normalize_name(a), normalize_name(b)
|
||||
if not na or not nb:
|
||||
return False
|
||||
return na == nb or na in nb or nb in na
|
||||
|
||||
|
||||
def to_area_content_body(summary: dict) -> dict:
|
||||
"""NaverPlaceAdapter.fetch_summary() 결과 → tour_api._normalize()와 같은 모양의 dict.
|
||||
|
||||
★ distance_m 은 항상 None 이다 — 지역명 검색으로 찾은 업체라 업장 좌표 기준 거리를
|
||||
모른다. local_content_service 의 body["distance_m"] 직접 접근 규약을 지키려면
|
||||
키 자체는 있어야 한다(값만 비운다).
|
||||
"""
|
||||
out = {
|
||||
"contentid": summary["place_id"],
|
||||
"content_type": LocalContentType.RESTAURANT.value,
|
||||
"distance_m": None,
|
||||
"name": summary["name"],
|
||||
"searchQuery": summary["name"],
|
||||
}
|
||||
if summary.get("address"):
|
||||
out["location"] = summary["address"]
|
||||
if summary.get("latitude"):
|
||||
out["latitude"] = summary["latitude"]
|
||||
if summary.get("longitude"):
|
||||
out["longitude"] = summary["longitude"]
|
||||
if summary.get("imageUrl"):
|
||||
out["imageUrl"] = summary["imageUrl"]
|
||||
return out
|
||||
|
||||
|
||||
def _as_float(value) -> float | None:
|
||||
try:
|
||||
return float(value) if value not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _distance_to_place(place_coords: tuple[float, float] | None, summary: dict) -> int | None:
|
||||
"""업장 좌표 ↔ 크롤링한 맛집 좌표 거리(m). 둘 중 하나라도 없으면 None.
|
||||
|
||||
★ 외부 호출 없는 순수 계산이다 — 좌표는 이미 fetch_summary()가 같은 응답에서 받아 온
|
||||
값이라 이 계산에 드는 비용은 없다(common.utils.geo.haversine_m 재사용).
|
||||
"""
|
||||
if place_coords is None:
|
||||
return None
|
||||
lat, lng = _as_float(summary.get("latitude")), _as_float(summary.get("longitude"))
|
||||
if lat is None or lng is None:
|
||||
return None
|
||||
return round(haversine_m(place_coords[0], place_coords[1], lat, lng))
|
||||
|
||||
|
||||
async def _place_coordinates(place_id) -> tuple[float, float] | None:
|
||||
"""이 place 자신의 좌표. 크롤링한 맛집과의 거리 계산용으로만 쓴다.
|
||||
|
||||
★ 순환 import 회피: story_service → 이 모듈로 이어지는 사슬이 있어 지연 import 한다.
|
||||
"""
|
||||
from services.local_content_service import LocalContentService
|
||||
|
||||
place = await LocalContentService()._load_place(place_id)
|
||||
if place is None:
|
||||
return None
|
||||
lat, lng = _as_float(getattr(place, "latitude", None)), _as_float(getattr(place, "longitude", None))
|
||||
if lat is None or lng is None:
|
||||
return None
|
||||
return lat, lng
|
||||
|
||||
|
||||
async def _sync_site_personalization(place_id, restaurant_refs: list) -> None:
|
||||
"""`place_area_refs` 기준 맛집 연결 중 사이트 개인화 맵(site_sections.local)에 없는
|
||||
것만 채운다 — 이미 있는 값(거리·숨김)은 건드리지 않는다.
|
||||
|
||||
restaurant_refs: [(content_id, distance_m, hidden), ...] — 기존 연결 + 이번에 새로
|
||||
크롤링한 것 전부. 기존 것이 이미 맵에 있으면 손대지 않고, 없는 것(새로 추가한 것,
|
||||
또는 과거에 맵 갱신 없이 만들어진 것)만 채운다 — 그래서 자연히 자가복구도 된다.
|
||||
|
||||
★ 캔버스(스냅샷)는 `place_area_refs`가 아니라 이 맵만 읽는다(services/snapshot.py::
|
||||
_site_places). `place_area_refs`에만 쓰고 여기를 안 채우면, DB에는 들어가도 화면에는
|
||||
안 나온다.
|
||||
★ 순환 import 회피: local_content_service → story_service → 이 모듈로 이어지는 사슬이 있어
|
||||
지연 import 한다(story_service.run_local_sync 의 관례와 동일).
|
||||
"""
|
||||
if not restaurant_refs:
|
||||
return
|
||||
from services.local_content_service import LocalContentService
|
||||
from services.snapshot import _site_places
|
||||
|
||||
places_map = dict(await _site_places(place_id))
|
||||
changed = False
|
||||
for content_id, distance_m, hidden in restaurant_refs:
|
||||
key = str(content_id)
|
||||
if key in places_map:
|
||||
continue
|
||||
places_map[key] = {"kind": "restaurant", "distanceMeters": distance_m, "hidden": bool(hidden)}
|
||||
changed = True
|
||||
if changed:
|
||||
await LocalContentService()._write_site_places(place_id, places_map)
|
||||
|
||||
|
||||
async def enrich_place_restaurants(place_id, region_label: str, region_code: str | None = None) -> dict:
|
||||
"""이 place 의 기존 맛집(TourAPI 등)은 그대로 두고, Perplexity 지역검색 상위 10개 이름 중
|
||||
아직 없는 곳만 네이버에서 크롤링해 추가한다. 기존 연결을 지우거나 숨기지 않는다.
|
||||
|
||||
흐름: ① Perplexity 로 이 지역 맛집 상위 10개 이름을 받는다 → ② 이름마다 이 place 에 이미
|
||||
연결된 맛집(TourAPI 또는 이전 크롤링분)과 유사도 매칭 — 있으면 건너뛰고(중복 크롤링 방지),
|
||||
없으면 네이버에서 크롤링해 새로 연결한다. 실패해도 예외를 던지지 않는다.
|
||||
"""
|
||||
stats = {"matched": 0, "added": 0, "checked": 0, "skipped": ""}
|
||||
|
||||
if not perplexity.is_configured():
|
||||
stats["skipped"] = "PERPLEXITY_API_KEY 미설정"
|
||||
return stats
|
||||
if not (region_label or "").strip():
|
||||
stats["skipped"] = "region_label 없음"
|
||||
return stats
|
||||
|
||||
names = await search_region_restaurants(region_label)
|
||||
if not names:
|
||||
stats["skipped"] = "Perplexity 검색 결과 없음"
|
||||
return stats
|
||||
|
||||
crud = PlaceContentCRUD()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_area_refs.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_by_place(s, place_id),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
stats["skipped"] = "기존 목록 조회 실패"
|
||||
return stats
|
||||
|
||||
existing = [r for r in (rows or []) if int(r.content_type) == LocalContentType.RESTAURANT.value]
|
||||
existing_titles = [r.title for r in existing if r.title]
|
||||
now = datetime.now(timezone.utc)
|
||||
place_coords = await _place_coordinates(place_id)
|
||||
new_entries: list = [] # [(content_id, distance_m), ...]
|
||||
|
||||
for name in names:
|
||||
stats["checked"] += 1
|
||||
if any(is_same_restaurant(name, title) for title in existing_titles):
|
||||
stats["matched"] += 1
|
||||
continue
|
||||
|
||||
naver_id = await naver_place_lookup.find_place_id(name, region_label)
|
||||
if not naver_id:
|
||||
continue
|
||||
|
||||
summary = await NaverPlaceAdapter().fetch_summary(naver_place_lookup.place_url(naver_id))
|
||||
if not summary:
|
||||
# ★ naver_place_lookup 이 찾은 id가 실제 상세 페이지가 아닐 수 있다(검색 원문에서
|
||||
# 상호 근처의 다른 숫자를 잘못 집은 경우) — 조용히 넘어가면 왜 스킵됐는지 안 보인다.
|
||||
LOG.w(f"[restaurant_enrich] '{name}' place={naver_id} 상세 조회 실패 — 포기")
|
||||
continue
|
||||
|
||||
body = to_area_content_body(summary)
|
||||
content_values = {
|
||||
"source": LocalSource.NAVER_CRAWL.value,
|
||||
"external_id": body["contentid"],
|
||||
"content_type": body["content_type"],
|
||||
"kind": AREA_KIND.get(body["content_type"]),
|
||||
"title": body["name"],
|
||||
"body": {k: v for k, v in body.items() if k not in _BODY_DROP},
|
||||
"latitude": _as_float(body.get("latitude")),
|
||||
"longitude": _as_float(body.get("longitude")),
|
||||
"region_code": region_code,
|
||||
"status": LocalContentStatus.PUBLISHED.value,
|
||||
"display_end_at": None,
|
||||
"collected_at": now,
|
||||
}
|
||||
write_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[area_contents.DBType()],
|
||||
[lambda s, v=content_values: crud.upsert_content(s, v)],
|
||||
)
|
||||
if write_err != ErrorType.SUCCESS:
|
||||
continue
|
||||
err_i, rows_i = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s, e=body["contentid"]: crud.find_content_id(s, LocalSource.NAVER_CRAWL.value, e),
|
||||
)
|
||||
if err_i != ErrorType.SUCCESS or not rows_i:
|
||||
continue
|
||||
content_id = rows_i[0]
|
||||
distance_m = _distance_to_place(place_coords, summary)
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_area_refs.DBType()],
|
||||
[lambda s, cid=content_id, d=distance_m: crud.upsert_ref(s, place_id, cid, d)],
|
||||
)
|
||||
|
||||
existing_titles.append(name)
|
||||
new_entries.append((content_id, distance_m))
|
||||
stats["added"] += 1
|
||||
LOG.i(f"[restaurant_enrich] place={place_id} '{name}' 네이버 크롤링으로 추가"
|
||||
f"{f' (거리 {distance_m}m)' if distance_m is not None else ''}")
|
||||
|
||||
restaurant_refs = [(r.local_content_id, r.distance_m, r.hidden) for r in existing]
|
||||
restaurant_refs += [(cid, dist, False) for cid, dist in new_entries]
|
||||
await _sync_site_personalization(place_id, restaurant_refs)
|
||||
return stats
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Prompt contract for regional restaurant name discovery (Perplexity)."""
|
||||
|
||||
SYSTEM_PROMPT = (
|
||||
"너는 지역 맛집 조사원이다. 실제로 영업 중인 음식점 상호명만 나열한다. "
|
||||
"설명이나 추천 이유는 쓰지 않는다."
|
||||
)
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"restaurants": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
}
|
||||
},
|
||||
"required": ["restaurants"],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_prompt(region_label: str) -> str:
|
||||
return "\n".join([
|
||||
f"지역: {region_label}",
|
||||
"",
|
||||
"이 지역에서 실제로 영업 중인 인기 음식점 상호명을 최대 10개 나열하라.",
|
||||
"- 상호명만 반환하고 주소·메뉴·설명은 쓰지 마라.",
|
||||
"- 폐업했거나 존재가 확실하지 않은 곳은 제외한다.",
|
||||
"- 확실한 곳이 10개 미만이면 있는 만큼만 반환한다.",
|
||||
])
|
||||
@@ -23,6 +23,7 @@ from pathlib import Path
|
||||
|
||||
from common.category_schema import get_schema
|
||||
from common.enums import (
|
||||
PUBLISHABLE_FACT_STATUSES,
|
||||
FactStatus,
|
||||
LinkChannel,
|
||||
LocalContentType,
|
||||
@@ -31,6 +32,8 @@ from common.enums import (
|
||||
SourceType,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from services.intro_summary import summarize_intro
|
||||
from services.stay_guide import nol_stay_guide
|
||||
|
||||
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
|
||||
SCHEMA_VERSION = 1
|
||||
@@ -611,6 +614,10 @@ def _local_place(row: dict, category: str):
|
||||
value = _text(body.get(key))
|
||||
if value:
|
||||
entry[key] = value
|
||||
# 수집한 소개를 버리면 stay 목업과 달리 실제 발행 카드에는 이름만 남는다.
|
||||
description = _text(body.get("description")) or _text(body.get("overview"))
|
||||
if description:
|
||||
entry["description"] = description
|
||||
_put_distance(entry, body)
|
||||
return entry
|
||||
|
||||
@@ -864,6 +871,10 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
"url": url,
|
||||
"title": _text(_get(row, "title")) or _CHANNEL_TITLE.get(int(channel), "채널"),
|
||||
"confirmed": _get(row, "confirmed_at") is not None,
|
||||
**({"stayGuide": nol_stay_guide(url, _get(row, "raw"))}
|
||||
if category == PlaceCategory.LODGING.value
|
||||
and _get(row, "confirmed_at") is not None
|
||||
and int(channel) == LinkChannel.YANOLJA.value else {}),
|
||||
})
|
||||
|
||||
# ── 소개문 ───────────────────────────────────────────
|
||||
@@ -1009,14 +1020,31 @@ def write_payload(payload: dict) -> str:
|
||||
return str(path)
|
||||
|
||||
|
||||
def emit_payload(place, snapshot: dict, site, version, links) -> str | None:
|
||||
async def prepare_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
"""미리보기·발행 공통 보강. 요약은 DB 스냅샷이 아니라 응답/산출물에만 싣는다."""
|
||||
payload = to_site_payload(place, snapshot, site, version, links)
|
||||
for fact in payload["facts"]:
|
||||
if fact["key"] != "intro" or fact["status"] not in {s.value for s in PUBLISHABLE_FACT_STATUSES}:
|
||||
continue
|
||||
try:
|
||||
summary = await summarize_intro(fact["key"], fact["value"])
|
||||
except Exception as ex:
|
||||
# 부가 요약 실패 때문에 미리보기·발행까지 막히면 원문도 읽을 수 없게 된다.
|
||||
LOG.w(f"[payload] 소개 요약 실패(원문 사용): {type(ex).__name__}")
|
||||
continue
|
||||
if summary and summary.strip():
|
||||
fact["summary"] = summary.strip()
|
||||
return payload
|
||||
|
||||
|
||||
async def emit_payload(place, snapshot: dict, site, version, links) -> str | None:
|
||||
"""payload 조립 + 파일 쓰기. 실패해도 예외를 밖으로 내보내지 않는다.
|
||||
|
||||
★ 발행 자체를 실패시키면 안 된다 — 게이트를 통과해 DB 에 남은 발행 기록은 이미 정확하고,
|
||||
payload 는 그것을 화면으로 옮기는 부수 산출물이다. 디스크가 없거나 권한이 없어서
|
||||
발행이 되돌려지는 게 더 나쁘다. 대신 경고 로그로 반드시 드러낸다."""
|
||||
try:
|
||||
payload = to_site_payload(place, snapshot, site, version, links)
|
||||
payload = await prepare_site_payload(place, snapshot, site, version, links)
|
||||
path = write_payload(payload)
|
||||
LOG.i(
|
||||
f"[payload] {payload['site']['slug']} → {path} "
|
||||
|
||||
@@ -163,11 +163,11 @@ class SiteService:
|
||||
"빌더에서는 보이는데 발행하면 없다"가 파서가 아니라 **렌더러**에서 났다.
|
||||
|
||||
★ 그래서 미리보기도 이 payload 하나만 먹는다. 발행이 굽는 것과 같은 함수
|
||||
(`snapshot.build_snapshot` → `site_payload.to_site_payload`)를 그대로 거치므로,
|
||||
(`snapshot.build_snapshot` → `site_payload.prepare_site_payload`)를 그대로 거치므로,
|
||||
여기서 갈릴 자리가 없다. 버전은 아직 없으니 0 으로 넘긴다 — 화면에 안 쓰인다.
|
||||
"""
|
||||
from services.build_service import ensure_site, _load_links
|
||||
from services.site_payload import to_site_payload
|
||||
from services.site_payload import prepare_site_payload
|
||||
from services.snapshot import build_snapshot
|
||||
|
||||
err_type, place = await self._load_place(user_info, place_id)
|
||||
@@ -179,7 +179,7 @@ class SiteService:
|
||||
snapshot = await build_snapshot(place)
|
||||
# ★ version 은 None 이다. 발행 전이라 버전 행이 없고, payload 의 site.version 은
|
||||
# 캐시 무효화 키라 미리보기에서는 뜻이 없다(to_site_payload 가 0 으로 떨어뜨린다).
|
||||
return to_site_payload(place, snapshot, site, None, links)
|
||||
return await prepare_site_payload(place, snapshot, site, None, links)
|
||||
|
||||
# ---- 사이트 주소(네임스페이스) ---------------------------------------
|
||||
# 규칙(정규식·예약어)은 services/site_slug 한 곳에만 있다. 확인과 저장이 그것을 같이 쓴다.
|
||||
|
||||
@@ -32,6 +32,7 @@ from common.enums import (
|
||||
ErrorType,
|
||||
FactStatus,
|
||||
LocalContentStatus,
|
||||
LocalContentType,
|
||||
LocalSource,
|
||||
MediaStatus,
|
||||
PlaceCategory,
|
||||
@@ -43,7 +44,7 @@ from services.external.naver import region_key
|
||||
_PUBLISHABLE = tuple(s.value for s in PUBLISHABLE_FACT_STATUSES)
|
||||
|
||||
# 지역 정보를 종류별로 몇 건까지 박제할지.
|
||||
# ★ 종류별(맛집·관광지·축제·코스) 노출 상한 — 화면·캔버스·발행본 모두 이 수까지만 보여준다(2026-09-07 결정).
|
||||
# ★ 관광지·축제·코스 노출 상한. 맛집은 수집된 전체를 발행한다(2026-09-14).
|
||||
# 스냅샷은 site_versions.snapshot 에 통째로 들어가므로 반경 안 수백 건을 다 박제하면 버전 행마다 복사된다.
|
||||
# 두 캐시(지역 수기 항목 + 업장 반경)를 **합쳐서** 센다 — 따로 세면 최대 40건이 나간다.
|
||||
_LOCAL_MAX_PER_TYPE = 20
|
||||
@@ -362,14 +363,15 @@ async def _site_places(place_id) -> dict:
|
||||
|
||||
|
||||
def _local_rows(rows, seen: dict[int, int], source: int | None = None) -> list[dict]:
|
||||
"""행 → 스냅샷 항목. 종류별 상한(_LOCAL_MAX_PER_TYPE)은 들어온 순서(정렬)대로 자른다.
|
||||
"""행 → 스냅샷 항목. 맛집 외 종류별 상한은 들어온 순서(정렬)대로 자른다.
|
||||
seen 은 호출측이 넘겨 두 캐시에 걸쳐 누적한다."""
|
||||
out = []
|
||||
for row in rows:
|
||||
content_type = int(row.content_type)
|
||||
kind = getattr(row, "kind", None)
|
||||
taken = seen.get(content_type, 0)
|
||||
if taken >= _LOCAL_MAX_PER_TYPE:
|
||||
# 맛집 수집은 전체 보존인데 여기서 20개로 자르면 발행본만 일부가 사라진다.
|
||||
if content_type != LocalContentType.RESTAURANT.value and taken >= _LOCAL_MAX_PER_TYPE:
|
||||
continue
|
||||
seen[content_type] = taken + 1
|
||||
body = row.body if isinstance(row.body, dict) else {}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""확정된 NOL 링크의 수집 원문에서 공개 안내 섹션만 전달한다."""
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def nol_stay_guide(url: str, raw) -> dict:
|
||||
try:
|
||||
parsed = urlsplit(url)
|
||||
except ValueError:
|
||||
return {}
|
||||
if parsed.scheme != "https" or parsed.hostname != "nol.yanolja.com":
|
||||
return {}
|
||||
if not re.fullmatch(r"/stay/domestic/\d+/?", parsed.path):
|
||||
return {}
|
||||
text = raw.get("text") if isinstance(raw, dict) else None
|
||||
if not isinstance(text, str):
|
||||
return {}
|
||||
|
||||
labels = {"시설/서비스": "service", "이용 안내": "policy", "예약 공지": "reservation"}
|
||||
# 수집기가 붙인 경계로만 나눈다. 규정 안의 괄호나 문장은 분리하지 않는다.
|
||||
sections = re.split(r"(?m)^\[(숙소 소개|시설/서비스|이용 안내|예약 공지)\]\s*\n", text)
|
||||
guide = {}
|
||||
for label, body in zip(sections[1::2], sections[2::2]):
|
||||
if label not in labels:
|
||||
continue
|
||||
lines = body.strip().splitlines()
|
||||
if lines and lines[0].strip() == label:
|
||||
lines.pop(0)
|
||||
# 제목 중복과 UI 버튼만 제외한다. 요약·추론 없이 수집 문장을 보존한다.
|
||||
body = "\n".join(line for line in lines if line.strip() != "전체보기").strip()
|
||||
if body:
|
||||
guide[labels[label]] = body
|
||||
if guide:
|
||||
guide["fields"] = structured_fields(guide)
|
||||
return guide
|
||||
|
||||
|
||||
def structured_fields(guide: dict) -> list[dict]:
|
||||
"""확실한 표기만 구조화한다. 매칭되지 않은 내용은 안내 원문에 남는다."""
|
||||
policy = guide.get("policy", "")
|
||||
service = guide.get("service", "")
|
||||
reservation = guide.get("reservation", "")
|
||||
lines = {line.strip().lstrip("- ") for line in (policy + "\n" + reservation).splitlines()}
|
||||
facilities = {line.strip() for line in service.splitlines()}
|
||||
fields = []
|
||||
|
||||
def add(key, label, value, group="rules", note=None):
|
||||
fields.append(dict(key=key, label=label, value=value, group=group,
|
||||
**({"note": note} if note else {})))
|
||||
|
||||
for token, key, label in (("체크인", "check_in_time", "체크인 시간"),
|
||||
("체크아웃", "check_out_time", "체크아웃 시간")):
|
||||
matches = set(re.findall(rf"{token}\s+([0-2]\d:[0-5]\d)(?!\d)", policy))
|
||||
if len(matches) == 1:
|
||||
value = matches.pop()
|
||||
if int(value[:2]) < 24:
|
||||
add(key, label, value)
|
||||
fees = [re.fullmatch(r"전 연령 동일 1인당\s*([\d,]+)\s*(만)?원", line) for line in lines]
|
||||
amounts = {int(m[1].replace(",", "")) * (10000 if m[2] else 1) for m in fees if m}
|
||||
if len(amounts) == 1:
|
||||
add("extra_person_fee", "인원 추가 요금", f"{amounts.pop():,}원", note="1인당 · 전 연령 동일")
|
||||
if "반려동물 입실금지" in lines and not any("반려동물 입실가능" == line for line in lines):
|
||||
add("pet_allowed", "반려동물 동반", "불가")
|
||||
if "전 구역 금연" in lines:
|
||||
add("smoking", "흡연", "불가", "facilities", "전 구역 금연")
|
||||
for token, key, label in (("주차가능", "parking", "주차"), ("와이파이", "wifi", "와이파이"),
|
||||
("취사가능", "cooking_allowed", "취사")):
|
||||
if token in facilities:
|
||||
restrictions = [line.strip().lstrip("- ") for line in reservation.splitlines()
|
||||
if "조리금지" in line or "조리 금지" in line]
|
||||
add(key, label, "가능", "facilities",
|
||||
"\n".join(restrictions) if key == "cooking_allowed" and restrictions else None)
|
||||
known = [name for name in ("욕조", "개별 화장실", "주방", "테라스/발코니", "OTT (스트리밍 서비스)",
|
||||
"다이닝룸", "벽난로", "어메니티", "카페형룸") if name in facilities]
|
||||
if known:
|
||||
add("facilities", "부대시설", ", ".join(known), "facilities")
|
||||
return fields
|
||||
@@ -33,6 +33,7 @@ from crud.local_content_crud import LocalContentCRUD
|
||||
from services.grounding import story as grounding
|
||||
from services.external import tour_api, wikimedia
|
||||
from services.llm import perplexity
|
||||
from services.local_restaurant_enrichment import enrich_place_restaurants
|
||||
from services.prompts import story as prompts
|
||||
|
||||
# ★ 다섯을 **순차로** 부른다. 처음엔 동시에 띄웠는데 실측(2026-09-09, 전북 군산시)에서
|
||||
@@ -278,6 +279,13 @@ async def run_local_sync(job: dict) -> dict:
|
||||
if not synced.result.success:
|
||||
LOG.w(f"[story] place={place_id} 반경 수집 실패(이야기는 계속한다): {synced.msg}")
|
||||
|
||||
# ── 1.5 주변 맛집 보강(Perplexity + 네이버) — 업장마다 ─────────────
|
||||
# ★ TourAPI 블록 바로 뒤다. 그쪽이 이미 만든 place_area_refs 개수를 기준으로
|
||||
# "10건 미만이면 채운다"를 판단하기 때문이다(services/local_restaurant_enrichment.py).
|
||||
out["restaurant_enrichment"] = await enrich_place_restaurants(
|
||||
uuid.UUID(str(place_id)), region_label, region_code,
|
||||
)
|
||||
|
||||
# ── 2. 여행 일정(LLM) — 업장마다 ──────────────────────────────────
|
||||
# ★ 이야기와 같은 잡에 둔다. 사장님에게는 "주변이 채워졌나" 하나이고, 둘 다 Perplexity 라
|
||||
# 같은 키로 나간다 — 잡을 나누면 두 잡이 동시에 떠서 서로를 429 로 막는다.
|
||||
|
||||
Reference in new issue
Block a user