Merge remote-tracking branch 'origin/main' into feature/social-post
# Conflicts: # docs/DECISIONS.md # docs/DEVLOG.md # solution/backend/requirements.txt # solution/backend/scheduler/__init__.py # solution/backend/worker/handlers.py # solution/site/src/pages/HomePage.tsx # solution/site/src/sections/index.ts
This commit is contained in:
commit
58d6249102
502 files changed
+127276
-5267
No files matched your search
@@ -22,7 +22,7 @@ def is_configured() -> bool:
|
||||
|
||||
|
||||
def output_dir() -> Path:
|
||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites"))
|
||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/solution/site/out"))
|
||||
|
||||
|
||||
def _content_type(path: Path) -> str:
|
||||
@@ -104,7 +104,7 @@ def _upload_shared(container, root: Path, prefix: str) -> set[str]:
|
||||
for entry in sorted(root.iterdir()):
|
||||
# `s/` 는 사이트별 디렉터리다 — 발행한 사이트 하나만 따로 올린다.
|
||||
# (여기서 함께 올리면 한 명이 발행할 때마다 전체 사이트를 다시 올리게 된다.)
|
||||
if entry.name.startswith(".") or entry.name == SITE_ROOT_DIR:
|
||||
if entry.name.startswith(".") or entry.name in {SITE_ROOT_DIR, "versions"}:
|
||||
continue
|
||||
if entry.is_dir():
|
||||
uploaded |= _upload_tree(container, root, entry.name, prefix)
|
||||
|
||||
@@ -29,21 +29,31 @@ from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.site_crud import SiteCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services import azure_static, indexnow, publish_gate, render_report, site_payload, site_thumbnail, song_service
|
||||
from services import (
|
||||
azure_static,
|
||||
indexnow,
|
||||
publish_gate,
|
||||
render_service,
|
||||
seo_keywords,
|
||||
site_payload,
|
||||
site_thumbnail,
|
||||
song_service,
|
||||
)
|
||||
from services.local_content_service import LocalContentService
|
||||
from services.site_payload import emit_payload
|
||||
from services.snapshot import build_snapshot
|
||||
from common.job_errors import PermanentJobError
|
||||
|
||||
_site_crud = SiteCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
|
||||
# 렌더러가 이 버전을 굽고 보고서를 돌려줄 때까지 기다리는 시간.
|
||||
# ★ 넉넉해야 한다. 짧으면 멀쩡한 발행이 "렌더 대기 초과"로 실패한다 —
|
||||
# 렌더러는 payload 를 2초 주기로 보고, 사이트 하나 굽는 데 1초 남짓 걸린다.
|
||||
# 렌더러 subprocess 가 끝나기를 기다리는 시간(사진 내려받기 포함).
|
||||
# ★ 넉넉해야 한다. 짧으면 멀쩡한 발행이 "렌더 시간 초과"로 실패한다 — 처음 보는 사진을
|
||||
# 내려받는 발행은 몇 초가 더 걸린다(mirrorMedia, prerender.ts).
|
||||
RENDER_TIMEOUT_SEC = float(os.environ.get("RENDER_TIMEOUT_SEC") or 180)
|
||||
|
||||
|
||||
class BuildAborted(RuntimeError):
|
||||
class BuildAborted(PermanentJobError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||
|
||||
|
||||
@@ -64,10 +74,13 @@ async def ensure_site(place_id: str) -> "sites":
|
||||
return row
|
||||
|
||||
|
||||
async def _load_links(place_id: str) -> list:
|
||||
async def load_channel_links(place_id: str) -> list:
|
||||
"""채널 링크(야놀자·네이버 플레이스·인스타…).
|
||||
|
||||
스냅샷에 담기지 않는 유일한 발행 재료라 여기서 읽어 payload 로 넘긴다.
|
||||
스냅샷에 담기지 않는 유일한 발행 재료라 여기서 읽어 payload 로 넘긴다 — 재빌드(run_build)
|
||||
도 롤백(rollback_service.run_rollback)도 같은 함수를 쓴다. **스냅샷에는 안 싣는다** —
|
||||
롤백이 옛 스냅샷으로 다시 구워도 링크는 항상 지금 확정된 것을 보여줘야 한다(끊긴 링크를
|
||||
옛 버전째 되살리면 안 된다).
|
||||
★ 실패해도 빈 목록으로 진행한다 — 링크가 없다고 발행을 막을 이유가 없다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_channels.DBType(),
|
||||
@@ -157,6 +170,19 @@ async def run_build(job: dict) -> dict:
|
||||
|
||||
snapshot = await build_snapshot(place)
|
||||
|
||||
# ★ 메타 태그용 검색 키워드(SiteOntology). **스냅샷에 싣는다** — payload 는 스냅샷만 보고 만들고,
|
||||
# "이 버전에 어떤 키워드가 나갔나" 가 site_versions.snapshot 에 남는다(services/seo_keywords 머리주석).
|
||||
# ★ 실패해도 빌드는 계속한다. 주변 정보·노래와 같은 규칙이다 — 키워드 없이 예전 제목·메타로 나간다.
|
||||
# ★ 재빌드(publish=False)에도 부른다. 로컬 임베딩이라 비용이 없고, 재빌드한 버전과 발행한 버전의
|
||||
# 제목이 갈리면 "눌러 본 것과 나간 것이 다르다" 가 된다.
|
||||
seo: dict | None = None
|
||||
try:
|
||||
seo = await seo_keywords.fetch(place_id, snapshot)
|
||||
except Exception as ex: # noqa: BLE001 — 키워드 실패가 발행을 죽이면 안 된다
|
||||
LOG.w(f"[build] place={place_id} 검색 키워드 실패(키워드 없이 발행): {type(ex).__name__}: {ex}")
|
||||
if seo:
|
||||
snapshot["seo"] = seo
|
||||
|
||||
v_err, version_no = await DB_SESSION_MNG.execute_lambda(
|
||||
site_versions.DBType(), DBWRType.DB_READ.value, lambda s: _site_crud.next_version_no(s, site.site_id)
|
||||
)
|
||||
@@ -180,6 +206,9 @@ async def run_build(job: dict) -> dict:
|
||||
# 잡 결과에 남긴다 — "노래가 왜 없나" 를 잡 하나만 열어 보면 알 수 있어야 한다.
|
||||
if song_result is not None:
|
||||
result["song"] = song_result
|
||||
# "제목이 왜 예전 그대로인가" 도 같다 — 키워드가 실렸으면 잡 결과에 보인다(없으면 로그의 [seo] 줄).
|
||||
if seo is not None:
|
||||
result["seo"] = seo
|
||||
now = GTime.UTC()
|
||||
|
||||
async def _fail(reason: str, gate: publish_gate.GateResult | None = None, extra: dict | None = None):
|
||||
@@ -224,24 +253,25 @@ async def run_build(job: dict) -> dict:
|
||||
site.status = SiteStatus.PUBLISHED.value
|
||||
site.published_at = site.published_at or now
|
||||
|
||||
links = await _load_links(place_id)
|
||||
payload_path = emit_payload(place, snapshot, site, version, links)
|
||||
links = await load_channel_links(place_id)
|
||||
payload_path = await emit_payload(place, snapshot, site, version, links, publish=want_publish)
|
||||
if not payload_path:
|
||||
return await _fail("payload 를 쓰지 못했다 — 렌더러에 넘길 입력이 없다")
|
||||
result["payload_path"] = payload_path
|
||||
|
||||
slug = site_payload.publish_slug(place, site)
|
||||
|
||||
# ---- 렌더 결과를 기다린다 ----
|
||||
# ---- 렌더러를 직접 돌린다 ----
|
||||
# ★ 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 렌더러가 자기 산출물을 대조해
|
||||
# 구조화 데이터 불일치와 고유 콘텐츠 수를 보고서로 돌려준다.
|
||||
report = await render_report.wait_for(slug, version_no, RENDER_TIMEOUT_SEC)
|
||||
if report is None:
|
||||
# ★ payload=False(미발행)면 렌더러는 `out/versions/<slug>/<version>/` 에만 굽고 공개
|
||||
# 주소(`out/s/<slug>`)는 건드리지 않는다 — emit_payload 에 실은 publish 플래그가 정한다.
|
||||
try:
|
||||
report = await render_service.render_site(payload_path, version_no, RENDER_TIMEOUT_SEC)
|
||||
except render_service.RenderFailed as ex:
|
||||
# ★ 발행하지 않는다. 페이지가 있는지 확인하지 못한 채 "발행됨"으로 남기면
|
||||
# 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다.
|
||||
return await _fail(
|
||||
f"렌더 결과를 {RENDER_TIMEOUT_SEC}초 안에 받지 못했다 — 렌더러가 도는지 확인이 필요하다"
|
||||
)
|
||||
return await _fail(str(ex))
|
||||
|
||||
mismatches = list(report.get("mismatches") or [])
|
||||
# ★ None(재지 못했다)과 0(재 봤더니 0건)을 뭉개지 않는다. 게이트는 raw 를 보고,
|
||||
@@ -283,8 +313,9 @@ async def run_build(job: dict) -> dict:
|
||||
thumbnail_url = None
|
||||
if want_publish:
|
||||
try:
|
||||
await render_service.activate_site(slug, version_no)
|
||||
azure_result = await azure_static.publish(slug)
|
||||
except azure_static.AzurePublishError as ex:
|
||||
except (azure_static.AzurePublishError, render_service.RenderFailed) as ex:
|
||||
return await _fail(str(ex), None, stamp)
|
||||
if azure_result:
|
||||
result["azure"] = azure_result
|
||||
@@ -358,4 +389,3 @@ async def run_build(job: dict) -> dict:
|
||||
version.build_status = BuildStatus.BUILT.value
|
||||
version.built_at = now
|
||||
return result
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
수집 결과는 사용자가 승인하기 전까지 사이트에 노출하지 않는다.
|
||||
"""
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
@@ -14,15 +15,17 @@ 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
|
||||
from common.job_errors import PermanentJobError
|
||||
|
||||
_place_crud = PlaceCRUD()
|
||||
_fact_crud = FactCRUD()
|
||||
|
||||
|
||||
class CollectAborted(RuntimeError):
|
||||
class CollectAborted(PermanentJobError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남아 운영자가 본다."""
|
||||
|
||||
|
||||
@@ -107,9 +110,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 +189,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 +277,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
|
||||
|
||||
@@ -13,15 +13,23 @@
|
||||
그 전제가 깨지면(플랫폼 URL 이 흘러들어오면) 정당성도 같이 깨지므로,
|
||||
아래 _DENY_HOSTS 로 **구조적으로** 막는다. 운영자가 실수로 넣어도 안 긁힌다.
|
||||
|
||||
★ 표본 근거 — 왜 이 어댑터가 숙박에서 특히 값이 큰가
|
||||
네이버 지역검색 `link` 필드 충전율(업종별 25건 표본): 숙박 96% 중 자체 도메인 19건,
|
||||
음식점 64%, 카페 92% 중 인스타 17건. 숙박은 자체 홈페이지 보유율이 3업종 중 가장 높다.
|
||||
★ NOL(nol.yanolja.com) 은 이 어댑터가 아니라 전용 어댑터가 받는다(2026-09-14).
|
||||
범용 HTML 수집을 OTA 로 넓힌 것이 아니다 — 레지스트리가 yanolja 를 이 어댑터보다
|
||||
**앞에** 등록하므로 그 한 패턴만 전용 경로로 가고, 나머지 야놀자·여기어때 주소는
|
||||
여기 _DENY_HOSTS 에서 그대로 막힌다.
|
||||
★ 실측(2026-09-15): 이 deny 목록에서 두 호스트가 빠져 있던 동안 범용 HTML 수집이
|
||||
`www.yanolja.com` · `goodchoice.kr` 을 받았다. 전용 어댑터를 들이는 것과
|
||||
범용 수집기를 그 플랫폼에 푸는 것은 다른 일이다.
|
||||
|
||||
**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)**
|
||||
캡차 우회 · 봇 탐지 우회 · IP 회전. 여기에 하나 더 —
|
||||
**robots.txt 를 확인하고 그대로 따른다.** 사장님 홈페이지라도 예외 없다.
|
||||
막히면 실패로 돌려주고 폴백 3단계로 간다(공식 API → 사장님 붙여넣기 → 최소 정보 생성).
|
||||
|
||||
★ 표본 근거 — 왜 이 어댑터가 숙박에서 특히 값이 큰가
|
||||
네이버 지역검색 `link` 필드 충전율(업종별 25건 표본): 숙박 96% 중 자체 도메인 19건,
|
||||
음식점 64%, 카페 92% 중 인스타 17건. 숙박은 자체 홈페이지 보유율이 3업종 중 가장 높다.
|
||||
|
||||
★ 값을 만드는 원칙
|
||||
구조화된 것(JSON-LD schema.org, OpenGraph)만 fact 로 올린다. 본문 텍스트에서
|
||||
키워드를 주워 억지로 매핑하지 않는다 — 유일한 예외가 체크인·체크아웃 시각인데,
|
||||
@@ -61,14 +69,14 @@ HEADERS = {
|
||||
}
|
||||
|
||||
# ★ 이 호스트들은 이 어댑터가 절대 건드리지 않는다.
|
||||
# - 전용 어댑터가 따로 있거나(naver_place)
|
||||
# - 전용 어댑터가 따로 있거나(naver_place · yanolja)
|
||||
# - 실측·판례로 수집 불가 결론이 난 곳이거나(야놀자·여기어때·카카오맵)
|
||||
# - 공식 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억 선례
|
||||
"yanolja.com", "goodchoice.kr", # OTA — 403 + 민사 10억 선례. NOL 은 전용 어댑터가 먼저 받는다
|
||||
"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,
|
||||
)
|
||||
@@ -1,250 +1,39 @@
|
||||
"""소개문·FAQ 생성 — COPY 잡이 하는 일.
|
||||
|
||||
★ LLM 은 사실을 만들지 않는다. 문장만 쓴다.
|
||||
- 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다.
|
||||
- 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다).
|
||||
- 소개문·FAQ 는 **바로 노출값**이다(VERIFIED). 승인 단계를 두지 않는다 — 2026-09-10 결정.
|
||||
게이트는 앞에 있다: 입력이 확인된 fact 뿐이고, 근거 없는 FAQ 는 저장조차 하지 않는다.
|
||||
확인된 사실로 쓴 문장을 한 번 더 승인받게 하면 같은 사실을 두 번 승인하는 셈이고,
|
||||
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
|
||||
(근거·실측: services/fact_service.upsert_fact · docs/DECISIONS.md 7절).
|
||||
- 사장님이 고친 문장(CORRECTED)은 재생성이 덮지 않는다. 그 잠금은 그대로다.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from common.category_schema import CategorySchemaError, get_schema
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import place_facts, place_faqs, place_channels, places, place_units
|
||||
from common.enums import (
|
||||
PUBLISHABLE_FACT_STATUSES,
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
FactStatus,
|
||||
PlaceCategory,
|
||||
SourceType,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from common.utils.gtime import GTime
|
||||
from config.server_configs import external_api_config
|
||||
from crud.fact_crud import FactCRUD
|
||||
from crud.faq_crud import FaqCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from router.v1.fact.protocol import Req_UpsertFact
|
||||
from services import place_research
|
||||
"""COPY 흐름. 단계 구현: copy_steps / 프롬프트: prompts/copy / 호출·검증: external/gemini_text."""
|
||||
from services.copy_steps import CopyAborted, prepare_copy, generate_copy, save_copy, fill_faqs
|
||||
from services.external import gemini_text
|
||||
from services.fact_service import FactService
|
||||
from services.job_progress import JobProgress
|
||||
|
||||
_fact_crud = FactCRUD()
|
||||
_faq_crud = FaqCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
|
||||
|
||||
class CopyAborted(RuntimeError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||
COPY_STEPS = ("prepare", "generate", "save", "faq_fill")
|
||||
|
||||
|
||||
async def run_copy(job: dict) -> dict:
|
||||
"""COPY 잡 핸들러. payload: {place_id, owner_user_id, requested_by?}"""
|
||||
progress = JobProgress(job, COPY_STEPS)
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
async with progress.step("prepare"):
|
||||
inputs = await prepare_copy(payload["place_id"], payload["owner_user_id"])
|
||||
|
||||
if not gemini_text.is_configured():
|
||||
raise CopyAborted("GEMINI_API_KEY 미설정 — 소개문·FAQ 를 생성할 수 없다")
|
||||
copy = None
|
||||
note = None
|
||||
if inputs.ungrounded or not gemini_text.is_configured():
|
||||
note = "근거로 쓸 확인된 fact 가 없다" if inputs.ungrounded else "GEMINI_API_KEY 미설정"
|
||||
await progress.skip("generate", "no_facts" if inputs.ungrounded else "not_configured")
|
||||
if inputs.catalog is None and not inputs.ungrounded:
|
||||
raise CopyAborted(note)
|
||||
else:
|
||||
async with progress.step("generate"):
|
||||
copy = await generate_copy(inputs)
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
async with progress.step("save"):
|
||||
result = await save_copy(inputs, copy)
|
||||
|
||||
try:
|
||||
schema = get_schema(PlaceCategory(place.category))
|
||||
except (CategorySchemaError, ValueError) as ex:
|
||||
raise CopyAborted(f"지원하지 않는 업종: {place.category}") from ex
|
||||
if inputs.catalog is not None:
|
||||
async with progress.step("faq_fill"):
|
||||
result["faq_fill"] = await fill_faqs(
|
||||
inputs.place.place_id, inputs.catalog, inputs.known_fact_keys, inputs.place.phone,
|
||||
)
|
||||
else:
|
||||
await progress.skip("faq_fill", "no_catalog")
|
||||
|
||||
# ★ 노출 가능한 fact 만 근거로 준다. 미검증 값으로 쓴 문장은 그 자체가 미검증이다.
|
||||
pid = uuid.UUID(place_id)
|
||||
f_err, fact_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _fact_crud.list_facts(s, pid, None, None, True, True),
|
||||
)
|
||||
if f_err != ErrorType.SUCCESS:
|
||||
raise CopyAborted(f"fact 조회 실패: {f_err.name}")
|
||||
|
||||
grounded = [
|
||||
gemini_text.FactInput(
|
||||
key=r.key,
|
||||
label=(schema.get(r.key).label if schema.get(r.key) else r.key),
|
||||
value=r.value,
|
||||
unit=r.unit,
|
||||
)
|
||||
for r in fact_rows
|
||||
if r.unit_id is None and (r.value or "").strip()
|
||||
]
|
||||
# ★ 수집 원문도 근거로 넘긴다 — fact 가 아니라 place_channels.raw 에 박제된 글이다.
|
||||
#
|
||||
# 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다.
|
||||
# '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면
|
||||
# ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다.
|
||||
#
|
||||
# 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다.
|
||||
# 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31).
|
||||
# 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다.
|
||||
# ★ 확정 링크만 읽던 것을 **조사 근거까지** 읽게 넓혔다(2026-09-10).
|
||||
# 업소 조사(`place_research`)는 남이 쓴 글이라 확정하지 않는다 — 공식 채널이 아니므로
|
||||
# 발행본의 sameAs·푸터에 나가면 안 된다. 그런데 그것 때문에 여기서도 안 읽혀서,
|
||||
# 조사해 온 재료가 소개문에 한 글자도 닿지 않았다. 확정 여부는 "화면에 채널로
|
||||
# 내보낼 것인가" 의 판단이지 "근거로 읽을 것인가" 의 판단이 아니다.
|
||||
# ★ 다만 아무 미확정 링크나 읽지는 않는다 — raw.kind 가 research 인 것만이다.
|
||||
# 미확정 채널 URL 은 동명 업소일 수 있고(그게 확정 절차의 이유다), 조사 근거는
|
||||
# 상호 대조를 통과한 것만 적재된다(`grounding/place_research.parse_items`).
|
||||
records: list[str] = []
|
||||
l_err, link_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_channels.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.list_links(s, pid, False),
|
||||
)
|
||||
if l_err == ErrorType.SUCCESS:
|
||||
for link in (link_rows or []):
|
||||
raw = link.raw if isinstance(link.raw, dict) else {}
|
||||
if link.confirmed_at is None and raw.get("kind") != place_research.RAW_KIND:
|
||||
continue
|
||||
text = (raw.get("text") or "").strip()
|
||||
if text:
|
||||
# ★ fact 목록이 아니라 records 로 넘긴다. fact 자리에 넣으면 모델이 값 하나로
|
||||
# 읽고 거의 쓰지 않는다(prompts/copy.build_prompt 머리주석의 실측).
|
||||
records.append(text[:4000])
|
||||
# ground_check 는 여전히 이 글을 근거로 인정해야 한다 — 근거 목록에도 남긴다.
|
||||
grounded.append(gemini_text.FactInput(
|
||||
key=f"source:{link.link_id}", label="수집 원문", value=text[:4000],
|
||||
))
|
||||
|
||||
# 객실·메뉴 요약도 근거로 넘긴다 — "최대 4명" 같은 수치가 통과하려면 근거에 있어야 한다.
|
||||
#
|
||||
# ★ 근거 없음 판정보다 **먼저** 읽는다.
|
||||
# 예전에는 사업장 fact 가 0건이면 여기까지 오지 못하고 되돌아갔다. 그런데 네이버에
|
||||
# 요금표만 올라온 모텔은 사업장 fact 가 0건이고 객실 fact 만 있다 — 쓸 근거가 있는데도
|
||||
# "근거 없음"으로 끝나 소개문·FAQ 가 영구히 생기지 않았다.
|
||||
u_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_units.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.list_units(s, pid),
|
||||
)
|
||||
unit_summaries = []
|
||||
if u_err == ErrorType.SUCCESS:
|
||||
by_unit: dict = {}
|
||||
for r in fact_rows:
|
||||
if r.unit_id and (r.value or "").strip():
|
||||
by_unit.setdefault(str(r.unit_id), {})[r.key] = r.value
|
||||
unit_summaries = [
|
||||
{
|
||||
"name": u.name,
|
||||
"facts": by_unit.get(str(u.unit_id), {}),
|
||||
# 스키마 라벨·단위를 같이 넘긴다 — 이게 없으면 프롬프트에 'weekday_price' 라는
|
||||
# 날 key 가 그대로 실려 모델이 그 낱말로 문장을 쓴다.
|
||||
"labels": {
|
||||
key: {
|
||||
"label": schema.get(key).label if schema.get(key) else key,
|
||||
"unit": schema.get(key).unit if schema.get(key) else None,
|
||||
}
|
||||
for key in by_unit.get(str(u.unit_id), {})
|
||||
},
|
||||
}
|
||||
for u in unit_rows
|
||||
if by_unit.get(str(u.unit_id))
|
||||
]
|
||||
|
||||
if not grounded and not unit_summaries:
|
||||
# 근거가 없으면 아무것도 쓰지 않는다 — 유료 호출조차 하지 않는다.
|
||||
return {"place_id": place_id, "intro": False, "faqs": 0, "note": "근거로 쓸 확인된 fact 가 없다"}
|
||||
|
||||
try:
|
||||
copy = await gemini_text.generate_copy(
|
||||
place.name,
|
||||
PlaceCategory(place.category),
|
||||
grounded,
|
||||
unit_summaries=unit_summaries or None,
|
||||
records=records or None,
|
||||
model=external_api_config.gemini_text_model,
|
||||
)
|
||||
except gemini_text.GeminiNotConfigured as ex:
|
||||
raise CopyAborted(str(ex)) from ex
|
||||
|
||||
now = GTime.UTC()
|
||||
stat = {
|
||||
"place_id": place_id,
|
||||
"grounded_facts": len(grounded),
|
||||
"intro": False,
|
||||
"meta": False,
|
||||
"faqs": 0,
|
||||
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
|
||||
"rejected": [list(r) for r in (copy.rejected or [])][:20],
|
||||
}
|
||||
|
||||
actor = UserInfo(
|
||||
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
|
||||
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
|
||||
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
|
||||
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
|
||||
user_id=owner_user_id,
|
||||
id="generator",
|
||||
role=1,
|
||||
)
|
||||
service = FactService(_fact_crud, _place_crud)
|
||||
|
||||
# 소개문·메타는 fact 로 들어간다 — FactService 가 allow_llm 을 다시 확인하고(뒷문 없음),
|
||||
# LLM 출처라 후보가 아니라 노출값으로 앉힌다(upsert_fact 의 LLM 분기).
|
||||
for key, text_value in (("intro", copy.intro), ("meta_description", copy.meta_description)):
|
||||
if not (text_value or "").strip():
|
||||
continue
|
||||
if not (schema.get(key) and schema.get(key).allow_llm):
|
||||
# 이 업종 스키마가 LLM 작성을 허용하지 않는 필드다. 조용히 건너뛴다.
|
||||
continue
|
||||
res = await service.upsert_fact(
|
||||
actor, place_id,
|
||||
Req_UpsertFact(
|
||||
key=key, value=text_value.strip(),
|
||||
source_type=SourceType.LLM, source_url=f"gemini:{external_api_config.gemini_text_model}",
|
||||
),
|
||||
)
|
||||
if res.result.success:
|
||||
stat["intro" if key == "intro" else "meta"] = True
|
||||
else:
|
||||
stat["rejected"].append([key, res.result.desc])
|
||||
|
||||
# 확인 안 된 기존 생성 FAQ 는 내리고 새로 넣는다. 사람이 확인한 FAQ 는 건드리지 않는다.
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_faqs.DBType(),
|
||||
lambda s: _faq_crud.expire_generated(s, pid, now),
|
||||
)
|
||||
for order, faq in enumerate(copy.faqs or []):
|
||||
if not faq.fact_keys:
|
||||
# ★ 근거 없는 FAQ 는 저장하지 않는다.
|
||||
stat["rejected"].append([faq.question, "근거 fact 없음"])
|
||||
continue
|
||||
row = place_faqs(
|
||||
place_id=pid,
|
||||
question=faq.question,
|
||||
answer=faq.answer,
|
||||
source_fact_ids=list(faq.fact_keys),
|
||||
generated_by=SourceType.LLM.value,
|
||||
# ★ 바로 노출한다 (2026-09-10 결정 — fact_service.upsert_fact 주석이 근거).
|
||||
# 근거 fact 가 없으면 위에서 이미 버렸으므로, 여기 남은 것은 전부 확인된 사실로 쓴 문장이다.
|
||||
status=FactStatus.VERIFIED.value,
|
||||
sort_order=order,
|
||||
)
|
||||
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_faqs.DBType()],
|
||||
[lambda s, r=row: _faq_crud.add_faq(s, r)],
|
||||
)
|
||||
if run_err == ErrorType.SUCCESS:
|
||||
stat["faqs"] += 1
|
||||
|
||||
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
|
||||
f"반려 {len(stat['rejected'])}건 (근거 fact {len(grounded)}개)")
|
||||
return stat
|
||||
if note:
|
||||
result["note"] = note
|
||||
return result
|
||||
@@ -0,0 +1,327 @@
|
||||
"""소개문·FAQ 생성 — COPY 잡이 하는 일.
|
||||
|
||||
★ LLM 은 사실을 만들지 않는다. 문장만 쓴다.
|
||||
- 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다.
|
||||
- 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다).
|
||||
- 소개문·FAQ 는 **바로 노출값**이다(VERIFIED). 승인 단계를 두지 않는다 — 2026-09-10 결정.
|
||||
게이트는 앞에 있다: 입력이 확인된 fact 뿐이고, 근거 없는 FAQ 는 저장조차 하지 않는다.
|
||||
확인된 사실로 쓴 문장을 한 번 더 승인받게 하면 같은 사실을 두 번 승인하는 셈이고,
|
||||
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
|
||||
(근거·실측: services/fact_service.upsert_fact · docs/DECISIONS.md 7절).
|
||||
- 사장님이 고친 문장(CORRECTED)은 재생성이 덮지 않는다. 그 잠금은 그대로다.
|
||||
- FAQ 가 목표 수(20)에 모자라면 업종 카탈로그에서 겹치지 않는 공통 질문을 **문의 안내** 답으로 채운다
|
||||
(services/faq_fill · common/faq_catalog). 답에 값·가능 여부를 적지 않으므로 사실을 만들지 않는다.
|
||||
★ fact 가 0건이어도(또는 API 키가 없어도) 채운다 — 그때는 LLM 을 부르지 않고 채우기만 한다.
|
||||
"""
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
from common.category_schema import CategorySchema, CategorySchemaError, get_schema
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.faq_catalog import FaqCatalog, find_catalog
|
||||
from common.database.model.models import place_facts, place_faqs, place_channels, places, place_units
|
||||
from common.enums import (
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
FactStatus,
|
||||
PlaceCategory,
|
||||
SourceType,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from common.utils.gtime import GTime
|
||||
from config.server_configs import external_api_config
|
||||
from crud.fact_crud import FactCRUD
|
||||
from crud.faq_crud import FaqCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from router.v1.fact.protocol import Req_UpsertFact
|
||||
from services import faq_fill, place_research
|
||||
from services.external import gemini_text
|
||||
from services.fact_service import FactService
|
||||
from common.job_errors import PermanentJobError
|
||||
|
||||
_fact_crud = FactCRUD()
|
||||
_faq_crud = FaqCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
|
||||
|
||||
class CopyAborted(PermanentJobError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class CopyInputs:
|
||||
place: places
|
||||
schema: CategorySchema
|
||||
grounded: list[gemini_text.FactInput]
|
||||
records: list[str]
|
||||
unit_summaries: list[dict]
|
||||
catalog: FaqCatalog | None
|
||||
known_fact_keys: set[str]
|
||||
|
||||
@property
|
||||
def ungrounded(self) -> bool:
|
||||
return not self.grounded and not self.unit_summaries
|
||||
|
||||
|
||||
async def prepare_copy(place_id: str, owner_user_id: str) -> CopyInputs:
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
|
||||
try:
|
||||
schema = get_schema(PlaceCategory(place.category))
|
||||
except (CategorySchemaError, ValueError) as ex:
|
||||
raise CopyAborted(f"지원하지 않는 업종: {place.category}") from ex
|
||||
|
||||
# ★ 노출 가능한 fact 만 근거로 준다. 미검증 값으로 쓴 문장은 그 자체가 미검증이다.
|
||||
pid = uuid.UUID(place_id)
|
||||
f_err, fact_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _fact_crud.list_facts(s, pid, None, None, True, True),
|
||||
)
|
||||
if f_err != ErrorType.SUCCESS:
|
||||
raise CopyAborted(f"fact 조회 실패: {f_err.name}")
|
||||
|
||||
grounded = [
|
||||
gemini_text.FactInput(
|
||||
key=r.key,
|
||||
label=(schema.get(r.key).label if schema.get(r.key) else r.key),
|
||||
value=r.value,
|
||||
unit=r.unit,
|
||||
)
|
||||
for r in fact_rows
|
||||
if r.unit_id is None and (r.value or "").strip()
|
||||
]
|
||||
# ★ 수집 원문도 근거로 넘긴다 — fact 가 아니라 place_channels.raw 에 박제된 글이다.
|
||||
#
|
||||
# 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다.
|
||||
# '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면
|
||||
# ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다.
|
||||
#
|
||||
# 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다.
|
||||
# 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31).
|
||||
# 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다.
|
||||
# ★ 확정 링크만 읽던 것을 **조사 근거까지** 읽게 넓혔다(2026-09-10).
|
||||
# 업소 조사(`place_research`)는 남이 쓴 글이라 확정하지 않는다 — 공식 채널이 아니므로
|
||||
# 발행본의 sameAs·푸터에 나가면 안 된다. 그런데 그것 때문에 여기서도 안 읽혀서,
|
||||
# 조사해 온 재료가 소개문에 한 글자도 닿지 않았다. 확정 여부는 "화면에 채널로
|
||||
# 내보낼 것인가" 의 판단이지 "근거로 읽을 것인가" 의 판단이 아니다.
|
||||
# ★ 다만 아무 미확정 링크나 읽지는 않는다 — raw.kind 가 research 인 것만이다.
|
||||
# 미확정 채널 URL 은 동명 업소일 수 있고(그게 확정 절차의 이유다), 조사 근거는
|
||||
# 상호 대조를 통과한 것만 적재된다(`grounding/place_research.parse_items`).
|
||||
records: list[str] = []
|
||||
l_err, link_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_channels.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.list_links(s, pid, False),
|
||||
)
|
||||
if l_err == ErrorType.SUCCESS:
|
||||
for link in (link_rows or []):
|
||||
raw = link.raw if isinstance(link.raw, dict) else {}
|
||||
if link.confirmed_at is None and raw.get("kind") != place_research.RAW_KIND:
|
||||
continue
|
||||
text = (raw.get("text") or "").strip()
|
||||
if text:
|
||||
# ★ fact 목록이 아니라 records 로 넘긴다. fact 자리에 넣으면 모델이 값 하나로
|
||||
# 읽고 거의 쓰지 않는다(prompts/copy.build_prompt 머리주석의 실측).
|
||||
records.append(text[:4000])
|
||||
# ground_check 는 여전히 이 글을 근거로 인정해야 한다 — 근거 목록에도 남긴다.
|
||||
grounded.append(gemini_text.FactInput(
|
||||
key=f"source:{link.link_id}", label="수집 원문", value=text[:4000],
|
||||
))
|
||||
|
||||
# 객실·메뉴 요약도 근거로 넘긴다 — "최대 4명" 같은 수치가 통과하려면 근거에 있어야 한다.
|
||||
#
|
||||
# ★ 근거 없음 판정보다 **먼저** 읽는다.
|
||||
# 예전에는 사업장 fact 가 0건이면 여기까지 오지 못하고 되돌아갔다. 그런데 네이버에
|
||||
# 요금표만 올라온 모텔은 사업장 fact 가 0건이고 객실 fact 만 있다 — 쓸 근거가 있는데도
|
||||
# "근거 없음"으로 끝나 소개문·FAQ 가 영구히 생기지 않았다.
|
||||
u_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_units.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.list_units(s, pid),
|
||||
)
|
||||
unit_summaries = []
|
||||
if u_err == ErrorType.SUCCESS:
|
||||
by_unit: dict = {}
|
||||
for r in fact_rows:
|
||||
if r.unit_id and (r.value or "").strip():
|
||||
by_unit.setdefault(str(r.unit_id), {})[r.key] = r.value
|
||||
unit_summaries = [
|
||||
{
|
||||
"name": u.name,
|
||||
"facts": by_unit.get(str(u.unit_id), {}),
|
||||
# 스키마 라벨·단위를 같이 넘긴다 — 이게 없으면 프롬프트에 'weekday_price' 라는
|
||||
# 날 key 가 그대로 실려 모델이 그 낱말로 문장을 쓴다.
|
||||
"labels": {
|
||||
key: {
|
||||
"label": schema.get(key).label if schema.get(key) else key,
|
||||
"unit": schema.get(key).unit if schema.get(key) else None,
|
||||
}
|
||||
for key in by_unit.get(str(u.unit_id), {})
|
||||
},
|
||||
}
|
||||
for u in unit_rows
|
||||
if by_unit.get(str(u.unit_id))
|
||||
]
|
||||
|
||||
# FAQ 채우기에 쓸 업종 카탈로그. 없으면(카페·음식점·호텔) 채우지 않는다.
|
||||
catalog = find_catalog(place.category, place.external_category)
|
||||
# 사업장·객실 fact 를 가리지 않는다 — "기준 인원" 은 객실 fact 로 답한다.
|
||||
known_fact_keys = {r.key for r in fact_rows if (r.value or "").strip()}
|
||||
|
||||
return CopyInputs(place, schema, grounded, records, unit_summaries, catalog, known_fact_keys)
|
||||
|
||||
|
||||
async def generate_copy(inputs: CopyInputs) -> gemini_text.GeneratedCopy:
|
||||
try:
|
||||
return await gemini_text.generate_copy(
|
||||
inputs.place.name,
|
||||
PlaceCategory(inputs.place.category),
|
||||
inputs.grounded,
|
||||
unit_summaries=inputs.unit_summaries or None,
|
||||
records=inputs.records or None,
|
||||
suggested_questions=faq_fill.suggested_questions(inputs.catalog, inputs.known_fact_keys) if inputs.catalog else None,
|
||||
max_faqs=faq_fill.FAQ_TARGET,
|
||||
model=external_api_config.gemini_text_model,
|
||||
)
|
||||
except gemini_text.GeminiNotConfigured as ex:
|
||||
raise CopyAborted(str(ex)) from ex
|
||||
|
||||
|
||||
async def save_copy(inputs: CopyInputs, copy: gemini_text.GeneratedCopy | None) -> dict:
|
||||
pid = inputs.place.place_id
|
||||
place_id = str(pid)
|
||||
schema = inputs.schema
|
||||
now = GTime.UTC()
|
||||
stat = {
|
||||
"place_id": place_id,
|
||||
"grounded_facts": len(inputs.grounded),
|
||||
"intro": False,
|
||||
"meta": False,
|
||||
"faqs": 0,
|
||||
"faq_fill": 0, # 목표 수를 채운 문의 안내 문항 수
|
||||
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
|
||||
"rejected": [list(r) for r in (copy.rejected or [])][:20] if copy else [],
|
||||
}
|
||||
|
||||
if copy is None:
|
||||
# 키만 없는 경우에는 기존 생성물을 보존한다.
|
||||
if inputs.ungrounded and inputs.catalog is not None:
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_faqs.DBType(), lambda s: _faq_crud.expire_generated(s, pid, now),
|
||||
)
|
||||
return stat
|
||||
|
||||
actor = UserInfo(
|
||||
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
|
||||
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
|
||||
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
|
||||
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
|
||||
user_id=str(inputs.place.owner_user_id),
|
||||
id="generator",
|
||||
role=1,
|
||||
)
|
||||
service = FactService(_fact_crud, _place_crud)
|
||||
|
||||
# 소개문·메타는 fact 로 들어간다 — FactService 가 allow_llm 을 다시 확인하고(뒷문 없음),
|
||||
# LLM 출처라 후보가 아니라 노출값으로 앉힌다(upsert_fact 의 LLM 분기).
|
||||
for key, text_value in (("intro", copy.intro), ("meta_description", copy.meta_description)):
|
||||
if not (text_value or "").strip():
|
||||
continue
|
||||
if not (schema.get(key) and schema.get(key).allow_llm):
|
||||
# 이 업종 스키마가 LLM 작성을 허용하지 않는 필드다. 조용히 건너뛴다.
|
||||
continue
|
||||
res = await service.upsert_fact(
|
||||
actor, place_id,
|
||||
Req_UpsertFact(
|
||||
key=key, value=text_value.strip(),
|
||||
source_type=SourceType.LLM, source_url=f"gemini:{external_api_config.gemini_text_model}",
|
||||
),
|
||||
)
|
||||
if res.result.success:
|
||||
stat["intro" if key == "intro" else "meta"] = True
|
||||
else:
|
||||
stat["rejected"].append([key, res.result.desc])
|
||||
|
||||
# 확인 안 된 기존 생성 FAQ 는 내리고 새로 넣는다. 사람이 확인한 FAQ 는 건드리지 않는다.
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
place_faqs.DBType(),
|
||||
lambda s: _faq_crud.expire_generated(s, pid, now),
|
||||
)
|
||||
for order, faq in enumerate(copy.faqs or []):
|
||||
if not faq.fact_keys:
|
||||
# ★ 근거 없는 FAQ 는 저장하지 않는다.
|
||||
stat["rejected"].append([faq.question, "근거 fact 없음"])
|
||||
continue
|
||||
row = place_faqs(
|
||||
place_id=pid,
|
||||
question=faq.question,
|
||||
answer=faq.answer,
|
||||
source_fact_ids=list(faq.fact_keys),
|
||||
generated_by=SourceType.LLM.value,
|
||||
# ★ 바로 노출한다 (2026-09-10 결정 — fact_service.upsert_fact 주석이 근거).
|
||||
# 근거 fact 가 없으면 위에서 이미 버렸으므로, 여기 남은 것은 전부 확인된 사실로 쓴 문장이다.
|
||||
status=FactStatus.VERIFIED.value,
|
||||
sort_order=order,
|
||||
)
|
||||
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_faqs.DBType()],
|
||||
[lambda s, r=row: _faq_crud.add_faq(s, r)],
|
||||
)
|
||||
if run_err == ErrorType.SUCCESS:
|
||||
stat["faqs"] += 1
|
||||
|
||||
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
|
||||
f"반려 {len(stat['rejected'])}건 (근거 fact {len(inputs.grounded)}개)")
|
||||
return stat
|
||||
|
||||
|
||||
async def fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
|
||||
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다. 넣은 건수를 돌려준다.
|
||||
|
||||
★ 기존 FAQ 는 **노출 중인 것 전부**로 센다 — 방금 넣은 생성분만이 아니라 재생성이 남긴
|
||||
사장님 입력·정정분까지. 그래야 사장님이 이미 답한 주제에 문의 안내가 겹쳐 붙지 않는다.
|
||||
★ 바로 노출값(VERIFIED)으로 넣는다. 답이 주장을 하지 않아 확인할 대상이 없다 —
|
||||
대신 JSON-LD · llms.txt · 고유 콘텐츠 계수에서는 빠진다(shared selectAnsweredFaqs)."""
|
||||
l_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_faqs.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _faq_crud.list_faqs(s, pid, True),
|
||||
)
|
||||
if l_err != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[copy] FAQ 채우기 건너뜀 — 목록 조회 실패 place={pid} {l_err.name}")
|
||||
return 0
|
||||
|
||||
picks = faq_fill.pick_fill_faqs(
|
||||
catalog,
|
||||
[faq_fill.ExistingFaq(r.question, r.source_fact_ids) for r in rows],
|
||||
known_fact_keys,
|
||||
phone,
|
||||
)
|
||||
next_order = max((r.sort_order for r in rows), default=-1) + 1
|
||||
added = 0
|
||||
for offset, pick in enumerate(picks):
|
||||
row = place_faqs(
|
||||
place_id=pid,
|
||||
question=pick.question,
|
||||
answer=pick.answer,
|
||||
source_fact_ids=None,
|
||||
generated_by=SourceType.TEMPLATE.value,
|
||||
status=FactStatus.VERIFIED.value,
|
||||
sort_order=next_order + offset,
|
||||
)
|
||||
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_faqs.DBType()],
|
||||
[lambda s, r=row: _faq_crud.add_faq(s, r)],
|
||||
)
|
||||
if run_err == ErrorType.SUCCESS:
|
||||
added += 1
|
||||
return added
|
||||
+68
-1
@@ -10,6 +10,7 @@
|
||||
한때 이 네 가지가 한 파일 500줄에 뭉쳐 있었다. "FAQ 답이 이상하다" 를 고치러 와도
|
||||
어디를 봐야 할지가 파일 안에서 갈리지 않았다.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
@@ -97,6 +98,7 @@ async def generate_copy(
|
||||
*,
|
||||
unit_summaries: Optional[list[dict]] = None,
|
||||
records: Optional[list[str]] = None,
|
||||
suggested_questions: Optional[list[str]] = None,
|
||||
max_faqs: int = 8,
|
||||
model: str = DEFAULT_TEXT_MODEL,
|
||||
max_retries: int = 2,
|
||||
@@ -125,7 +127,7 @@ async def generate_copy(
|
||||
|
||||
body = {
|
||||
"contents": [{"role": "user", "parts": [{
|
||||
"text": build_prompt(place_name, category, facts, max_faqs, unit_grounding, records)
|
||||
"text": build_prompt(place_name, category, facts, max_faqs, unit_grounding, records, suggested_questions)
|
||||
}]}],
|
||||
"generationConfig": {
|
||||
"responseMimeType": "application/json",
|
||||
@@ -196,6 +198,71 @@ async def generate_copy(
|
||||
return result
|
||||
|
||||
|
||||
# ── 요약(summarize_text) ──────────────────────────────────────────────────
|
||||
# ★ generate_copy 와 다르다: 여기서 압축하는 문장은 **이미 승인된 값**이다(fact 로 저장된 intro·
|
||||
# room_intro). 새 사실을 만드는 게 아니라 같은 내용을 짧게 쓰는 것뿐이라 ground_check 를 다시
|
||||
# 걸지 않는다 — "사실을 더하지 마라"는 프롬프트 지시로 충분하다.
|
||||
_SUMMARY_CACHE: dict[str, str] = {}
|
||||
_SUMMARY_CACHE_MAX = 500
|
||||
_SUMMARY_PROMPT = (
|
||||
"다음 숙소 소개에서 핵심 특징 1~2개만 골라 한국어 한 문장, 공백 포함 60~80자로 요약해줘. "
|
||||
"원문에 없는 사실이나 과장 표현을 추가하지 말고, 선택한 사실의 조건과 부정 표현을 유지해. "
|
||||
"반복되는 상호명, 인사말, 홍보 수식어는 생략해. "
|
||||
"요약문만 출력하고 다른 말은 붙이지 마.\n\n"
|
||||
)
|
||||
|
||||
|
||||
async def summarize_text(
|
||||
text: str,
|
||||
*,
|
||||
model: str = DEFAULT_TEXT_MODEL,
|
||||
max_retries: int = 2,
|
||||
client: Optional[httpx.AsyncClient] = None,
|
||||
) -> Optional[str]:
|
||||
"""캔버스 미리보기용 축약문. 실패해도 예외를 올리지 않는다 — 호출측은 None 이면 원문을 쓴다.
|
||||
|
||||
★ DB 에 남기지 않는다. 같은 원문은 프로세스 메모리 캐시(sha256 키)로 재호출을 막는다
|
||||
(서버 재시작하면 비워진다 — 요구사항: "DB 저장은 생략하고 프론트 응답에만 실어준다").
|
||||
"""
|
||||
stripped = text.strip()
|
||||
if not stripped:
|
||||
return None
|
||||
if not is_configured():
|
||||
return None
|
||||
|
||||
# 길이 기준을 바꾼 뒤 이전 길이의 요약을 재사용하지 않도록 프롬프트도 키에 넣는다.
|
||||
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": _SUMMARY_PROMPT + stripped,
|
||||
}]}],
|
||||
"generationConfig": {"temperature": 0.2},
|
||||
}
|
||||
|
||||
owns_client = client is None
|
||||
client = client or httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0))
|
||||
try:
|
||||
payload = await call(client, model, body, max_retries)
|
||||
summary = extract_text(payload).strip()
|
||||
except GeminiError as ex:
|
||||
LOG.w(f"[gemini-text] 요약 실패: {ex}")
|
||||
return None
|
||||
finally:
|
||||
if owns_client:
|
||||
await client.aclose()
|
||||
|
||||
if not summary:
|
||||
return None
|
||||
if len(_SUMMARY_CACHE) >= _SUMMARY_CACHE_MAX:
|
||||
_SUMMARY_CACHE.clear() # 간단한 캐시 상한 — 관리 도구 트래픽 규모에는 LRU 가 과하다.
|
||||
_SUMMARY_CACHE[cache_key] = summary
|
||||
return summary
|
||||
|
||||
|
||||
@dataclass
|
||||
class GeneratedSong:
|
||||
"""가사 생성 결과. 곡은 여기서 만들지 않는다 — 작곡은 services/external/suno 다."""
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""SiteOntology(o2o-site-ontology) 클라이언트 — 이 가게에 맞는 검색 키워드를 받아 온다.
|
||||
|
||||
SiteOntology 는 펜션 SEO/AEO 키워드 사전(pgvector)을 들고, 업체 프로필에 맞는 단어를 골라 주는
|
||||
사내 서비스다. 여기서는 창구 두 개만 쓴다(실측 2026-09-14, 로컬 :3100).
|
||||
|
||||
POST /v1/merchants/publish {externalId, name, industryId, regionId, description, profile, generate:false}
|
||||
→ 201 {merchant, generation: "skipped"} 업체를 저장만 한다. 키워드는 주지 않는다
|
||||
POST /v1/match {query: <externalId>, limit}
|
||||
→ 201 {resolved, lanes, matches[], byLane[], excluded[]} 저장된 프로필로 추천한다
|
||||
|
||||
★ 두 번 부르는 이유: "프로필을 주면 키워드를 돌려주는" 창구가 한 번에는 없다. match 는 query 문자열만
|
||||
받고, externalId 를 넣으면 저장된 업체로 해석해 그 프로필로 추천한다. 그래서 먼저 publish 로 프로필을
|
||||
이번 빌드의 스냅샷 값으로 맞춘다.
|
||||
★ generate:false 를 반드시 보낸다. 빠뜨리면 SiteOntology 가 LLM 키워드 생성을 큐에 넣는다 —
|
||||
그 결과는 우리가 쓰지 않는 창구(/seo)로만 나가고, 로컬은 mock LLM 이라 가짜 단어가 사전에 쌓인다.
|
||||
★ regionId 가 SiteOntology 의 region 표에 없으면 **500** 이다(외래키 위반, 실측). 그 표는 적재한 데이터셋에
|
||||
따라 달라서(군산만 / 전국 54개) 우리가 알 수 없다 — 500 이면 regionId 를 비워 한 번 더 보낸다.
|
||||
지역이 비면 유형 추천에서 "군산" 이 빠져 품질이 떨어지지만(실측: 1위가 `독채펜션`), 없는 것보다 낫고
|
||||
지역 없는 단어는 호출측 거르기(seo_keywords)가 제목에서 뺀다.
|
||||
★ externalId 가 해석되지 않으면 match 는 에러가 아니라 **입력 문자열 자체로 검색한 결과**를 201 로 준다
|
||||
(실측: "no-such-place-id" → `나운동 숙소`·`선유도 숙소 예약 언제 해야 하나요`). 그걸 쓰면 남의 동네 단어가
|
||||
나간다 — resolved 가 우리 externalId 가 아니면 실패로 본다.
|
||||
★ 실패는 발행을 막지 않는다. 여기서는 SiteOntologyError 로 올리고, 호출측이 잡아 키워드 없이 굽는다.
|
||||
"""
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.server_configs import external_api_config
|
||||
|
||||
# 로컬 임베딩 모델이라 호출당 1~2초다. 넉넉히 잡되 발행 잡 데드라인(900s)을 잡아먹지 않게 끊는다.
|
||||
TIMEOUT_SEC = 15.0
|
||||
# 거르기(seo_keywords)에서 절반 넘게 떨어진다(실측: 10건 → 4건). 메타 태그 10개를 채우려면 넉넉히 받는다.
|
||||
DEFAULT_LIMIT = 40
|
||||
|
||||
PUBLISH_PATH = "/v1/merchants/publish"
|
||||
MATCH_PATH = "/v1/match"
|
||||
|
||||
|
||||
class SiteOntologyError(RuntimeError):
|
||||
"""SiteOntology 호출 실패(네트워크·타임아웃·4xx/5xx·업체 미해석). 발행은 계속된다."""
|
||||
|
||||
|
||||
def base_url() -> str:
|
||||
return (external_api_config.site_ontology_url or "").strip().rstrip("/")
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return bool(base_url())
|
||||
|
||||
|
||||
async def _post(client: httpx.AsyncClient, path: str, body: dict) -> dict:
|
||||
res = await client.post(f"{base_url()}{path}", json=body)
|
||||
if res.status_code >= 400:
|
||||
raise SiteOntologyError(f"{path} HTTP {res.status_code}: {res.text[:200]}")
|
||||
try:
|
||||
data = res.json()
|
||||
except ValueError as ex:
|
||||
raise SiteOntologyError(f"{path} 응답이 JSON 이 아니다: {res.text[:200]}") from ex
|
||||
if not isinstance(data, dict):
|
||||
raise SiteOntologyError(f"{path} 응답 모양이 다르다: {type(data).__name__}")
|
||||
return data
|
||||
|
||||
|
||||
async def match_for_merchant(merchant: dict, limit: int = DEFAULT_LIMIT) -> dict:
|
||||
"""업체를 저장하고, 그 업체로 해석된 추천 결과(/v1/match 응답)를 돌려준다.
|
||||
|
||||
merchant 는 publish 요청 본문이다(generate 는 여기서 붙인다). 실패하면 SiteOntologyError."""
|
||||
body = {**merchant, "generate": False}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client:
|
||||
try:
|
||||
await _post(client, PUBLISH_PATH, body)
|
||||
except SiteOntologyError as ex:
|
||||
if not body.get("regionId"):
|
||||
raise
|
||||
LOG.w(f"[site-ontology] regionId={body['regionId']} 로 저장하지 못했다 — 지역 없이 다시 보낸다: {ex}")
|
||||
body = {**body, "regionId": None}
|
||||
await _post(client, PUBLISH_PATH, body)
|
||||
result = await _post(client, MATCH_PATH, {"query": merchant["externalId"], "limit": limit})
|
||||
except httpx.HTTPError as ex:
|
||||
raise SiteOntologyError(f"{type(ex).__name__}: {ex}") from ex
|
||||
|
||||
resolved = result.get("resolved") or {}
|
||||
if resolved.get("externalId") != merchant["externalId"]:
|
||||
raise SiteOntologyError(f"업체가 해석되지 않았다 — externalId={merchant['externalId']}")
|
||||
return result
|
||||
@@ -33,6 +33,7 @@ from router.v1.fact.protocol import (
|
||||
Res_FactList,
|
||||
)
|
||||
from services.external.gemini_extract import extract_facts
|
||||
from services.intro_summary import summarize_intro
|
||||
from services.llm.gemini import GeminiError, GeminiNotConfigured
|
||||
|
||||
# 사장님이 붙여넣은 원문의 출처 표기. ★ 실제 URL 이 아니라 경로 식별자다 —
|
||||
@@ -40,7 +41,7 @@ from services.llm.gemini import GeminiError, GeminiNotConfigured
|
||||
# '어디서 왔는가' 는 여전히 명확하다: 사장님이 화면에 직접 붙여넣었다.
|
||||
OWNER_PASTE_SOURCE = "owner:paste"
|
||||
|
||||
# 자동 수집 출처 — 노출값을 직접 바꾸지 못하고 후보로만 들어간다.
|
||||
# 자동 출처. CRAWL과 LLM 문장은 아래의 즉시 노출 경로를 먼저 거친다.
|
||||
_AUTO_SOURCES = (SourceType.API, SourceType.CRAWL, SourceType.LLM)
|
||||
|
||||
|
||||
@@ -48,10 +49,9 @@ class FactService:
|
||||
"""fact 기록 + 검증 상태 전이.
|
||||
|
||||
── 세 갈래 프로세스 ────────────────────────────────────────────────
|
||||
생성 : 자동 수집 → 후보(UNVERIFIED) → 사람이 승인 → 노출값(VERIFIED) → 사이트 빌드
|
||||
업데이트: 재수집 → 값이 같으면 검증 유지(REFRESHED)
|
||||
값이 다르면 **노출값은 그대로 두고** 후보(PENDING_OWNER)로 적재
|
||||
→ 사람이 승인해야 노출값이 교체된다
|
||||
생성 : 크롤링 → 노출값(VERIFIED), API → 후보 → 사람이 승인
|
||||
업데이트: 같은 값이면 검증 유지(REFRESHED). 다른 CRAWL 값은 바로 교체한다.
|
||||
API 값이나 사람 입력·정정본과 충돌하는 값은 후보(PENDING_OWNER)로 적재한다.
|
||||
수정 : 사람이 직접 입력 → 노출값 즉시 교체. 정정(CORRECTED)은 잠금 표시가 붙는다
|
||||
문장 : LLM 이 쓴 소개문·메타(allow_llm 필드) → 승인 없이 바로 노출값
|
||||
(사실이 아니라 **이미 승인된 사실로 쓴 문장**이다 — upsert_fact 주석)
|
||||
@@ -63,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 에 있는 것만
|
||||
"""
|
||||
|
||||
@@ -133,12 +133,21 @@ class FactService:
|
||||
res.result.SetResult(list_err)
|
||||
return res
|
||||
res.facts = [FactData.model_validate(r) for r in rows]
|
||||
await self._attach_summaries(res.facts)
|
||||
# ★ 사이트에 나갈 수 있는 건수. 발행 게이트가 보는 숫자와 같은 기준이다.
|
||||
res.publishable = sum(1 for r in rows if FactStatus(r.status) in PUBLISHABLE_FACT_STATUSES)
|
||||
# 재수집이 올려놓은 확인 대기 건수 — 관리 화면의 '검토할 것' 배지.
|
||||
res.pending_review = sum(1 for r in rows if FactStatus(r.status) == FactStatus.PENDING_OWNER)
|
||||
return res
|
||||
|
||||
async def _attach_summaries(self, facts: list) -> None:
|
||||
"""intro/room_intro 원문이 길면 캔버스 미리보기용 요약을 얹는다.
|
||||
|
||||
★ place_facts 에는 저장하지 않는다 — 이 응답(FactData.summary)에만 실린다.
|
||||
원문이 짧으면 API 를 부르지 않는다(summarize_intro)."""
|
||||
for f in facts:
|
||||
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:
|
||||
"""사장님이 붙여넣은 원문 → fact 후보.
|
||||
@@ -237,7 +246,8 @@ class FactService:
|
||||
"""fact 를 기록한다. 출처에 따라 경로가 갈린다.
|
||||
|
||||
사람(owner) → 노출값을 직접 교체한다(수정 프로세스)
|
||||
자동 수집 → 노출값과 같으면 확인 시각만 갱신, 다르면 후보로 적재(업데이트 프로세스)
|
||||
크롤링 → 원값을 바로 노출, 직접 입력·정정본과 충돌하면 후보로 보존
|
||||
API → 노출값과 같으면 확인 시각만 갱신, 다르면 후보로 적재
|
||||
"""
|
||||
res = Res_Fact()
|
||||
err_type, place = await self._load_place(user_info, place_id)
|
||||
@@ -266,6 +276,12 @@ class FactService:
|
||||
res.result.SetResult(ErrorType.FACT_INVALID_KEY)
|
||||
return res
|
||||
|
||||
# 규칙 4 — TEMPLATE 은 FAQ 문의 안내 전용 출처다(services/faq_fill). fact 에는 쓸 수 없다.
|
||||
# OWNER 도 자동 수집도 아니라서, 막지 않으면 아래 분기에서 사람 입력처럼 바로 노출값이 된다.
|
||||
if req.source_type == SourceType.TEMPLATE:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
pid = uuid.UUID(place_id)
|
||||
pub_err, published = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
@@ -279,6 +295,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(
|
||||
@@ -305,7 +332,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)
|
||||
@@ -367,9 +394,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,
|
||||
@@ -380,7 +407,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,
|
||||
@@ -390,6 +417,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:
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""FAQ 목표 수 채우기 — 생성된 FAQ 가 모자라면 카탈로그에서 겹치지 않는 공통 질문을 고른다.
|
||||
|
||||
순수 함수만 둔다(DB·네트워크 없음). 무엇이 왜 골렸는지를 이 파일만 읽고 답할 수 있어야 한다.
|
||||
|
||||
고르는 규칙 (카탈로그 순서 = 우선순위)
|
||||
1. 답할 fact 가 있는 질문은 고르지 않는다 — 그건 LLM 이 fact 로 답할 자리다.
|
||||
"주차할 수 있나요?" 에 parking=true 가 있는데 "문의 부탁드립니다" 가 붙으면 아는 것을 숨긴 셈이다.
|
||||
2. 기존 FAQ 가 이미 다룬 주제는 고르지 않는다. 기존 FAQ 에는 LLM 생성분 · 사장님 입력 · 정정분이 모두 든다.
|
||||
- 근거 fact key 가 겹치면 같은 주제다. LLM 은 "주차 및 와이파이" 처럼 두 주제를 한 문항에 묶고
|
||||
근거에 [parking, wifi] 를 적는다 — 낱말 대조만으로는 둘 중 하나를 놓친다.
|
||||
- 질문에 카탈로그 키워드가 들어 있으면 같은 주제다(사장님 입력은 근거 key 가 없다).
|
||||
3. 공통 답은 문의 안내뿐이다. 값·가능 여부를 적지 않는다(common/faq_catalog 머리주석).
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from common.faq_catalog import FaqCatalog
|
||||
|
||||
# ★ 사이트에 싣는 FAQ 목표 수. 생성 상한(max_faqs)도 이 값을 쓴다.
|
||||
FAQ_TARGET = 20
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExistingFaq:
|
||||
question: str
|
||||
source_fact_ids: Optional[list] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FillFaq:
|
||||
catalog_id: str
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
def _compact(text: str) -> str:
|
||||
return re.sub(r"\s+", "", text or "").lower()
|
||||
|
||||
|
||||
def _base_key(key: str) -> str:
|
||||
"""객실 근거는 "A동:max_capacity" 로 적힌다 — 주제 비교에는 key 만 쓴다."""
|
||||
return str(key).rsplit(":", 1)[-1]
|
||||
|
||||
|
||||
def _with_topic_particle(topic: str) -> str:
|
||||
"""주제 뒤에 은/는 을 붙인다. 받침이 있으면 '은'."""
|
||||
last = topic.strip()[-1:]
|
||||
if "가" <= last <= "힣":
|
||||
return topic + ("은" if (ord(last) - ord("가")) % 28 else "는")
|
||||
return topic + "은(는)"
|
||||
|
||||
|
||||
def fallback_answer(catalog: FaqCatalog, index: int, topic: str, phone: Optional[str]) -> str:
|
||||
"""문의 안내 문구. 문구를 번갈아 써서 스무 줄이 전부 같은 문장이 되지 않게 한다."""
|
||||
phone = (phone or "").strip()
|
||||
templates = catalog.fallback_with_contact if phone else catalog.fallback_without_contact
|
||||
template = templates[index % len(templates)]
|
||||
return template.format(topic=_with_topic_particle(topic), contact=f"전화({phone})")
|
||||
|
||||
|
||||
def pick_fill_faqs(
|
||||
catalog: FaqCatalog,
|
||||
existing: Iterable[ExistingFaq],
|
||||
fact_keys: Iterable[str],
|
||||
phone: Optional[str] = None,
|
||||
target: int = FAQ_TARGET,
|
||||
) -> list[FillFaq]:
|
||||
"""목표 수까지 모자란 만큼 카탈로그 질문을 고른다. 모자라지 않으면 빈 목록."""
|
||||
existing = list(existing)
|
||||
need = target - len(existing)
|
||||
if need <= 0:
|
||||
return []
|
||||
|
||||
asked = [_compact(faq.question) for faq in existing]
|
||||
covered_keys = {_base_key(k) for faq in existing for k in (faq.source_fact_ids or [])}
|
||||
known_keys = {_base_key(k) for k in fact_keys}
|
||||
|
||||
picked: list[FillFaq] = []
|
||||
for item in catalog.items:
|
||||
if len(picked) >= need:
|
||||
break
|
||||
if known_keys.intersection(item.fact_keys):
|
||||
continue # 규칙 1
|
||||
if covered_keys.intersection(item.fact_keys):
|
||||
continue # 규칙 2 — 근거 key
|
||||
if any(keyword in question for keyword in item.keywords for question in asked):
|
||||
continue # 규칙 2 — 질문 낱말
|
||||
answer = fallback_answer(catalog, len(picked), item.topic, phone)
|
||||
picked.append(FillFaq(item.id, item.question, answer))
|
||||
return picked
|
||||
|
||||
|
||||
def suggested_questions(catalog: FaqCatalog, fact_keys: Iterable[str]) -> list[str]:
|
||||
"""fact 로 답할 수 있는 카탈로그 질문 — 프롬프트에 실어 LLM 이 이 질문들부터 쓰게 한다.
|
||||
채우기(규칙 1)가 이 질문들을 건너뛰므로, LLM 이 안 쓰면 그 주제는 비게 된다."""
|
||||
known = {_base_key(k) for k in fact_keys}
|
||||
return [item.question for item in catalog.items if known.intersection(item.fact_keys)]
|
||||
@@ -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):
|
||||
|
||||
@@ -11,9 +11,12 @@
|
||||
`search_results` 의 첫 줄을 붙인다 — 모델 답변은 환각이 섞이지만 search_results 는
|
||||
실제로 검색된 주소다(`grounding/channels.py` 와 같은 판단).
|
||||
둘 다 없으면 항목을 버린다. 출처 없는 사실은 이 레포의 규칙 위반이다.
|
||||
★ 예외가 하나 있다 — `_SEARCH_LINK_KINDS`. 거기 있는 종류는 **모델의 URL 을 아예 안 받고**
|
||||
제목으로 찾아가는 검색 링크를 코드가 만든다.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from common.logger import LOG
|
||||
|
||||
@@ -23,10 +26,27 @@ _TITLE_KEY = {
|
||||
"daily": "title",
|
||||
"people": "name",
|
||||
"chronicle": "title",
|
||||
"reading": "title",
|
||||
"postcard": "line",
|
||||
"quiz": "question",
|
||||
}
|
||||
|
||||
# ★ 출처를 **모델에게 받지 않고 코드가 만드는** 종류.
|
||||
# 개별 문서 주소(`terms.naver.com/entry.naver?docId=…`)는 짐작해서 적으면 없는 문서로
|
||||
# 이어진다 — 레포 절대규칙(없는 사실을 짓지 않는다)에 걸린다. 검색 링크는 제목을 그대로
|
||||
# 넘기니 항상 관련 결과로 뜬다. 2026-09-14 대표 지시("확인필요 없애고 링크는 네이버 링크로"),
|
||||
# 시연본 구현은 `site/scripts/mockup/build_reading.py` 의 `naver()`.
|
||||
_SEARCH_LINK_KINDS = {"reading"}
|
||||
|
||||
|
||||
def _search_source(title: str, region_label: str) -> dict:
|
||||
"""제목으로 찾아가는 검색 링크. 지역명이 제목에 없으면 붙여 검색 정확도를 올린다."""
|
||||
region = (region_label or "").split()[-1] if region_label else ""
|
||||
query = title if (not region or region[:-1] in title or region in title) else f"{title} {region}"
|
||||
return {"name": "네이버에서 찾아보기",
|
||||
"url": "https://search.naver.com/search.naver?query=" + quote(query)}
|
||||
|
||||
|
||||
# 코드펜스를 두르고 오는 경우가 있다. 규칙 1 로 금지했지만 모델은 종종 어긴다.
|
||||
_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE)
|
||||
|
||||
@@ -57,7 +77,9 @@ def _clean_source(value) -> dict | None:
|
||||
return {"name": (value.get("name") or url).strip(), "url": url}
|
||||
|
||||
|
||||
def parse_items(payload: dict, kind: str, limit: int) -> tuple[list[dict], list[str]]:
|
||||
def parse_items(
|
||||
payload: dict, kind: str, limit: int, region_label: str = ""
|
||||
) -> tuple[list[dict], list[str]]:
|
||||
"""(쓸 수 있는 항목, 버린 이유) — 버린 이유는 로그와 잡 결과에 남긴다.
|
||||
|
||||
한 항목이 잘못돼도 나머지를 살린다. 지역 하나에 8~14건인데 한 줄 때문에 전부 버리면
|
||||
@@ -101,6 +123,14 @@ def parse_items(payload: dict, kind: str, limit: int) -> tuple[list[dict], list[
|
||||
item = {k: v for k, v in raw.items() if v not in (None, "", [], {})}
|
||||
item[title_key] = title
|
||||
|
||||
if kind in _SEARCH_LINK_KINDS:
|
||||
# 출처는 코드가 만든다(위 _SEARCH_LINK_KINDS). 모델이 URL 을 적어 왔어도 버린다 —
|
||||
# 짐작해 적은 주소가 섞이는 통로를 아예 남기지 않는다. 검수 배지도 함께 뺀다.
|
||||
item["source"] = _search_source(title, region_label)
|
||||
item.pop("verified", None)
|
||||
out.append(item)
|
||||
continue
|
||||
|
||||
source = _clean_source(raw.get("source")) or fallback
|
||||
if source is None:
|
||||
dropped.append(f"{title}: 출처가 없다")
|
||||
|
||||
@@ -44,7 +44,7 @@ def is_configured() -> bool:
|
||||
|
||||
|
||||
def output_dir() -> Path:
|
||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites"))
|
||||
return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/solution/site/out"))
|
||||
|
||||
|
||||
def site_urls(slug: str) -> list[str]:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""작업 단계 기록. 실행 순서는 도메인 서비스, 화면 문구는 프론트가 소유한다."""
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from crud.job_crud import JobQueue
|
||||
|
||||
|
||||
class JobProgress:
|
||||
def __init__(self, job: dict, steps: tuple[str, ...]):
|
||||
self.job = job
|
||||
self.queue = JobQueue()
|
||||
self.state = {
|
||||
"attempt": job["attempts"],
|
||||
"steps": [{"id": step, "status": "pending"} for step in steps],
|
||||
}
|
||||
|
||||
async def _set(self, step_id: str, status: str, reason: str | None = None):
|
||||
step = next(step for step in self.state["steps"] if step["id"] == step_id)
|
||||
step.update(status=status, reason=reason)
|
||||
if not await self.queue.set_progress(self.job, self.state):
|
||||
raise RuntimeError("작업 소유권이 만료되어 진행 기록을 중단합니다")
|
||||
|
||||
@asynccontextmanager
|
||||
async def step(self, step_id: str):
|
||||
await self._set(step_id, "running")
|
||||
try:
|
||||
yield
|
||||
except BaseException:
|
||||
await self._set(step_id, "failed")
|
||||
raise
|
||||
else:
|
||||
await self._set(step_id, "done")
|
||||
|
||||
async def skip(self, step_id: str, reason: str):
|
||||
await self._set(step_id, "skipped", reason)
|
||||
@@ -1,6 +1,7 @@
|
||||
from fastapi import Depends
|
||||
|
||||
from common.enums import ErrorType, JobType
|
||||
from common.enums import ErrorType, JobType, UserRole
|
||||
from common.models.gmodel import UserInfo
|
||||
from common.logger import LOG
|
||||
from crud.job_crud import JobQueue
|
||||
from router.v1.job.protocol import JobData, Res_Job, Res_JobOps
|
||||
@@ -15,13 +16,34 @@ class JobService:
|
||||
def __init__(self, queue: JobQueue = Depends(JobQueue)):
|
||||
self.queue = queue
|
||||
|
||||
async def get_job(self, job_id: str) -> Res_Job:
|
||||
async def get_job(self, job_id: str, user_info: UserInfo | None = None) -> Res_Job:
|
||||
"""잡 단건. ★ 주인이 아니면 **없는 것으로** 답한다(JOB_NOT_FOUND).
|
||||
|
||||
★ 잡 id 하나만 알면 남의 작업 결과가 열렸다(실측 2026-09-15). BUILD 결과에는
|
||||
site_id · 게이트 상세(비어 있는 필수 항목 목록) · payload 경로가 들어 있다.
|
||||
예전에는 COPY 만 주인을 봤는데, 가려야 할 것은 잡 종류가 아니라 **남의 사업장**이다.
|
||||
★ 주인을 알 수 없는 잡(내부 동기화·노래 등 payload 에 owner_user_id 가 없는 것)은
|
||||
사장님에게 열지 않는다 — '주인이 없으니 아무나' 가 아니라 '확인할 수 없으니 닫는다' 다.
|
||||
★ user_info 가 None 인 호출은 내부 경로다(운영자 전용 requeue) — 그쪽은 이미
|
||||
RequireDeveloper 가 막는다.
|
||||
"""
|
||||
res = Res_Job()
|
||||
row = await self.queue.get(job_id)
|
||||
if row is None:
|
||||
res.result.SetResult(ErrorType.JOB_NOT_FOUND)
|
||||
return res
|
||||
res.job = JobData(**{k: v for k, v in row.items() if k in JobData.model_fields})
|
||||
payload = row.get("payload") or {}
|
||||
if user_info is not None and (user_info.role or 0) < UserRole.DEVELOPER.value:
|
||||
owner = payload.get("owner_user_id")
|
||||
if owner is None or str(owner) != str(user_info.user_id):
|
||||
res.result.SetResult(ErrorType.JOB_NOT_FOUND)
|
||||
return res
|
||||
fields = {k: v for k, v in row.items() if k in JobData.model_fields}
|
||||
# 어느 사업장의 작업인지는 종류를 가리지 않고 싣는다 — 화면이 "이 화면의 작업이 맞나" 를
|
||||
# 이 값으로 판단한다(useGenerationJob 의 wrongJob).
|
||||
if payload.get("place_id") is not None:
|
||||
fields["place_id"] = payload.get("place_id")
|
||||
res.job = JobData(**fields)
|
||||
return res
|
||||
|
||||
async def ops(self) -> Res_JobOps:
|
||||
|
||||
@@ -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
|
||||
@@ -295,28 +295,55 @@ class PlaceService:
|
||||
sess, uuid.UUID(user_info.user_id), ExternalPlaceSource.NAVER.value, str(naver_id),
|
||||
),
|
||||
)
|
||||
canonical_id = place_id
|
||||
#
|
||||
# ★ **사장님이 새로 만들겠다고 누른 것은 뒤집지 않는다** (2026-09-15)
|
||||
# 위 합치기는 "위저드를 다시 시작하면 빈 행이 쌓인다" 를 막으려던 것인데,
|
||||
# [새로 크롤링하고 사이트 생성하기] 와 구분이 없어서 **일부러 다시 만들려는 경우도
|
||||
# 기존 사업장으로 끌고 갔다** — 새로 만들기를 눌렀는데 기존 에디터가 열린다.
|
||||
# 그래서 이어붙이기는 `reuse_existing` 이 켜져 있을 때만 한다.
|
||||
#
|
||||
# 끄더라도 **비어 있는 중복 행은 치운다.** 원래 막으려던 누적이 그것이고,
|
||||
# 빈 행은 잃을 것이 없다. 지금 행은 앞으로 채워질 것이므로 대상이 아니다.
|
||||
others = []
|
||||
if err_dup == ErrorType.SUCCESS:
|
||||
existing = next((r for r in (dup_rows or []) if str(r.place_id) != str(place_id)), None)
|
||||
if existing is not None:
|
||||
canonical_id = str(existing.place_id)
|
||||
if await self._is_empty(place_id):
|
||||
others = [r for r in (dup_rows or []) if str(r.place_id) != str(place_id)]
|
||||
|
||||
if others and not req.reuse_existing:
|
||||
for row in others:
|
||||
if await self._is_empty(str(row.place_id)):
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda sess: self.crud.delete_place(
|
||||
sess, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
|
||||
lambda sess, rid=row.place_id: self.crud.delete_place(
|
||||
sess, uuid.UUID(user_info.user_id), rid,
|
||||
),
|
||||
)
|
||||
LOG.i(f"[verify_by_url] 같은 업소가 이미 있다 — 빈 행 {place_id} 를 접고 "
|
||||
f"{canonical_id} 로 잇는다 (naver {naver_id})")
|
||||
else:
|
||||
LOG.w(f"[verify_by_url] 같은 업소가 둘이다 — {place_id} 에 쌓인 것이 있어 "
|
||||
f"지우지 않는다. 정본 {canonical_id} 를 돌려준다 (naver {naver_id})")
|
||||
place_id = canonical_id
|
||||
err_type, place = await self._load(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
LOG.i(f"[verify_by_url] 새로 만들기 — 빈 중복 행 {row.place_id} 를 치운다 "
|
||||
f"(naver {naver_id})")
|
||||
LOG.i(f"[verify_by_url] 새로 만들기 — 같은 업소가 {len(others)}개 있지만 "
|
||||
f"{place_id} 로 새로 간다 (naver {naver_id})")
|
||||
others = []
|
||||
|
||||
canonical_id = place_id
|
||||
if others:
|
||||
existing = others[0]
|
||||
canonical_id = str(existing.place_id)
|
||||
if await self._is_empty(place_id):
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda sess: self.crud.delete_place(
|
||||
sess, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
|
||||
),
|
||||
)
|
||||
LOG.i(f"[verify_by_url] 같은 업소가 이미 있다 — 빈 행 {place_id} 를 접고 "
|
||||
f"{canonical_id} 로 잇는다 (naver {naver_id})")
|
||||
else:
|
||||
LOG.w(f"[verify_by_url] 같은 업소가 둘이다 — {place_id} 에 쌓인 것이 있어 "
|
||||
f"지우지 않는다. 정본 {canonical_id} 를 돌려준다 (naver {naver_id})")
|
||||
place_id = canonical_id
|
||||
err_type, place = await self._load(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
coord = base.get("coordinate") or {}
|
||||
verify_req = Req_VerifyPlace(
|
||||
@@ -904,21 +931,29 @@ class PlaceService:
|
||||
async def start_copy(self, user_info: UserInfo, place_id: str, req: Req_StartCopy) -> Res_StartCopy:
|
||||
"""소개문·FAQ 생성을 큐에 넣는다.
|
||||
|
||||
★ 근거로 쓸 확인된 fact 가 없으면 잡을 만들지 않는다 —
|
||||
근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다."""
|
||||
★ 근거로 쓸 확인된 fact 가 없으면 LLM 은 부르지 않는다 —
|
||||
근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다.
|
||||
★ 그래도 FAQ 카탈로그가 있는 업종(펜션)이면 잡을 만든다 — fact 가 0건이어도 FAQ 는
|
||||
문의 안내로 20개를 채운다(DECISIONS.md 8절). 그 경로는 LLM 을 안 쓰므로 API 키도 필요 없다."""
|
||||
from common.database.model.models import place_facts as facts_model
|
||||
from common.faq_catalog import find_catalog
|
||||
from crud.fact_crud import FactCRUD
|
||||
from services.external import gemini_text
|
||||
|
||||
res = Res_StartCopy()
|
||||
err_type, _place = await self._load(user_info, place_id)
|
||||
err_type, place = await self._load(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
if not gemini_text.is_configured():
|
||||
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
||||
return res
|
||||
# URL 에 잡 ID 를 쓰기 전에 응답이 끊겨도 완료된 작업을 다시 만들지 않는다.
|
||||
if req.resume:
|
||||
existing = await self.queue.find_latest(f"copy:{place_id}")
|
||||
if existing:
|
||||
res.job_id = uuid.UUID(existing["job_id"])
|
||||
res.status = JobStatus(existing["status"])
|
||||
res.created = False
|
||||
return res
|
||||
|
||||
crud = FactCRUD()
|
||||
f_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
@@ -930,9 +965,15 @@ class PlaceService:
|
||||
res.result.SetResult(f_err)
|
||||
return res
|
||||
res.grounded_facts = sum(1 for r in rows if r.unit_id is None and (r.value or "").strip())
|
||||
if res.grounded_facts == 0:
|
||||
# 객실 fact 만 있어도 LLM 이 쓴다(copy_service 의 unit_summaries) — 키 검사는 그 기준으로 한다.
|
||||
needs_llm = any((r.value or "").strip() for r in rows)
|
||||
if not needs_llm and find_catalog(place.category, place.external_category) is None:
|
||||
# 쓸 근거도, 채울 공통 질문도 없다(카페·음식점·호텔).
|
||||
res.result.SetResult(ErrorType.FAQ_UNGROUNDED)
|
||||
return res
|
||||
if needs_llm and not gemini_text.is_configured():
|
||||
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
||||
return res
|
||||
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.COPY,
|
||||
|
||||
@@ -56,6 +56,7 @@ def build_prompt(
|
||||
max_faqs: int,
|
||||
unit_facts: Optional[Sequence[FactLike]] = None,
|
||||
records: Optional[Sequence[str]] = None,
|
||||
suggested_questions: Optional[Sequence[str]] = None,
|
||||
) -> str:
|
||||
"""소개문·메타·FAQ 생성 프롬프트.
|
||||
|
||||
@@ -79,6 +80,14 @@ def build_prompt(
|
||||
"업소에 대해 확인된 기록(출처가 있는 글):",
|
||||
*(f"- {line}" for line in records),
|
||||
])
|
||||
if suggested_questions:
|
||||
# 업종 카탈로그 중 위 사실로 답할 수 있는 질문들(services/faq_fill.suggested_questions).
|
||||
# ★ 채우기는 fact 가 있는 질문을 건너뛴다 — 여기서 모델이 안 쓰면 그 주제는 비어 버린다.
|
||||
sections.extend([
|
||||
"",
|
||||
"FAQ 로 먼저 쓸 질문(위 사실로 답할 수 있는 것):",
|
||||
*(f"- {q}" for q in suggested_questions),
|
||||
])
|
||||
sections.extend([
|
||||
"",
|
||||
"출력:",
|
||||
@@ -96,6 +105,9 @@ def build_prompt(
|
||||
"- false·불가·없음 값을 가능하다고 표현하지 않는다.",
|
||||
"- 홍보성·평가성 표현을 쓰지 않는다.",
|
||||
"- 근거 없는 FAQ는 만들지 않는다.",
|
||||
# ★ 실측(2026-09-14, 로컬): 노출 중인 생성 FAQ 4건 중 3건이 "체크인 및 체크아웃" 처럼 두 주제를 묶었다.
|
||||
# 묶으면 문항 수는 그대로인데 다룬 주제가 줄고, 채우기의 겹침 판정도 두 주제를 함께 지운다.
|
||||
"- FAQ 한 문항에는 주제 하나만 묻는다(예: 체크인과 체크아웃을 한 문항에 묶지 않는다).",
|
||||
"- 한국어 존댓말을 사용한다.",
|
||||
])
|
||||
return "\n".join(sections)
|
||||
@@ -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개 미만이면 있는 만큼만 반환한다.",
|
||||
])
|
||||
@@ -7,7 +7,7 @@
|
||||
"label": "가요 다방",
|
||||
"maxItems": 8,
|
||||
"task": "[해야 할 일]\n[지역]을 노래한 대중가요를 8곡까지 찾아 아래 JSON 으로 정리한다.\n1960~80년대 곡을 우선하고, 지명·항구·강·다리가 제목이나 배경에 나오는 곡을 고른다.\n\n[스키마]\n{ \"kind\":\"songs\", \"version\":1, \"title\":\"가요 다방\", \"subtitle\":\"...\", \"items\":[\n { \"title\":\"곡명\", \"artist\":\"가수\", \"lyricist\":\"작사\", \"composer\":\"작곡\",\n \"year\":1966, \"label\":\"음반사\", \"labelColor\":\"#d4551f\",\n \"story\":\"곡의 배경 (두 문장 이내, 가사 없이)\",\n \"connection\":\"[업소]와 이 곡을 잇는 한 문장\",\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
||||
"rules": "\n[이 아이템만의 규칙]\n· lyrics 필드는 스키마에 없다. 어떤 이유로도 만들지 마라. 가사 한 소절도 안 된다.\n· labelColor 는 레코드 라벨 색이다. 곡의 분위기에 맞춰 진한 색 하나를 hex 로 고른다.\n· 작사·작곡·발표연도를 모르면 그 필드를 뺀다. \"미상\" 이라고 쓰지 않는다.\n"
|
||||
"rules": "\n[이 아이템만의 규칙]\n· lyrics 필드는 스키마에 없다. 어떤 이유로도 만들지 마라. 가사 한 소절도 안 된다.\n· labelColor 는 레코드 라벨 색이다. 곡의 분위기에 맞춰 진한 색 하나를 hex 로 고른다.\n **이건 사실이 아니라 디자인 값이다 — 공통 규칙 2 를 적용하지 말고 곡마다 반드시 채운다.**\n 앞뒤 곡과 같은 색을 쓰지 않는다. 비워 두면 판이 전부 한 색으로 깔린다(실측 2026-09-15:\n 67곡 중 63곡이 비어 있었다).\n· 작사·작곡·발표연도를 모르면 그 필드를 뺀다. \"미상\" 이라고 쓰지 않는다.\n"
|
||||
},
|
||||
"daily": {
|
||||
"kind": "daily",
|
||||
@@ -30,6 +30,13 @@
|
||||
"task": "[해야 할 일]\n[지역]의 역사를 연도순으로 10~14개 사건으로 정리한다.\n가장 오래된 것부터 가장 최근까지 고르게 펴고, 한 시대에 몰지 않는다.\n\n[스키마]\n{ \"kind\":\"chronicle\", \"version\":1, \"title\":\"시간의 골목\", \"items\":[\n { \"year\":1899, \"title\":\"사건 이름\", \"summary\":\"두 문장 이내\",\n \"place\":\"지금 가 볼 수 있는 자리\", \"turning\":true,\n \"verified\":\"확인|확인필요\",\n \"source\":{\"name\":\"출처명\",\"url\":\"https://...\"} } ] }",
|
||||
"rules": "\n[이 아이템만의 규칙]\n· turning 은 도시의 성격을 바꾼 해에만 true 다. 3~4개를 넘기지 않는다.\n· 연도가 불확실하면 그 항목을 통째로 뺀다. 연표에서 틀린 연도는 바로 들킨다.\n· place 는 지금도 찾아갈 수 있는 자리만 적는다. 없으면 필드를 뺀다.\n· 다만 **찾아갈 수 있는 자리가 있으면 반드시 적는다.** 행정 개편처럼 장소가 없어 보이는\n 사건에도 그 일이 남긴 자리가 대개 있다(개항 → 항구, 부두 건설 → 그 부두, 준공 → 그 구조물).\n 이 값으로 공공데이터에서 그 해의 사진을 찾아 붙인다 — 비면 연표가 활자만으로 선다.\n"
|
||||
},
|
||||
"reading": {
|
||||
"kind": "reading",
|
||||
"label": "지역 읽기",
|
||||
"maxItems": 34,
|
||||
"task": "[해야 할 일]\n[지역]을 소개하는 글 30~34꼭지를 갈래로 나눠 쓴다.\n갈래는 다섯이다 — 문학 · 섬과 바다 · 역사 · 장소 · 음식과 생활.\n한 갈래에 몰지 않되, 댈 수 있는 사실이 적은 갈래는 적게 쓴다.\n\n[스키마]\n{ \"kind\":\"reading\", \"version\":1, \"title\":\"[지역] 읽기\",\n \"subtitle\":\"문학 · 섬과 바다 · 역사 · 장소 · 음식과 생활 — 올 때마다 다른 몇 가지\",\n \"items\":[\n { \"group\":\"문학|섬과 바다|역사|장소|음식과 생활\",\n \"title\":\"꼭지 제목\", \"body\":\"서너 문장\", \"year\":1937 } ] }",
|
||||
"rules": "\n[이 아이템만의 규칙]\n· body 는 **서너 문장**이다. 두 문장이면 카드가 한 줄로 접혀 빈 카드처럼 보인다.\n 다만 문장을 늘리려고 없는 숫자·연도·거리를 지어내지 않는다 — 널리 알려진 배경만 보탠다.\n· **이미 다른 자리에 선 것은 쓰지 않는다.** 인물·대중가요·축제·연표 사건·주변 명소·맛집은\n 각자 섹션이 있다. 같은 것을 두 번 세우면 페이지만 길어지고 손님은 같은 말을 두 번 읽는다.\n· year 는 연도를 댈 수 있는 꼭지에만 쓴다. 짐작해서 넣지 않는다.\n· source 와 verified 를 적지 않는다. **주소를 짐작해 적으면 없는 문서로 이어진다** —\n 제목으로 찾아가는 검색 링크를 서버가 붙인다(2026-09-14 대표 지시).\n· 시·소설·가사의 원문을 한 줄도 옮기지 않는다. 제목과 배경만 쓴다.\n· 부제에 전체 개수를 적지 않는다. 화면은 이 중 5~6개만 매번 무작위로 보여준다 —\n 숫자를 박으면 보이는 개수와 어긋난다.\n"
|
||||
},
|
||||
"postcard": {
|
||||
"kind": "postcard",
|
||||
"label": "오늘의 엽서",
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
"""렌더 보고서 — SSG 가 실제로 페이지를 구웠는지 확인하는 창구.
|
||||
|
||||
★ 왜 필요한가
|
||||
발행 잡은 payload JSON 을 쓰는 것까지가 끝이고, 방문자가 볼 HTML 은 프론트의 SSG 가 굽는다.
|
||||
그 사이가 끊겨 있었다. 프리렌더가 깨져도 DB 에는 "발행됨"으로 남고, 페이지는 없는데
|
||||
아무도 그걸 모른다 — 사장님이 [사이트 열기] 를 눌러야 404 로 발견된다.
|
||||
BUILD 잡은 payload JSON 을 쓰고 렌더러를 직접 돌린다(services/render_service). 렌더러는
|
||||
굽는 동안 있었던 일(성공/실패, 구조화 데이터 대조, 고유 콘텐츠 수)을 사이트마다
|
||||
`<payload_dir>/.status/<slug>.json` 에 남긴다 — 백엔드에 마운트된 디렉토리가 payload
|
||||
디렉토리뿐이라 보고서도 그 안에 둔다.
|
||||
|
||||
이제 프리렌더가 사이트마다 결과를 `<payload_dir>/.status/<slug>.json` 에 쓴다.
|
||||
백엔드에 마운트된 디렉토리가 payload 디렉토리뿐이라 보고서도 그 안에 둔다.
|
||||
|
||||
★ 여기서 하는 두 가지
|
||||
1. 렌더 상태 — 구워졌는가, 언제, 실패했으면 왜 (사이트 조회 API 가 그대로 내보낸다)
|
||||
2. 발행 대기 — BUILD 잡이 이 버전의 보고서를 기다렸다가, 그 결과로 발행 여부를 정한다
|
||||
(wait_for). 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다.
|
||||
★ 여기서 하는 일 — 그 보고서를 읽는다.
|
||||
render_service 가 렌더러 subprocess 를 기다린 **직후** 한 번 읽어 발행 여부를 정하고,
|
||||
사이트 조회 API(render_status)는 아무 때나 다시 읽어 "지금 이 버전이 구워져 있나" 를 보여준다.
|
||||
|
||||
★ 읽기 전용이다. 보고서가 없거나 깨져 있어도 예외를 밖으로 내보내지 않는다 —
|
||||
사이트 조회가 부수 산출물 때문에 실패하면 안 된다.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -58,29 +54,6 @@ def read_report(slug: str) -> dict | None:
|
||||
return report
|
||||
|
||||
|
||||
async def wait_for(slug: str, site_version: int, timeout_sec: float, poll_sec: float = 1.0) -> dict | None:
|
||||
"""이 버전의 렌더 보고서가 나올 때까지 기다린다. 시간 안에 안 나오면 None.
|
||||
|
||||
★ 왜 기다리나
|
||||
발행 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 그 HTML 은 프론트 렌더러가
|
||||
굽고, 렌더러는 payload 파일을 보고 도는 별도 프로세스다. 그래서 잡이 payload 를 쓴 뒤
|
||||
보고서가 올 때까지 기다렸다가, 그 결과로 발행 여부를 정한다.
|
||||
|
||||
★ 버전이 맞는 보고서만 받는다. 직전 버전 보고서를 보고 통과시키면 이번에 바뀐 값은
|
||||
아무도 검사하지 않은 채로 발행된다.
|
||||
|
||||
★ BUILD 잡은 heartbeat 로 lease 를 갱신하므로 여기서 기다려도 reaper 에 회수되지 않는다."""
|
||||
deadline = asyncio.get_running_loop().time() + timeout_sec
|
||||
while True:
|
||||
report = read_report(slug)
|
||||
if report is not None and report.get("siteVersion") == site_version:
|
||||
return report
|
||||
if asyncio.get_running_loop().time() >= deadline:
|
||||
LOG.w(f"[render] 보고서 대기 시간 초과 slug={slug} v{site_version} ({timeout_sec}초)")
|
||||
return None
|
||||
await asyncio.sleep(poll_sec)
|
||||
|
||||
|
||||
def render_status(slug: str, site_version: int | None = None) -> dict:
|
||||
"""사이트 조회 API 가 그대로 내보내는 렌더 상태.
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""렌더러 실행 — Python 워커가 미리 컴파일된 Node 렌더러를 subprocess 로 직접 돌린다.
|
||||
|
||||
★ 왜 (프리렌더를 워커 실행으로 통합, 2026-09-15)
|
||||
예전에는 `solution-prerender` 라는 별도 상시 컨테이너가 payloads/ 디렉토리를 2초마다
|
||||
폴링하며 바뀐 파일을 구웠고, BUILD 잡은 `.status/<slug>.json` 이 나타나기를 또 폴링했다
|
||||
(render_report.wait_for). 컨테이너 하나·폴링 두 겹이 전부 "굽는 걸 어떻게 아느냐"는
|
||||
같은 문제를 풀고 있었다 — 워커가 굽기를 직접 돌리면 둘 다 필요 없다: subprocess 가
|
||||
끝나는 순간이 곧 "구워졌다"는 신호다.
|
||||
|
||||
★ 이 파일은 payload → 렌더러 실행 → 구조화된 결과, 그 경계만 다룬다.
|
||||
Python 은 여전히 HTML 을 만들지 않는다(ARCHITECTURE 1절) — 여기서 하는 일은 미리 빌드된
|
||||
JS 파일 하나를 `node` 로 실행하고 그 결과 보고서(.status/<slug>.json, prerender.ts 가 쓴다)
|
||||
를 읽어 돌려주는 것뿐이다. 렌더러 코드 자체는 solution/site 소유 그대로다.
|
||||
|
||||
★ 워커 이미지에는 컴파일된 렌더러(`dist/client` · `dist/prerender/prerender.js`)와 `public/`
|
||||
만 있으면 된다 — node_modules 는 필요 없다(vite.config.ts `ssr.noExternal: true`, 실측:
|
||||
node_modules 를 지우고 실행해도 그대로 돈다). 기동·잡 실행 중에 npm install 을 하지 않는다.
|
||||
"""
|
||||
import asyncio
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from common.logger import LOG
|
||||
from services import render_report
|
||||
|
||||
# 컴파일된 렌더러 진입점. Dockerfile 의 site-builder 스테이지가 여기에 굽는다.
|
||||
RENDERER_ENTRY_ENV = "RENDERER_ENTRY"
|
||||
DEFAULT_RENDERER_ENTRY = "/app/solution/site/dist/prerender/prerender.js"
|
||||
|
||||
NODE_BIN_ENV = "NODE_BIN"
|
||||
DEFAULT_NODE_BIN = "node"
|
||||
|
||||
# 렌더러가 굽는 산출물 루트(out/). services/azure_static·indexnow 와 **같은 env** 를 본다 —
|
||||
# 렌더러가 쓴 자리와 백엔드가 훑는 자리가 어긋나면 "구웠는데 없다"는 조용한 실패가 난다.
|
||||
OUTPUT_DIR_ENV = "SITE_OUTPUT_DIR"
|
||||
DEFAULT_OUTPUT_DIR = "/app/solution/site/out"
|
||||
|
||||
|
||||
class RenderFailed(RuntimeError):
|
||||
"""렌더러 프로세스 자체가 죽었거나(비정상 종료) 보고서를 남기지 못했다.
|
||||
|
||||
★ 게이트 반려(구조화 데이터 불일치·고유 콘텐츠 0건)는 여기 안 걸린다 — 그건 exit code
|
||||
1 이어도 보고서가 정상적으로 남으므로 호출측이 report.ok 로 판단한다. 이 예외는
|
||||
"무슨 일이 있었는지조차 모른다" 는 경우만 위한 것이다."""
|
||||
|
||||
|
||||
def renderer_entry() -> str:
|
||||
return os.environ.get(RENDERER_ENTRY_ENV) or DEFAULT_RENDERER_ENTRY
|
||||
|
||||
|
||||
def output_dir() -> str:
|
||||
return os.environ.get(OUTPUT_DIR_ENV) or DEFAULT_OUTPUT_DIR
|
||||
|
||||
|
||||
async def _run_subprocess(args: list[str], timeout_sec: float) -> tuple[int | None, str]:
|
||||
"""같은 볼륨의 자산 대장·사이트맵은 한 프로세스만 갱신한다."""
|
||||
root = Path(output_dir())
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with (root / ".render.lock").open("a") as lock:
|
||||
try:
|
||||
async with asyncio.timeout(timeout_sec):
|
||||
while True:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
await asyncio.sleep(0.1)
|
||||
return await _run_unlocked(args, timeout_sec)
|
||||
except TimeoutError:
|
||||
return None, "렌더 대기 또는 실행 시간 초과"
|
||||
finally:
|
||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
async def _run_unlocked(args: list[str], timeout_sec: float) -> tuple[int | None, str]:
|
||||
"""렌더러 프로세스를 돌리고 (exit_code, stderr 일부) 를 돌려준다.
|
||||
|
||||
★ 타임아웃이면 프로세스를 죽이고 회수한다 — 좀비로 남겨 워커 컨테이너의 프로세스 표를
|
||||
채우면 안 된다. exit_code 는 None 으로 남아 "시간 안에 안 끝났다" 를 구분한다."""
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
_stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout_sec)
|
||||
except (asyncio.TimeoutError, TimeoutError):
|
||||
proc.kill()
|
||||
# kill 후에도 반드시 wait 한다 — 안 하면 좀비 프로세스로 남는다.
|
||||
await proc.wait()
|
||||
return None, f"{timeout_sec:.0f}초 안에 끝나지 않아 강제 종료했다"
|
||||
except asyncio.CancelledError:
|
||||
if proc.returncode is None:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
raise
|
||||
# 사유는 앞부분에 나온다(watch-payloads.mjs 의 run() 과 같은 규칙) — 스택 전체를 들 이유가 없다.
|
||||
return proc.returncode, stderr.decode("utf-8", errors="replace")[:4000]
|
||||
|
||||
|
||||
async def render_site(payload_path: str, site_version: int, timeout_sec: float) -> dict:
|
||||
"""payload 파일 하나를 굽는다. 끝나면 렌더 보고서(dict)를 돌려준다.
|
||||
|
||||
★ 게이트 판정은 여기서 하지 않는다 — 반환된 보고서의 `ok`·`mismatches`·
|
||||
`uniqueContentCount` 를 build_service.run_build 가 그대로 판단한다(예전과 같은 계약,
|
||||
render_report.wait_for 가 폴링해서 얻던 것과 같은 모양이다).
|
||||
★ 멱등이다 — 같은 payload 파일로 다시 부르면 같은 결과가 나온다(재시도 안전). 렌더러
|
||||
자신이 사이트별로 실패를 격리하므로, 이미 성공한 사이트를 다시 구워도 결과는 같다."""
|
||||
slug = Path(payload_path).stem
|
||||
# 재시도에서 같은 버전의 옛 성공 보고서를 이번 실행 결과로 읽지 않는다.
|
||||
render_report.report_path(slug).unlink(missing_ok=True)
|
||||
args = [
|
||||
os.environ.get(NODE_BIN_ENV) or DEFAULT_NODE_BIN,
|
||||
renderer_entry(),
|
||||
f"--payload={payload_path}",
|
||||
f"--out={output_dir()}",
|
||||
"--stage-only",
|
||||
]
|
||||
try:
|
||||
code, stderr = await _run_subprocess(args, timeout_sec)
|
||||
except OSError as ex:
|
||||
raise RenderFailed(f"렌더러 실행 실패: {type(ex).__name__}") from ex
|
||||
|
||||
report = render_report.read_report(slug)
|
||||
if code in (0, 1) and report is not None and report.get("siteVersion") == site_version:
|
||||
return report
|
||||
|
||||
# ★ 프로세스가 죽거나 시간 초과였는데 보고서도 없으면(사이트를 하나도 돌기 전에 죽은 경우)
|
||||
# 대신 실패로 남긴다 — 안 그러면 build_service 가 "렌더 결과를 못 받았다" 는 것만 알고
|
||||
# 진짜 사유(모듈 누락·OOM 등)는 워커 로그에만 남는다.
|
||||
reason = (
|
||||
f"렌더러가 {timeout_sec:.0f}초 안에 끝나지 않았다"
|
||||
if code is None
|
||||
else f"렌더러가 비정상 종료했다(exit {code})" if code != 0 else "보고서를 남기지 못했다(버전 불일치 포함)"
|
||||
)
|
||||
detail = f"{reason}" + (f" — {stderr.strip()}" if stderr.strip() else "")
|
||||
LOG.w(f"[render] {slug} v{site_version}: {detail}")
|
||||
raise RenderFailed(detail)
|
||||
|
||||
|
||||
async def activate_site(slug: str, site_version: int) -> None:
|
||||
"""두 게이트를 통과한 뒤 Node가 공개 링크만 전환한다."""
|
||||
args = [
|
||||
os.environ.get(NODE_BIN_ENV) or DEFAULT_NODE_BIN,
|
||||
renderer_entry(), f"--out={output_dir()}", f"--activate={slug}:{site_version}",
|
||||
]
|
||||
try:
|
||||
code, _stderr = await _run_subprocess(args, 30)
|
||||
except OSError as ex:
|
||||
raise RenderFailed(f"공개 전환 실행 실패: {type(ex).__name__}") from ex
|
||||
if code != 0:
|
||||
raise RenderFailed("공개 버전 전환 실패")
|
||||
@@ -0,0 +1,158 @@
|
||||
"""예전 버전으로 되돌리기 — ROLLBACK 잡이 하는 일.
|
||||
|
||||
대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환
|
||||
|
||||
★ 재수집·재생성을 하지 않는다. run_build 와 다른 점이 이것 하나다 — 대상 버전이
|
||||
박제해 둔 snapshot(site_versions.snapshot)을 **그대로** 다시 payload 로 옮길 뿐이다.
|
||||
사장님이 그때 이미 확인하고 발행했던 값이므로, 지금 fact 상태가 바뀌었어도 롤백은
|
||||
그 시점의 값을 그대로 복원한다 — "롤백했는데 최신 수정이 섞여 있다"를 막는다.
|
||||
|
||||
★ 그래도 게이트는 다시 돈다. 스냅샷은 그대로지만 **렌더러는 그때와 다를 수 있다**
|
||||
(그 사이 배포됐을 수 있다) — 새 렌더러가 옛 스냅샷을 어떻게 굽는지는 다시 확인해야 한다.
|
||||
|
||||
★ 재굽기가 필요 없을 수도 있다 — 대상 버전 디렉토리가 보관 기간 안에 아직 디스크에 있으면
|
||||
렌더러가 그 사실을 알아서 이용한다(prerender.ts publishVersion 은 렌더 자체는 매번 다시
|
||||
하지만, 결과가 같으면 파일 내용도 같다 — 멱등이다). 디스크에서 지워졌어도 문제없다 —
|
||||
snapshot 이 있으니 처음부터 다시 굽는다.
|
||||
|
||||
★ 실패하면 지금 공개된 버전은 그대로다. render_service.render_site 가 실패를 던지거나
|
||||
report.ok=False 면 심볼릭 링크를 아예 안 돌린다(prerender.ts publishVersion 은 성공한
|
||||
렌더 결과에만 닿는다) — 발행 파이프라인과 같은 원자성 보장이다.
|
||||
"""
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, site_publish_logs, site_versions, sites
|
||||
from common.enums import (
|
||||
BuildStatus,
|
||||
DBWRType,
|
||||
ErrorType,
|
||||
PlaceCategory,
|
||||
PublishAction,
|
||||
PublishResult,
|
||||
SiteStatus,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud.site_crud import SiteCRUD
|
||||
from services import azure_static, indexnow, publish_gate, render_service, site_payload
|
||||
from services.build_service import ensure_site, load_channel_links
|
||||
|
||||
_site_crud = SiteCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
|
||||
RENDER_TIMEOUT_SEC_ENV = "RENDER_TIMEOUT_SEC"
|
||||
|
||||
|
||||
class RollbackAborted(RuntimeError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||
|
||||
|
||||
async def _log(site_id, version_id, result: PublishResult, gate=None, actor=None):
|
||||
row = site_publish_logs(
|
||||
site_id=site_id,
|
||||
site_version_id=version_id,
|
||||
action=PublishAction.ROLLBACK.value,
|
||||
result=result.value,
|
||||
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
||||
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
||||
actor_user_id=uuid.UUID(actor) if actor else None,
|
||||
)
|
||||
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
||||
|
||||
|
||||
async def run_rollback(job: dict) -> dict:
|
||||
"""ROLLBACK 잡 핸들러. payload: {place_id, owner_user_id, target_version, requested_by?}"""
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
target_version = int(payload["target_version"])
|
||||
render_timeout_sec = float(os.environ.get(RENDER_TIMEOUT_SEC_ENV) or 180)
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise RollbackAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
|
||||
site = await ensure_site(place_id)
|
||||
|
||||
v_err, version = await DB_SESSION_MNG.execute_lambda(
|
||||
site_versions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _site_crud.get_version_by_number(s, site.site_id, target_version),
|
||||
)
|
||||
if v_err != ErrorType.SUCCESS or version is None:
|
||||
raise RollbackAborted(f"버전 {target_version} 을 찾을 수 없다")
|
||||
if version.build_status != BuildStatus.BUILT.value or not version.snapshot:
|
||||
raise RollbackAborted(f"버전 {target_version} 은 성공적으로 빌드된 적이 없어 되돌릴 수 없다")
|
||||
if site.current_version_id == version.site_version_id:
|
||||
raise RollbackAborted(f"이미 지금 공개 중인 버전이다(v{target_version})")
|
||||
|
||||
result = {
|
||||
"place_id": place_id, "site_id": str(site.site_id),
|
||||
"target_version": target_version, "site_version_id": str(version.site_version_id),
|
||||
}
|
||||
|
||||
async def _fail(reason: str, gate: publish_gate.GateResult | None = None):
|
||||
await _log(site.site_id, version.site_version_id, PublishResult.REJECTED if gate else PublishResult.FAILED,
|
||||
gate, payload.get("requested_by"))
|
||||
result["rolled_back"] = False
|
||||
result["error"] = reason
|
||||
LOG.w(f"[rollback] place={place_id} v{target_version} 실패: {reason}")
|
||||
return result
|
||||
|
||||
# ★ snapshot 을 그대로 옮긴다 — 재수집하지 않는다(파일 머리주석 참조).
|
||||
links = await load_channel_links(place_id)
|
||||
payload_dict = await site_payload.prepare_site_payload(
|
||||
place, version.snapshot, site, version, links, publish=True
|
||||
)
|
||||
payload_path = site_payload.write_payload(payload_dict)
|
||||
result["payload_path"] = payload_path
|
||||
|
||||
try:
|
||||
report = await render_service.render_site(payload_path, target_version, render_timeout_sec)
|
||||
except render_service.RenderFailed as ex:
|
||||
return await _fail(str(ex))
|
||||
|
||||
mismatches = list(report.get("mismatches") or [])
|
||||
unique_count_raw = report.get("uniqueContentCount")
|
||||
|
||||
# ★ 렌더러가 그때와 달라졌을 수 있으므로 게이트를 다시 돈다(파일 머리주석 참조) —
|
||||
# fact 검증 게이트(1차)는 건너뛴다. snapshot 은 이미 확인된 값만 담아 발행했던 것이라
|
||||
# 다시 물을 것이 없다 — 여기서 또 물으면 "그때는 됐는데 지금은 안 된다"는 모순이 난다.
|
||||
gate = publish_gate.evaluate(
|
||||
PlaceCategory(place.category), version.snapshot.get("facts") or [], unique_count_raw, mismatches
|
||||
)
|
||||
result["gate"] = {"passed": gate.passed, **gate.as_log()}
|
||||
if not gate.passed:
|
||||
return await _fail(f"{gate.reason.name}: {gate.as_log()}", gate)
|
||||
if not report.get("ok"):
|
||||
return await _fail(str(report.get("error") or "렌더 실패"))
|
||||
|
||||
slug = site_payload.publish_slug(place, site)
|
||||
try:
|
||||
await render_service.activate_site(slug, target_version)
|
||||
await azure_static.publish(slug)
|
||||
except (render_service.RenderFailed, azure_static.AzurePublishError) as ex:
|
||||
return await _fail(str(ex))
|
||||
await indexnow.submit(slug)
|
||||
|
||||
now = GTime.UTC()
|
||||
site_update = {
|
||||
"status": SiteStatus.PUBLISHED.value,
|
||||
"current_version_id": version.site_version_id,
|
||||
"published_at": now,
|
||||
}
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
sites.DBType(), lambda s: _site_crud.update_site(s, site.site_id, site_update)
|
||||
)
|
||||
await _log(site.site_id, version.site_version_id, PublishResult.SUCCESS, None, payload.get("requested_by"))
|
||||
|
||||
result["rolled_back"] = True
|
||||
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
||||
return result
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Teams Workflow 수신용. 원문 오류/인증 정보는 메시지에 싣지 않는다."""
|
||||
from datetime import timedelta
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
def alert_reason(row, now, days: int) -> str | None:
|
||||
if row.alerted_at and now - row.alerted_at < timedelta(days=1):
|
||||
return None
|
||||
if row.error_code:
|
||||
return f"조회/제출 실패: {row.error_code}"
|
||||
if (row.inspection or {}).get("verdict") == "PASS":
|
||||
return None
|
||||
if now - row.published_at >= timedelta(days=days):
|
||||
return f"발행 후 {days}일 이상 색인 미확인"
|
||||
return None
|
||||
|
||||
|
||||
async def send_alert(webhook_url: str, page_url: str, reason: str) -> bool:
|
||||
if not webhook_url:
|
||||
return False
|
||||
if not webhook_url.startswith("https://"):
|
||||
LOG.w("[search-console] ALERT_URL_INVALID")
|
||||
return False
|
||||
payload = {"type": "message", "attachments": [{
|
||||
"contentType": "application/vnd.microsoft.card.adaptive",
|
||||
"contentUrl": None,
|
||||
"content": {"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
"type": "AdaptiveCard", "version": "1.2", "body": [
|
||||
{"type": "TextBlock", "text": "Google 색인 확인 필요", "weight": "Bolder"},
|
||||
{"type": "TextBlock", "text": page_url, "wrap": True},
|
||||
{"type": "TextBlock", "text": reason, "wrap": True},
|
||||
]},
|
||||
}]}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
|
||||
response = await client.post(webhook_url, json=payload)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
except httpx.HTTPError:
|
||||
# webhook 주소 자체가 인증 수단이므로 예외 문자열도 로그에 남기지 않는다.
|
||||
LOG.w("[search-console] ALERT_DELIVERY_FAILED")
|
||||
return False
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Google Search Console REST 클라이언트 — 사이트맵 제출 · URL 색인 상태 조회.
|
||||
|
||||
PUT https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/sitemaps/{feedpath}
|
||||
POST https://searchconsole.googleapis.com/v1/urlInspection/index:inspect
|
||||
|
||||
자세한 계약은 docs/SEARCH_CONSOLE_CLIENT.md.
|
||||
|
||||
★ `SearchConsoleError` 는 `code` 문자열만 담는다 — Google 응답 본문·토큰·키·원본
|
||||
예외 메시지는 절대 싣지 않는다.
|
||||
★ `inspectionResult`·`indexStatusResult` 가 없거나 빈 응답은 "미색인"으로
|
||||
넘겨짚지 않고 예외로 끊는다 — 검사 실패와 색인 결과를 구분 못하면 오판이 된다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
|
||||
SITEMAPS_BASE = "https://www.googleapis.com/webmasters/v3/sites"
|
||||
INSPECT_URL = "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect"
|
||||
SCOPES = ["https://www.googleapis.com/auth/webmasters"]
|
||||
TIMEOUT_SEC = 20.0
|
||||
AUTH_REFRESH_TIMEOUT_SEC = 20.0
|
||||
|
||||
|
||||
class SearchConsoleError(RuntimeError):
|
||||
"""code 만 담는다 — Google 응답 본문·토큰·키는 여기 실으면 안 된다."""
|
||||
|
||||
def __init__(self, code: str):
|
||||
self.code = code
|
||||
super().__init__(code)
|
||||
|
||||
|
||||
def _service_account_credentials(credentials_file: str):
|
||||
"""lazy import — 미설치여도 이 모듈의 import 자체는 죽지 않는다."""
|
||||
from google.oauth2 import service_account
|
||||
|
||||
return service_account.Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
|
||||
|
||||
|
||||
def _refresh_sync(credentials) -> None:
|
||||
"""동기 토큰 갱신. `asyncio.to_thread` 로 감싸 부른다.
|
||||
|
||||
`Request.__call__` 기본 타임아웃(120s)을 그대로 두면 만료된 키·막힌 네트워크에서
|
||||
오래 걸릴 수 있다 — 매 요청에 상한을 강제로 덮어씌운다(호출측이 넘긴 값 포함)."""
|
||||
import requests
|
||||
from google.auth.transport.requests import Request
|
||||
|
||||
with requests.Session() as session:
|
||||
original_request = session.request
|
||||
|
||||
def _request_with_timeout(*args, **kwargs):
|
||||
kwargs["timeout"] = AUTH_REFRESH_TIMEOUT_SEC
|
||||
return original_request(*args, **kwargs)
|
||||
|
||||
session.request = _request_with_timeout
|
||||
credentials.refresh(Request(session=session))
|
||||
|
||||
|
||||
def _status_error_code(status_code: int) -> str:
|
||||
if status_code == 401:
|
||||
return "unauthorized"
|
||||
if status_code == 403:
|
||||
return "forbidden"
|
||||
if status_code == 429:
|
||||
return "rate_limited"
|
||||
if 500 <= status_code < 600:
|
||||
return "server_error"
|
||||
return f"http_{status_code}"
|
||||
|
||||
|
||||
def _transport_error_code(ex: httpx.HTTPError) -> str:
|
||||
if isinstance(ex, httpx.TimeoutException):
|
||||
return "timeout"
|
||||
return "transport_error"
|
||||
|
||||
|
||||
class SearchConsoleClient:
|
||||
def __init__(self, credentials_file: str, *, transport: httpx.AsyncBaseTransport | None = None):
|
||||
self._credentials_file = credentials_file
|
||||
self._client = httpx.AsyncClient(timeout=TIMEOUT_SEC, transport=transport)
|
||||
self._credentials: Any = None
|
||||
self._auth_lock = asyncio.Lock()
|
||||
|
||||
async def __aenter__(self) -> "SearchConsoleClient":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> None:
|
||||
await self.aclose()
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self._client.aclose()
|
||||
|
||||
async def submit_sitemap(self, property_url: str, sitemap_url: str) -> None:
|
||||
url = f"{SITEMAPS_BASE}/{quote(property_url, safe='')}/sitemaps/{quote(sitemap_url, safe='')}"
|
||||
headers = await self._auth_headers()
|
||||
res = await self._put(url, headers)
|
||||
self._raise_for_status(res)
|
||||
|
||||
async def inspect_url(self, property_url: str, page_url: str) -> dict[str, Any]:
|
||||
headers = await self._auth_headers()
|
||||
body = {"inspectionUrl": page_url, "siteUrl": property_url}
|
||||
res = await self._post(INSPECT_URL, headers, body)
|
||||
self._raise_for_status(res)
|
||||
return _index_status_result(res)
|
||||
|
||||
async def _put(self, url: str, headers: dict[str, str]) -> httpx.Response:
|
||||
try:
|
||||
return await self._client.put(url, headers=headers)
|
||||
except httpx.HTTPError as ex:
|
||||
raise SearchConsoleError(_transport_error_code(ex)) from None
|
||||
|
||||
async def _post(self, url: str, headers: dict[str, str], body: dict[str, Any]) -> httpx.Response:
|
||||
try:
|
||||
return await self._client.post(url, headers=headers, json=body)
|
||||
except httpx.HTTPError as ex:
|
||||
raise SearchConsoleError(_transport_error_code(ex)) from None
|
||||
|
||||
def _raise_for_status(self, res: httpx.Response) -> None:
|
||||
if not res.is_success:
|
||||
raise SearchConsoleError(_status_error_code(res.status_code))
|
||||
|
||||
async def _auth_headers(self) -> dict[str, str]:
|
||||
token = await self._access_token()
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
async def _access_token(self) -> str:
|
||||
credentials = self._load_credentials()
|
||||
if not getattr(credentials, "valid", False):
|
||||
async with self._auth_lock:
|
||||
if not getattr(credentials, "valid", False):
|
||||
try:
|
||||
await asyncio.to_thread(_refresh_sync, credentials)
|
||||
except Exception:
|
||||
raise SearchConsoleError("auth_failed") from None
|
||||
token = getattr(credentials, "token", None)
|
||||
if not token:
|
||||
raise SearchConsoleError("auth_failed")
|
||||
return token
|
||||
|
||||
def _load_credentials(self) -> Any:
|
||||
if self._credentials is None:
|
||||
try:
|
||||
self._credentials = _service_account_credentials(self._credentials_file)
|
||||
except Exception:
|
||||
raise SearchConsoleError("invalid_credentials_file") from None
|
||||
return self._credentials
|
||||
|
||||
|
||||
def _index_status_result(res: httpx.Response) -> dict[str, Any]:
|
||||
try:
|
||||
data = res.json()
|
||||
except ValueError:
|
||||
raise SearchConsoleError("invalid_json") from None
|
||||
inspection_result = data.get("inspectionResult") if isinstance(data, dict) else None
|
||||
if not isinstance(inspection_result, dict):
|
||||
raise SearchConsoleError("missing_inspection_result")
|
||||
index_status_result = inspection_result.get("indexStatusResult")
|
||||
if not isinstance(index_status_result, dict) or not index_status_result:
|
||||
raise SearchConsoleError("missing_index_status_result")
|
||||
return index_status_result
|
||||
@@ -0,0 +1,129 @@
|
||||
"""발행 감지 → 사이트맵 제출 → 색인 조회 → 알림. 발행 잡과 별도 트랜잭션이다."""
|
||||
import asyncio
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import httpx
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType
|
||||
from common.logger import LOG
|
||||
from crud import search_console_crud as store
|
||||
from services import site_payload
|
||||
from services.search_console_alerts import alert_reason, send_alert
|
||||
from services.search_console_client import SearchConsoleClient, SearchConsoleError
|
||||
from services.search_console_settings import load_settings, belongs_to_property
|
||||
|
||||
|
||||
async def run_scheduled_check():
|
||||
try:
|
||||
settings = load_settings()
|
||||
if settings is None:
|
||||
return
|
||||
await DB_SESSION_MNG.execute_lambda_write(
|
||||
DBType.MAIN.value, lambda session: run_batch(session, settings),
|
||||
)
|
||||
except Exception:
|
||||
# 크론 실패가 API/발행에 전파되지 않고 다음 주기에 재시도된다.
|
||||
LOG.w("[search-console] BATCH_FAILED — 설정 및 DB 마이그레이션 확인 필요")
|
||||
|
||||
|
||||
async def run_batch(session, settings):
|
||||
if not await store.lock_batch(session):
|
||||
return
|
||||
if not belongs_to_property(site_payload.publish_origin() + "/sitemap.xml", settings.property_url):
|
||||
raise SearchConsoleError("PROPERTY_MISMATCH")
|
||||
await register_publications(session, settings)
|
||||
rows = await store.due_sites(session, settings.property_url)
|
||||
if not rows:
|
||||
return
|
||||
async with SearchConsoleClient(settings.credentials_file) as client:
|
||||
submitted = set()
|
||||
for row in rows:
|
||||
await check_site(client, row, settings, submitted)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def register_publications(session, settings):
|
||||
for site, place, version in await store.new_publications(session, settings.property_url):
|
||||
slug = site_payload.publish_slug(place, site)
|
||||
page_url = f"{site_payload.publish_origin()}/s/{slug}"
|
||||
if not belongs_to_property(page_url, settings.property_url):
|
||||
LOG.w("[search-console] PROPERTY_MISMATCH")
|
||||
continue
|
||||
await store.register(session, {
|
||||
"site_id": site.site_id, "site_version_id": version.site_version_id,
|
||||
"property_url": settings.property_url, "page_url": page_url,
|
||||
"published_at": site.published_at,
|
||||
})
|
||||
|
||||
|
||||
async def read_sitemap(sitemap_url: str) -> set[str]:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20, follow_redirects=False) as client:
|
||||
async with client.stream("GET", sitemap_url) as response:
|
||||
response.raise_for_status()
|
||||
body = bytearray()
|
||||
async for chunk in response.aiter_bytes():
|
||||
body.extend(chunk)
|
||||
if len(body) > 5_000_000:
|
||||
raise SearchConsoleError("SITEMAP_TOO_LARGE")
|
||||
root = ET.fromstring(body)
|
||||
return {(item.text or "").strip() for item in root.iter(
|
||||
"{http://www.sitemaps.org/schemas/sitemap/0.9}loc"
|
||||
)}
|
||||
except (httpx.HTTPError, ET.ParseError):
|
||||
raise SearchConsoleError("SITEMAP_UNAVAILABLE") from None
|
||||
|
||||
|
||||
async def submit_sitemap(client, row, submitted: set):
|
||||
if row.sitemap_submitted_at:
|
||||
return
|
||||
sitemap_url = site_payload.publish_origin() + "/sitemap.xml"
|
||||
# 디스크가 아니라 실제 공개 URL을 확인한다. 업로드 지연 시 Google에 먼저 알리지 않는다.
|
||||
urls = await read_sitemap(sitemap_url)
|
||||
if row.page_url not in urls:
|
||||
raise SearchConsoleError("URL_NOT_IN_SITEMAP")
|
||||
if sitemap_url not in submitted:
|
||||
await client.submit_sitemap(row.property_url, sitemap_url)
|
||||
submitted.add(sitemap_url)
|
||||
row.sitemap_submitted_at = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def record_inspection(row, inspection: dict, now):
|
||||
row.inspection = inspection
|
||||
row.inspected_at = now
|
||||
row.error_code = None
|
||||
row.failures = 0
|
||||
if inspection.get("verdict") == "PASS":
|
||||
row.first_indexed_at = row.first_indexed_at or now
|
||||
row.next_check_at = now + timedelta(days=1)
|
||||
|
||||
|
||||
def record_error(row, code: str, now):
|
||||
row.error_code = code
|
||||
row.failures = (row.failures or 0) + 1
|
||||
hours = min(24, 2 ** min(row.failures - 1, 5))
|
||||
row.next_check_at = now + timedelta(hours=hours)
|
||||
|
||||
|
||||
async def check_site(client, row, settings, submitted: set):
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
if not belongs_to_property(row.page_url, settings.property_url):
|
||||
raise SearchConsoleError("PROPERTY_MISMATCH")
|
||||
async with asyncio.timeout(90):
|
||||
await submit_sitemap(client, row, submitted)
|
||||
inspection = await client.inspect_url(row.property_url, row.page_url)
|
||||
record_inspection(row, inspection, now)
|
||||
except SearchConsoleError as ex:
|
||||
record_error(row, ex.code, now)
|
||||
except TimeoutError:
|
||||
record_error(row, "CHECK_TIMEOUT", now)
|
||||
except Exception:
|
||||
record_error(row, "CHECK_FAILED", now)
|
||||
reason = alert_reason(row, now, settings.alert_days)
|
||||
if reason:
|
||||
LOG.w(f"[search-console] site={row.site_id} {reason}")
|
||||
if await send_alert(settings.alert_url, row.page_url, reason):
|
||||
row.alerted_at = now
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Google 로그인 설정과 분리한다. 서비스 계정 키는 서버 파일로만 읽는다."""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SearchConsoleSettings:
|
||||
property_url: str
|
||||
credentials_file: str
|
||||
alert_url: str = ""
|
||||
alert_days: int = 7
|
||||
|
||||
|
||||
def load_settings() -> SearchConsoleSettings | None:
|
||||
if os.environ.get("GSC_ENABLED") != "1":
|
||||
return None
|
||||
prop = os.environ.get("GSC_PROPERTY_URL", "").strip()
|
||||
key_file = os.environ.get("GSC_CREDENTIALS_FILE", "").strip()
|
||||
if not prop or not key_file:
|
||||
raise ValueError("GSC_CONFIG_MISSING")
|
||||
parsed = urlsplit(prop)
|
||||
domain_property = prop.startswith("sc-domain:") and bool(prop.removeprefix("sc-domain:"))
|
||||
root_property = (parsed.scheme == "https" and parsed.hostname and parsed.path == "/"
|
||||
and not parsed.query and not parsed.fragment and not parsed.username)
|
||||
if not domain_property and not root_property:
|
||||
raise ValueError("GSC_PROPERTY_INVALID")
|
||||
days = int(os.environ.get("GSC_ALERT_DAYS", "7"))
|
||||
if days < 1:
|
||||
raise ValueError("GSC_ALERT_DAYS_INVALID")
|
||||
return SearchConsoleSettings(prop, key_file, os.environ.get("GSC_ALERT_WEBHOOK_URL", ""), days)
|
||||
|
||||
|
||||
def belongs_to_property(page_url: str, property_url: str) -> bool:
|
||||
parsed = urlsplit(page_url)
|
||||
if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
|
||||
return False
|
||||
if parsed.query or parsed.fragment:
|
||||
return False
|
||||
if property_url.startswith("sc-domain:"):
|
||||
domain = property_url.removeprefix("sc-domain:").lower()
|
||||
return bool(domain) and (parsed.hostname == domain or parsed.hostname.endswith("." + domain))
|
||||
return page_url.startswith(property_url)
|
||||
@@ -6,6 +6,8 @@
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from common.enums import SourceType
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AuditCheck:
|
||||
@@ -31,7 +33,8 @@ def _check(id, group, label, points, passed, detail, recommendation=None, partia
|
||||
def evaluate(snapshot: dict, *, verified: bool, site=None, version=None, ai_checks: list | None = None) -> dict:
|
||||
place = snapshot.get("place") or {}
|
||||
facts = snapshot.get("facts") or []
|
||||
faqs = snapshot.get("faqs") or []
|
||||
# 문의 안내(TEMPLATE)는 답이 아니다 — "질문형 FAQ" 에 세면 채우기만으로 만점이 난다.
|
||||
faqs = [q for q in (snapshot.get("faqs") or []) if q.get("generated_by") != SourceType.TEMPLATE.value]
|
||||
media = snapshot.get("media") or []
|
||||
built = bool(version and getattr(version, "built_at", None))
|
||||
unique_count = int(getattr(version, "unique_content_count", 0) or 0) if version else 0
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
"""발행 사이트 메타 태그용 검색 키워드 — SiteOntology 추천을 이 가게의 확인된 자료로 한 번 더 거른다.
|
||||
|
||||
스냅샷 → 업체 프로필(build_merchant) → SiteOntology publish + match → 거르기(select)
|
||||
→ snapshot["seo"] → payload.seo → <meta name="keywords"> · <title> 의 업종어 자리
|
||||
|
||||
★ 스냅샷에 싣는다(site_versions.snapshot). payload 는 스냅샷만 보고 만든다는 원칙(site_payload 머리주석)을
|
||||
그대로 지키고, "이 버전에 어떤 키워드가 나갔나" 가 발행 기록으로 남는다. SiteOntology 쪽에는 남기지 않는다.
|
||||
★ 숙박만 부른다. SiteOntology 사전은 펜션 키워드뿐이다(2026-09-14 기준 industry=stay.pension).
|
||||
다른 업종으로 부르면 펜션 단어가 카페 사이트의 메타 태그에 붙는다.
|
||||
|
||||
★ 거르기 규칙은 하나다 — **키워드의 모든 낱말이 이 가게의 확인된 자료에 있어야 한다.**
|
||||
SiteOntology 의 사실 필터는 수용 인원과 일부 시설(바베큐·수영장·스파…)만 본다. 실측(2026-09-14, 스테이머뭄
|
||||
프로필)에서 `군산 독채 마당 펜션`·`군산 독채 복층 펜션` 이 status=ok 로 왔다 — 마당·복층은 확인된 적이 없다.
|
||||
사전에는 `선유도 독채펜션`(다른 권역)·`군산 펜션 최저가`(가격 주장)도 있다. 낱말 대조 하나로 셋이 함께 걸린다.
|
||||
메타 태그와 제목은 AI 검색이 그대로 읽는 자리라, 확인 안 된 시설을 광고하는 단어는 지어낸 문장과 같다
|
||||
(solution/site/src/seo/meta.ts 머리주석 — description 은 지어내지 않는다).
|
||||
"자료" 는 상호·소개문·주소·확인된 시설/객실 fact·발행되는 주변 관광지다. 미확인(unverified)은 자료가 아니다.
|
||||
"""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from common.enums import LocalContentType, PlaceCategory
|
||||
from common.logger import LOG
|
||||
from services.external import site_ontology
|
||||
from services.site_payload import _parse_address_parts
|
||||
|
||||
LODGING_INDUSTRY = "stay.pension"
|
||||
MAX_KEYWORDS = 10
|
||||
MAX_NEARBY = 8
|
||||
|
||||
# ★ SiteOntology 의 시설 어휘(match.rules.ts AMENITY_SYNONYMS)로 옮긴다 — 저쪽이 이 낱말로 보유 시설을 판정한다.
|
||||
# 값이 "true" 면 있음 → features, "false" 면 **없음** → 어디에도 넣지 않는다(그래야 저쪽이 그 시설 키워드를 배제한다),
|
||||
# fact 가 아예 없으면 **모름** → unverified(저쪽이 배제하지 않고 보류한다 — 없음과 모름은 다르다).
|
||||
_AMENITY_FACTS = {
|
||||
"bbq_available": "바베큐",
|
||||
"parking": "주차",
|
||||
"pet_allowed": "애견동반",
|
||||
"breakfast": "조식",
|
||||
}
|
||||
# 사장님이 확인한 글자 그대로 싣는 fact(객실 단위 포함). "독채"·"오션뷰" 같은 유형·전망어가 여기서 온다.
|
||||
_FEATURE_TEXT_KEYS = ("room_type", "building_scale", "facilities", "view")
|
||||
_CAPACITY_KEYS = ("max_capacity", "accommodation_capacity")
|
||||
|
||||
# (ISO 3166-2 시·도, 시·군) → SiteOntology region 키(data/regions.json 54개).
|
||||
# ★ 시·도를 함께 본다 — 고성군은 강원과 경남에 둘 다 있다.
|
||||
# ★ 을왕리(kr.incheon.yeongjong)는 넣지 않는다. 행정구역으로는 인천 중구인데 중구 전체를 을왕리로 보낼 수 없다.
|
||||
_REGION_KEYS = {
|
||||
("KR-41", "가평군"): "kr.gyeonggi.gapyeong", ("KR-41", "양평군"): "kr.gyeonggi.yangpyeong",
|
||||
("KR-41", "포천시"): "kr.gyeonggi.pocheon", ("KR-41", "파주시"): "kr.gyeonggi.paju",
|
||||
("KR-28", "강화군"): "kr.incheon.ganghwa",
|
||||
("KR-42", "춘천시"): "kr.gangwon.chuncheon", ("KR-42", "홍천군"): "kr.gangwon.hongcheon",
|
||||
("KR-42", "인제군"): "kr.gangwon.inje", ("KR-42", "평창군"): "kr.gangwon.pyeongchang",
|
||||
("KR-42", "정선군"): "kr.gangwon.jeongseon", ("KR-42", "강릉시"): "kr.gangwon.gangneung",
|
||||
("KR-42", "속초시"): "kr.gangwon.sokcho", ("KR-42", "양양군"): "kr.gangwon.yangyang",
|
||||
("KR-42", "고성군"): "kr.gangwon.goseong", ("KR-42", "동해시"): "kr.gangwon.donghae",
|
||||
("KR-42", "삼척시"): "kr.gangwon.samcheok", ("KR-42", "태백시"): "kr.gangwon.taebaek",
|
||||
("KR-43", "단양군"): "kr.chungbuk.danyang", ("KR-43", "제천시"): "kr.chungbuk.jecheon",
|
||||
("KR-43", "충주시"): "kr.chungbuk.chungju", ("KR-43", "괴산군"): "kr.chungbuk.goesan",
|
||||
("KR-44", "태안군"): "kr.chungnam.taean", ("KR-44", "보령시"): "kr.chungnam.boryeong",
|
||||
("KR-44", "서산시"): "kr.chungnam.seosan", ("KR-44", "공주시"): "kr.chungnam.gongju",
|
||||
("KR-44", "부여군"): "kr.chungnam.buyeo",
|
||||
("KR-45", "군산시"): "kr.jeonbuk.gunsan", ("KR-45", "부안군"): "kr.jeonbuk.buan",
|
||||
("KR-45", "전주시"): "kr.jeonbuk.jeonju", ("KR-45", "무주군"): "kr.jeonbuk.muju",
|
||||
("KR-45", "남원시"): "kr.jeonbuk.namwon",
|
||||
("KR-46", "여수시"): "kr.jeonnam.yeosu", ("KR-46", "순천시"): "kr.jeonnam.suncheon",
|
||||
("KR-46", "담양군"): "kr.jeonnam.damyang", ("KR-46", "구례군"): "kr.jeonnam.gurye",
|
||||
("KR-46", "해남군"): "kr.jeonnam.haenam", ("KR-46", "완도군"): "kr.jeonnam.wando",
|
||||
("KR-46", "보성군"): "kr.jeonnam.boseong",
|
||||
("KR-47", "경주시"): "kr.gyeongbuk.gyeongju", ("KR-47", "포항시"): "kr.gyeongbuk.pohang",
|
||||
("KR-47", "안동시"): "kr.gyeongbuk.andong", ("KR-47", "영덕군"): "kr.gyeongbuk.yeongdeok",
|
||||
("KR-47", "울진군"): "kr.gyeongbuk.uljin", ("KR-47", "문경시"): "kr.gyeongbuk.mungyeong",
|
||||
("KR-48", "거제시"): "kr.gyeongnam.geoje", ("KR-48", "통영시"): "kr.gyeongnam.tongyeong",
|
||||
("KR-48", "남해군"): "kr.gyeongnam.namhae", ("KR-48", "하동군"): "kr.gyeongnam.hadong",
|
||||
("KR-48", "사천시"): "kr.gyeongnam.sacheon", ("KR-48", "산청군"): "kr.gyeongnam.sancheong",
|
||||
("KR-26", "기장군"): "kr.busan.gijang",
|
||||
("KR-49", "제주시"): "kr.jeju.jejusi", ("KR-49", "서귀포시"): "kr.jeju.seogwipo",
|
||||
}
|
||||
|
||||
# 자료에 없어도 되는 낱말 — 업종어와 "근처" 류. 무엇을 주장하지 않는다.
|
||||
_GENERIC_WORDS = frozenset({"펜션", "숙소", "숙박", "스테이", "근처", "가까운", "주변", "인근", "예약", "추천"})
|
||||
# "독채펜션"·"감성숙소" 처럼 붙여 쓴 업종어는 떼고 앞부분만 자료와 대조한다.
|
||||
_GENERIC_SUFFIXES = ("펜션", "숙소", "스테이")
|
||||
# 제목에는 싣지 않는 낱말. `스테이,머뭄 · 군산 독채펜션 예약` 은 검색어로는 맞아도 가게 이름 옆에서는 광고 문구다.
|
||||
_TITLE_BLOCKED_WORDS = frozenset({"예약", "추천"})
|
||||
# 한 글자 낱말("봄"·"뷰")은 소개문 어딘가에 우연히 들어 있어 대조가 무의미하다 — 통과시키지 않는다.
|
||||
_MIN_CORE_LEN = 2
|
||||
|
||||
_NON_WORD = re.compile(r"[^\w]")
|
||||
|
||||
|
||||
def _text(value) -> str:
|
||||
return str(value).strip() if value is not None else ""
|
||||
|
||||
|
||||
def _compact(text: str) -> str:
|
||||
"""대조용 표기 — 공백·구두점을 지우고 소문자로. "스테이,머뭄" 과 "스테이 머뭄" 이 같아진다."""
|
||||
return _NON_WORD.sub("", unicodedata.normalize("NFKC", text or "").lower())
|
||||
|
||||
|
||||
def _number(value) -> int | None:
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def region_key(*addresses: str | None) -> str | None:
|
||||
"""주소 → SiteOntology region 키. 표에 없으면 None(지어내지 않는다)."""
|
||||
parts = _parse_address_parts(*addresses)
|
||||
locality = (parts.get("addressLocality") or "").split()
|
||||
if not locality:
|
||||
return None
|
||||
return _REGION_KEYS.get((parts["addressRegionCode"], locality[0]))
|
||||
|
||||
|
||||
def _locality_word(*addresses: str | None) -> str:
|
||||
"""사람이 검색창에 치는 시·군 이름 — "군산시" → "군산". 제목 키워드가 이 낱말을 품어야 한다."""
|
||||
locality = (_parse_address_parts(*addresses).get("addressLocality") or "").split()
|
||||
if not locality:
|
||||
return ""
|
||||
word = locality[0]
|
||||
return word[:-1] if len(word) > 2 and word.endswith(("시", "군", "구")) else word
|
||||
|
||||
|
||||
def build_merchant(place_id: str, snapshot: dict) -> dict | None:
|
||||
"""스냅샷 → SiteOntology publish 요청 본문. 숙박이 아니거나 상호가 없으면 None.
|
||||
|
||||
★ 스냅샷만 읽는다 — 스냅샷에는 노출 가능한 값(VERIFIED/CORRECTED fact · 발행 창 안의 지역 정보)만 있다.
|
||||
미검증 fact 를 프로필에 실으면 그걸 근거로 고른 키워드가 메타 태그로 나간다."""
|
||||
place = (snapshot or {}).get("place") or {}
|
||||
if _number(place.get("category")) != PlaceCategory.LODGING.value:
|
||||
return None
|
||||
name = _text(place.get("name"))
|
||||
if not name:
|
||||
return None
|
||||
|
||||
values: dict[str, list[str]] = {}
|
||||
for fact in (snapshot or {}).get("facts") or []:
|
||||
if not isinstance(fact, dict):
|
||||
continue
|
||||
value = _text(fact.get("value"))
|
||||
if value:
|
||||
values.setdefault(_text(fact.get("key")), []).append(value)
|
||||
|
||||
features: list[str] = []
|
||||
unverified: list[str] = []
|
||||
for key, label in _AMENITY_FACTS.items():
|
||||
found = values.get(key)
|
||||
if not found:
|
||||
unverified.append(label)
|
||||
elif "true" in found:
|
||||
features.append(label)
|
||||
for key in _FEATURE_TEXT_KEYS:
|
||||
for value in values.get(key, []):
|
||||
if value not in features:
|
||||
features.append(value)
|
||||
|
||||
capacities = [n for key in _CAPACITY_KEYS for n in map(_number, values.get(key, [])) if n]
|
||||
intro = next(iter(values.get("intro", [])), "")
|
||||
description = next((p.strip() for p in intro.split("\n") if p.strip()), "")
|
||||
|
||||
nearby: list[str] = []
|
||||
for row in ((snapshot or {}).get("local") or {}).get("contents") or []:
|
||||
if not isinstance(row, dict) or row.get("content_type") != LocalContentType.ATTRACTION.value:
|
||||
continue
|
||||
attraction = _text((row.get("body") or {}).get("name")) or _text(row.get("title"))
|
||||
if attraction and attraction not in nearby:
|
||||
nearby.append(attraction)
|
||||
if len(nearby) >= MAX_NEARBY:
|
||||
break
|
||||
|
||||
road_address, address = place.get("road_address"), place.get("address")
|
||||
profile = {
|
||||
"address": _text(road_address) or _text(address),
|
||||
"capacity": {"max": max(capacities)} if capacities else None,
|
||||
"features": features,
|
||||
"nearby": nearby,
|
||||
"unverified": unverified,
|
||||
}
|
||||
return {
|
||||
"externalId": place_id,
|
||||
"name": name,
|
||||
"industryId": LODGING_INDUSTRY,
|
||||
"regionId": region_key(road_address, address),
|
||||
"description": description,
|
||||
"profile": {key: value for key, value in profile.items() if value},
|
||||
}
|
||||
|
||||
|
||||
def _evidence(merchant: dict) -> str:
|
||||
"""이 가게의 확인된 자료를 한 덩어리로. 키워드 낱말은 여기에 들어 있어야 한다."""
|
||||
profile = merchant.get("profile") or {}
|
||||
parts = [
|
||||
merchant.get("name"), merchant.get("description"), profile.get("address"),
|
||||
*(profile.get("features") or []), *(profile.get("nearby") or []),
|
||||
]
|
||||
return _compact(" ".join(_text(p) for p in parts if p))
|
||||
|
||||
|
||||
def _supported(keyword: str, evidence: str) -> bool:
|
||||
"""모든 낱말이 자료에 있고, **자료로 확인한 낱말이 하나는 있어야** 한다.
|
||||
|
||||
★ 뒤 조건이 없으면 `숙소` 처럼 업종어뿐인 단어가 "주장하는 게 없다" 는 이유로 통과한다 —
|
||||
실측(2026-09-14, 실제 발행 한 바퀴)에서 메타 10칸 중 한 칸이 `숙소` 였다. 어느 가게에나 붙는 단어라
|
||||
이 가게를 설명하지 못한다."""
|
||||
specific = False
|
||||
for word in keyword.split():
|
||||
if word in _GENERIC_WORDS:
|
||||
continue
|
||||
core = next((word[: -len(s)] for s in _GENERIC_SUFFIXES if word.endswith(s) and len(word) > len(s)), word)
|
||||
core = _compact(core)
|
||||
if len(core) < _MIN_CORE_LEN or core not in evidence:
|
||||
return False
|
||||
specific = True
|
||||
return specific
|
||||
|
||||
|
||||
def _is_question(item: dict) -> bool:
|
||||
canonical = _text(item.get("canonical"))
|
||||
return item.get("category") == "질문형" or "?" in canonical or canonical.endswith(("요", "까"))
|
||||
|
||||
|
||||
def _usable(item, evidence: str) -> str | None:
|
||||
"""메타 태그에 실어도 되는 추천이면 그 표기를, 아니면 None."""
|
||||
if not isinstance(item, dict) or item.get("status") != "ok" or _is_question(item):
|
||||
return None
|
||||
canonical = _text(item.get("canonical"))
|
||||
return canonical if canonical and _supported(canonical, evidence) else None
|
||||
|
||||
|
||||
def _title_keyword(result: dict, evidence: str, locality: str) -> str | None:
|
||||
"""제목 업종어 자리에 넣을 대표 키워드 — 유형 레인에서 고른다.
|
||||
|
||||
★ SiteOntology 설계상 "한 페이지의 주력 키워드는 1개, 유형 레인 1위가 메인 페이지 주력" 이다.
|
||||
다만 1위가 `군산 펜션 독채`(시설) 이고 2위가 `군산 독채펜션`(코어) 인 식으로 오므로 코어를 앞에 둔다.
|
||||
★ 시·군 이름을 품어야 한다. `독채펜션` 만 남으면 지금 제목(`… 군산시 숙소`)보다 지역 신호가 약해진다."""
|
||||
lane = next(
|
||||
(l for l in result.get("byLane") or [] if isinstance(l, dict) and l.get("key") == "type"),
|
||||
{},
|
||||
)
|
||||
items = [i for i in lane.get("items") or [] if isinstance(i, dict)]
|
||||
for item in sorted(items, key=lambda i: i.get("category") != "코어"):
|
||||
canonical = _usable(item, evidence)
|
||||
if not canonical or _TITLE_BLOCKED_WORDS.intersection(canonical.split()):
|
||||
continue
|
||||
if locality and locality not in canonical:
|
||||
continue
|
||||
return canonical
|
||||
return None
|
||||
|
||||
|
||||
def select(result: dict, merchant: dict) -> dict:
|
||||
"""/v1/match 응답 → {keywords, titleKeyword?}. 순위는 SiteOntology 의 융합 순위를 그대로 따른다."""
|
||||
evidence = _evidence(merchant)
|
||||
keywords: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in result.get("matches") or []:
|
||||
canonical = _usable(item, evidence)
|
||||
if not canonical or _compact(canonical) in seen:
|
||||
continue
|
||||
seen.add(_compact(canonical))
|
||||
keywords.append(canonical)
|
||||
if len(keywords) >= MAX_KEYWORDS:
|
||||
break
|
||||
|
||||
seo: dict = {"keywords": keywords}
|
||||
title = _title_keyword(result, evidence, _locality_word((merchant.get("profile") or {}).get("address")))
|
||||
if title:
|
||||
seo["titleKeyword"] = title
|
||||
return seo
|
||||
|
||||
|
||||
async def fetch(place_id: str, snapshot: dict) -> dict | None:
|
||||
"""스냅샷에 실을 seo 값. 못 만들면 None — 예외를 올리지 않는다(키워드는 발행을 막지 않는다)."""
|
||||
if not site_ontology.is_configured():
|
||||
return None
|
||||
merchant = build_merchant(place_id, snapshot)
|
||||
if merchant is None:
|
||||
return None
|
||||
try:
|
||||
result = await site_ontology.match_for_merchant(merchant)
|
||||
except site_ontology.SiteOntologyError as ex:
|
||||
LOG.w(f"[seo] place={place_id} SiteOntology 실패 — 키워드 없이 발행: {ex}")
|
||||
return None
|
||||
|
||||
seo = select(result, merchant)
|
||||
LOG.i(
|
||||
f"[seo] place={place_id} 추천 {len(result.get('matches') or [])}건 → 메타 {len(seo['keywords'])}건"
|
||||
f" · 제목 {seo.get('titleKeyword') or '(기존 제목)'}"
|
||||
)
|
||||
if not seo["keywords"] and "titleKeyword" not in seo:
|
||||
return None
|
||||
return seo
|
||||
@@ -37,8 +37,11 @@ class ShowcaseService:
|
||||
# ★ 주소 규칙은 site_payload 한 곳뿐이다 — 여기서 다시 만들면
|
||||
# 카드가 가리키는 곳과 실제 발행 주소가 갈린다(CLAUDE.md '슬러그 규칙은 두 곳').
|
||||
url=f"/s/{site_payload.publish_slug(place, site)}",
|
||||
thumbnail_url=site.thumbnail_url,
|
||||
# ★ sites.thumbnail_url 은 Azure 썸네일 저장소가 꺼져 있으면(로컬 개발 등) 비어
|
||||
# 있다 — 이 목록은 이미 PUBLISHED 만 걷었으므로, 그때는 빌더가 쓰는 대표 사진
|
||||
# (primary_photo_url)으로 대신 채운다(services/site_service._my_site_row 와 같은 규칙).
|
||||
thumbnail_url=site.thumbnail_url or primary_photo_url,
|
||||
)
|
||||
for site, place in rows
|
||||
for site, place, primary_photo_url in rows
|
||||
]
|
||||
return res
|
||||
@@ -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,13 +32,21 @@ 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
|
||||
from services.weather_notes import weather_notes
|
||||
|
||||
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
# 출력 디렉토리. 컨테이너 밖(볼륨·오브젝트 스토리지)으로 빼기 쉬우라고 env 로 둔다.
|
||||
# ★ 기본값이 `solution/site/payloads` 아래인 이유 — 렌더러(prerender.ts)가 songs·out 디렉토리를
|
||||
# **자기 파일 위치 기준 상대경로**로 찾는다(SITE_ROOT = dist/prerender/../..). 워커가 그
|
||||
# 렌더러를 subprocess 로 직접 띄우면서(render_service.py) 세 디렉토리(payloads·songs·out)가
|
||||
# 그 렌더러가 실제로 설치된 자리(`/app/solution/site/`) 아래에 나란히 있어야 한다 —
|
||||
# 어긋나면 워커는 payload 를 잘 쓰는데 렌더러는 다른 곳에서 songs 를 찾다가 못 찾는다.
|
||||
PAYLOAD_DIR_ENV = "SITE_PAYLOAD_DIR"
|
||||
DEFAULT_PAYLOAD_DIR = "/app/out/payloads"
|
||||
DEFAULT_PAYLOAD_DIR = "/app/solution/site/payloads"
|
||||
|
||||
# 커스텀 도메인이 없을 때 쓰는 기본 호스트. sites.domain 이 채워지면 그 값이 이긴다.
|
||||
#
|
||||
@@ -137,7 +146,7 @@ _DEFAULT_THEME = {
|
||||
# 수집이 다 됐어도 그 섹션이 아예 안 나온다 — 저장값이 없는 사업장에는 이 표가 곧 발행본이다.
|
||||
# ★ "이용 규정"은 뺐다 (2026-09-09) — 발행본에 그 섹션이 없다. 체크인·취소·취사·
|
||||
# 반려동물 줄은 기본 정보 안에서 규정 덩이로 묶여 나간다(EssentialInfoSection).
|
||||
# ★ 가요·일력·인물·연표·엽서는 여기 넣지 않는다. 이 표의 항목은 전부 켜서 나가는데
|
||||
# ★ 가요·일력·인물·연표·읽기·엽서는 여기 넣지 않는다. 이 표의 항목은 전부 켜서 나가는데
|
||||
# (`_sections`), 그것들은 '지역 이야기'(story) 탭 **안에서** 그려지는 것이라
|
||||
# 켜면 탭 밖에 한 번 더 선다. story 하나만 두면 데이터가 있는 것만 탭이 된다.
|
||||
# ★ 퀴즈(quiz)도 넣지 않지만 사정이 다르다 — 탭이 아니라 **독립 섹션**이라
|
||||
@@ -521,7 +530,7 @@ def _weather(row: dict):
|
||||
return {
|
||||
"temperature": temperature,
|
||||
"condition": _weather_condition(body.get("weather_code")),
|
||||
# note 는 LLM 이 쓰는 안내 문구다. 지금 그걸 만드는 경로가 없으므로 넣지 않는다(지어내지 않는다).
|
||||
**weather_notes(),
|
||||
"observedAt": observed_at,
|
||||
}
|
||||
|
||||
@@ -615,6 +624,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
|
||||
|
||||
@@ -778,11 +791,15 @@ def region_label(*addresses: str | None) -> str | None:
|
||||
|
||||
|
||||
# ── payload 조립 ──────────────────────────────────────────────────────────
|
||||
def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
def to_site_payload(place, snapshot: dict, site, version, links, publish: bool = False) -> dict:
|
||||
"""스냅샷 + 사이트/버전 행 + 채널 링크 → SitePayload(dict).
|
||||
|
||||
순수 변환 함수다. DB 도 파일도 건드리지 않는다 — 그래야 테스트가 쉽고,
|
||||
같은 입력이면 언제나 같은 payload 가 나온다."""
|
||||
같은 입력이면 언제나 같은 payload 가 나온다.
|
||||
|
||||
★ `publish` 는 렌더러(prerender.ts publishVersion)에게 "이 버전으로 공개 주소를
|
||||
넘겨도 되는가"를 알리는 신호다. False(미리보기·게이트 통과 전 재빌드)면 렌더러가
|
||||
`out/versions/<slug>/<version>/` 에만 굽고 `out/s/<slug>` 심볼릭 링크는 그대로 둔다."""
|
||||
snapshot = snapshot or {}
|
||||
snap_place = snapshot.get("place") or {}
|
||||
place_id = str(_get(place, "place_id"))
|
||||
@@ -869,6 +886,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 {}),
|
||||
})
|
||||
|
||||
# ── 소개문 ───────────────────────────────────────────
|
||||
@@ -923,6 +944,7 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
"publishedAt": published_at or updated_at,
|
||||
"updatedAt": updated_at,
|
||||
"version": int(_get(version, "version") or 1),
|
||||
"publish": bool(publish),
|
||||
},
|
||||
"place": {
|
||||
"name": name,
|
||||
@@ -983,9 +1005,26 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
for r in snapshot.get("social_posts", [])],
|
||||
"narrative": narrative,
|
||||
"theme": theme,
|
||||
# ★ 검색 키워드(SiteOntology). 스냅샷에 있을 때만 싣는다 — 옛 스냅샷·SiteOntology 가 꺼진 빌드에는 없고,
|
||||
# 그때 렌더러는 제목·메타를 예전 그대로 굽는다(solution/site/src/seo/meta.ts).
|
||||
**_seo_entry(snapshot.get("seo")),
|
||||
}
|
||||
|
||||
|
||||
def _seo_entry(value) -> dict:
|
||||
"""스냅샷의 seo(services/seo_keywords) → payload 의 `seo`. 없으면 키 자체를 만들지 않는다.
|
||||
|
||||
★ 여기서 다시 거르지 않는다 — 이 가게 자료로 거르는 곳은 seo_keywords 한 곳이다. 모양만 확인한다.
|
||||
★ 빈 seo 를 만들지 않는다. 빈 배열은 '받았는데 비었다' 로 읽힌다(itineraries 와 같은 규칙)."""
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
keywords = [_text(k) for k in value.get("keywords") or [] if _text(k)]
|
||||
title = _text(value.get("titleKeyword"))
|
||||
if not keywords and not title:
|
||||
return {}
|
||||
return {"seo": {"keywords": keywords, **({"titleKeyword": title} if title else {})}}
|
||||
|
||||
|
||||
def _as_float(value):
|
||||
try:
|
||||
return float(value) if value not in (None, "") else None
|
||||
@@ -1017,14 +1056,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, publish: bool = False) -> dict:
|
||||
"""미리보기·발행 공통 보강. 요약은 DB 스냅샷이 아니라 응답/산출물에만 싣는다."""
|
||||
payload = to_site_payload(place, snapshot, site, version, links, publish)
|
||||
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, publish: bool = False) -> 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, publish)
|
||||
path = write_payload(payload)
|
||||
LOG.i(
|
||||
f"[payload] {payload['site']['slug']} → {path} "
|
||||
|
||||
@@ -29,6 +29,7 @@ from router.v1.site.protocol import (
|
||||
Req_SiteStatus,
|
||||
Req_SiteTemplate,
|
||||
Req_SiteTheme,
|
||||
Req_Rollback,
|
||||
Req_StartBuild,
|
||||
Res_MySites,
|
||||
Res_PublishLogs,
|
||||
@@ -163,11 +164,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.build_service import ensure_site, load_channel_links
|
||||
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)
|
||||
@@ -175,11 +176,11 @@ class SiteService:
|
||||
return None
|
||||
|
||||
site = await ensure_site(place_id)
|
||||
links = await _load_links(place_id)
|
||||
links = await load_channel_links(place_id)
|
||||
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 한 곳에만 있다. 확인과 저장이 그것을 같이 쓴다.
|
||||
@@ -216,10 +217,15 @@ class SiteService:
|
||||
return reason, None
|
||||
|
||||
value = (slug or "").strip()
|
||||
# ★ 주인 확인이 예약어보다 먼저다. 예약어 목록은 나중에 늘어나는데(목업 슬러그를 막는
|
||||
# 것처럼), 늘린 이름을 이미 쓰고 있던 사장님이 자기 편집 화면을 여는 순간
|
||||
# "이 주소는 못 씁니다" 가 뜬다 — 바꿀 수도 없는 주소다(발행 뒤 SITE_SLUG_LOCKED).
|
||||
owner = await self._domain_owner(value)
|
||||
if owner is not None and owner == str(uuid.UUID(place_id)):
|
||||
return None, None
|
||||
if reason is None:
|
||||
owner = await self._domain_owner(value)
|
||||
# ★ 이미 자기 주소면 쓸 수 있다 — 저장해 둔 화면을 다시 열었을 때 '중복'이라고 하면 안 된다.
|
||||
if owner is None or owner == str(uuid.UUID(place_id)):
|
||||
if owner is None:
|
||||
return None, None
|
||||
reason = site_slug.REASON_TAKEN
|
||||
return reason, await self._suggest(value)
|
||||
@@ -227,13 +233,25 @@ class SiteService:
|
||||
async def check_slug(self, user_info: UserInfo, place_id: str, slug: str) -> Res_SlugCheck:
|
||||
"""주소를 쓸 수 있는지 미리 본다.
|
||||
|
||||
★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고르고, 겹치면 고르기 전에 알려 준다."""
|
||||
★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고르고, 겹치면 고르기 전에 알려 준다.
|
||||
★ 확인과 저장은 같은 판정을 해야 한다. 발행 잠금(SITE_SLUG_LOCKED)을 여기서 안 보면
|
||||
"쓸 수 있습니다" 라고 답해 놓고 저장에서 1707 로 튕긴다 — 지금은 발행 모달이
|
||||
입력칸을 잠가 가려져 있을 뿐이고, API 를 직접 쓰는 쪽에는 그대로 드러난다."""
|
||||
res = Res_SlugCheck()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
site = await self._get_site(place_id)
|
||||
if site is not None and (site.published_at is not None or site.status == SiteStatus.PUBLISHED.value):
|
||||
if (site.domain or "") != (slug or "").strip():
|
||||
res.available = False
|
||||
res.reason = site_slug.REASON_LOCKED
|
||||
return res
|
||||
res.available = True
|
||||
return res
|
||||
|
||||
reason, suggestion = await self._judge_slug(place_id, slug)
|
||||
res.available = reason is None
|
||||
res.reason = reason
|
||||
@@ -459,14 +477,24 @@ class SiteService:
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.sites = [self._my_site_row(place, site, built_at) for place, site, built_at in rows]
|
||||
res.sites = [
|
||||
self._my_site_row(place, site, built_at, primary_photo_url)
|
||||
for place, site, built_at, primary_photo_url in rows
|
||||
]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
@staticmethod
|
||||
def _my_site_row(place, site, built_at) -> MySiteData:
|
||||
def _my_site_row(place, site, built_at, primary_photo_url) -> MySiteData:
|
||||
# ★ 재빌드 판별은 단건(get_site)과 같은 규칙이어야 한다 — 다르면 목록과 에디터가 다른 답을 한다.
|
||||
changed = place.content_updated_at
|
||||
# ★ sites.thumbnail_url 은 발행할 때 Azure 에 대표 사진을 재호스팅해야 채워진다
|
||||
# (services/site_thumbnail.store) — 저장소가 안 꺼져 있으면(로컬 개발 등) 늘 비어 있다.
|
||||
# 그래도 "한 번이라도 발행한 줄은 그림"이라는 화면 규칙은 지켜야 하므로, 빌더가 이미
|
||||
# 쓰고 있는 대표 사진(place_photos, primary_photo_url)으로 대신 채운다 — 발행 전 줄에는
|
||||
# 쓰지 않는다(그 규칙은 published_at 유무로 가른다: crud.site_crud.list_owner_sites).
|
||||
ever_published = site is not None and getattr(site, "published_at", None) is not None
|
||||
thumbnail_url = getattr(site, "thumbnail_url", None) or (primary_photo_url if ever_published else None)
|
||||
return MySiteData(
|
||||
place_id=place.place_id,
|
||||
name=place.name,
|
||||
@@ -479,7 +507,7 @@ class SiteService:
|
||||
domain=getattr(site, "domain", None),
|
||||
template_id=getattr(site, "template_id", None),
|
||||
published_at=getattr(site, "published_at", None),
|
||||
thumbnail_url=getattr(site, "thumbnail_url", None),
|
||||
thumbnail_url=thumbnail_url,
|
||||
needs_rebuild=bool(site is not None and changed and (built_at is None or changed > built_at)),
|
||||
)
|
||||
|
||||
@@ -549,6 +577,26 @@ class SiteService:
|
||||
res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED)
|
||||
return res
|
||||
|
||||
# ★ publish=False 는 **이미 나가 있는 사이트를 다시 굽는** 경로다. 한 번도 발행한 적
|
||||
# 없는 사업장에는 쓸 수 없다.
|
||||
# 왜 막나 — 빌드는 게이트를 판정하려고 payload 를 디스크에 쓰고, 프리렌더는 거기
|
||||
# 생긴 것을 곧바로 공개 페이지로 굽는다(sitemap · llms.txt · /s 목록 포함).
|
||||
# 그래서 publish=False 인데도 페이지가 공개됐고, DB 는 DRAFT·published_at=NULL 이라
|
||||
# 빌더 화면은 "발행 전" 으로 보였다. 2차 게이트(고유 콘텐츠 · JSON-LD)는 구운 결과를
|
||||
# 봐야 판정하므로 **거부돼도 페이지는 이미 나가 있었다**(실측 2026-09-15).
|
||||
# 발행 전에 보고 싶은 것은 `GET /site/preview` 가 준다 — 그쪽은 디스크를 건드리지 않는다.
|
||||
site = await self._get_site(place_id)
|
||||
if not req.publish:
|
||||
if site is None or site.published_at is None:
|
||||
res.result.SetResult(ErrorType.SITE_VERSION_NOT_FOUND)
|
||||
return res
|
||||
|
||||
# ★ 주소를 안 골랐어도 막지 않는다. 그때 쓰는 임시 슬러그(`slugify(상호명)-place_id[:8]`)에
|
||||
# 한글이 남는 것은 실수가 아니라 결정이다 — 음차하면 같은 가게가 두 주소를 갖는다
|
||||
# (`site_payload.slugify` 주석). 사람이 고르는 주소만 영문으로 제한한다.
|
||||
# 발행 모달은 주소를 먼저 받게 되어 있고(PublishModal), API 로 건너뛰면 임시 주소로
|
||||
# 나간 뒤 SITE_SLUG_LOCKED 로 잠긴다는 점은 그대로다.
|
||||
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.BUILD,
|
||||
{
|
||||
@@ -570,6 +618,35 @@ class SiteService:
|
||||
res.created = created
|
||||
return res
|
||||
|
||||
async def start_rollback(self, user_info: UserInfo, place_id: str, req: Req_Rollback) -> Res_StartBuild:
|
||||
"""예전 버전으로 공개 주소를 되돌리는 잡을 큐에 넣는다.
|
||||
|
||||
★ dedupe_key 를 빌드와 **같은 것**(`build:{place_id}`)을 쓴다 — 롤백 도중에 새 발행이
|
||||
끼어들거나 그 반대가 되면 어느 쪽이 이겼는지 알 수 없는 상태가 된다. 이 사이트의
|
||||
공개 주소를 바꾸는 작업은 항상 하나만 활성화된다."""
|
||||
res = Res_StartBuild()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.ROLLBACK,
|
||||
{
|
||||
"place_id": place_id, "owner_user_id": user_info.user_id,
|
||||
"target_version": req.target_version, "requested_by": user_info.user_id,
|
||||
},
|
||||
dedupe_key=f"build:{place_id}",
|
||||
)
|
||||
if job_id is None:
|
||||
res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING)
|
||||
return res
|
||||
|
||||
res.job_id = uuid.UUID(job_id)
|
||||
res.status = JobStatus.PENDING
|
||||
res.created = created
|
||||
return res
|
||||
|
||||
async def list_versions(self, user_info: UserInfo, place_id: str) -> Res_SiteVersions:
|
||||
from sqlalchemy import select
|
||||
|
||||
|
||||
@@ -48,6 +48,14 @@ RESERVED_SLUGS = frozenset({
|
||||
"search", "index", "home", "main", "new", "edit", "delete", "create", "update",
|
||||
# 값이 비었을 때 프론트가 문자열로 흘려보내는 것들 — 주소로 들어오면 버그의 흔적이다
|
||||
"null", "undefined", "none", "nan", "true", "false",
|
||||
# ★ 손으로 만든 목업이 쓰는 주소(solution/site/out/s, mockup/README).
|
||||
# payload 가 없어 프리렌더가 굽지 않는 자리인데, 사장님이 이 주소로 발행하면
|
||||
# **payload 가 생기는 순간** 덮여서 유일본이 영영 사라진다(AGENTS.md ★★ 항목).
|
||||
# 실측(2026-09-15): `stay` 는 주인이 있어 우연히 TAKEN 이었을 뿐이고
|
||||
# `stay2` · `stay3` 는 주인도 예약도 없어 "쓸 수 있다" 로 나갔다.
|
||||
# ★ 굽기 쪽 보호(prerender PROTECTED_SLUGS)와 겹쳐 두는 것이지 대신하는 게 아니다 —
|
||||
# 저쪽은 이미 나간 발행을 막고, 여기는 애초에 고르지 못하게 한다.
|
||||
"stay", "stay2", "stay3",
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -260,7 +261,7 @@ async def _local_contents(place) -> dict:
|
||||
.order_by(area_contents.content_type.asc(), area_contents.collected_at.desc())
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
|
||||
area_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query, raise_error=False)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
|
||||
@@ -285,7 +286,7 @@ async def _local_contents(place) -> dict:
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(s, shared_q),
|
||||
lambda s: DB_SESSION_MNG.execute(s, shared_q, raise_error=False),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
|
||||
@@ -361,7 +362,7 @@ async def _site_places(place_id) -> dict:
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
site_sections.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, q)
|
||||
site_sections.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, q, raise_error=False)
|
||||
)
|
||||
if err != ErrorType.SUCCESS or not rows:
|
||||
return {}
|
||||
@@ -370,14 +371,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 {}
|
||||
@@ -413,9 +415,16 @@ def _iso(value) -> str | None:
|
||||
|
||||
|
||||
async def _select(query) -> list:
|
||||
"""조회 실패는 **빈 목록**이다 — 미리보기·발행이 조각 하나 때문에 통째로 죽지 않게.
|
||||
|
||||
★ raise_error=False 가 핵심이다 (2026-09-14). 이 함수는 원래 실패를 [] 로 삼키도록
|
||||
썼는데, DB 계층이 기본값 raise_error=True 로 **예외를 던져** 그 처리가 실행될 기회조차
|
||||
없었다. 실측: place_songs 테이블이 없던 동안 미리보기가 통째로 HTTP 500 이었다 —
|
||||
노래 한 칸이 빠진 화면 대신 아무것도 못 보는 화면이 나갔다.
|
||||
"""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_facts.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(s, query),
|
||||
lambda s: DB_SESSION_MNG.execute(s, query, raise_error=False),
|
||||
)
|
||||
return list(rows) if err == ErrorType.SUCCESS else []
|
||||
@@ -19,7 +19,7 @@ from common.database.model.models import (
|
||||
place_facts,
|
||||
owner_social_accounts as Account,
|
||||
)
|
||||
from common.enums import SiteStatus, ErrorType, PUBLISHABLE_FACT_STATUSES
|
||||
from common.enums import SiteStatus, ErrorType, JobType, PUBLISHABLE_FACT_STATUSES
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud import social_crud as db
|
||||
from services import site_payload, social_account_service as accounts
|
||||
@@ -224,7 +224,7 @@ async def create_draft(user_id, place_id, provider=2):
|
||||
await s.flush()
|
||||
row_id = row.post_id
|
||||
if row_id:
|
||||
await db.enqueue(s, row.post_id, 8)
|
||||
await db.enqueue(s, row.post_id, JobType.SOCIAL_DRAFT.value)
|
||||
return public_post(row)
|
||||
|
||||
return await db.transaction(run)
|
||||
|
||||
@@ -54,6 +54,7 @@ from crud.song_crud import SongCRUD
|
||||
from services import place_research, site_payload
|
||||
from services.external import gemini_text, suno
|
||||
from services.llm.gemini import GeminiError, GeminiInvalidOutput, GeminiNotConfigured
|
||||
from common.job_errors import PermanentJobError
|
||||
|
||||
_fact_crud = FactCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
@@ -65,7 +66,7 @@ _song_crud = SongCRUD()
|
||||
SONGS_DIRNAME = "songs"
|
||||
|
||||
|
||||
class SongAborted(RuntimeError):
|
||||
class SongAborted(PermanentJobError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남아 운영자가 본다."""
|
||||
|
||||
|
||||
@@ -128,12 +129,21 @@ async def run_song(job: dict) -> dict:
|
||||
|
||||
발행 경로는 이 잡을 거치지 않고 `ensure_song` 을 직접 부른다(build_service)."""
|
||||
payload = job["payload"]
|
||||
return await ensure_song(payload["place_id"], payload["owner_user_id"])
|
||||
# ★ 이 잡은 "다시 만들어 달라" 는 요청이다 — 기존 곡이 있어도 만든다(ensure_song 주석).
|
||||
return await ensure_song(payload["place_id"], payload["owner_user_id"], force=True)
|
||||
|
||||
|
||||
async def ensure_song(place_id: str, owner_user_id: str) -> dict:
|
||||
async def ensure_song(place_id: str, owner_user_id: str, *, force: bool = False) -> dict:
|
||||
"""이 업장의 노래를 한 곡 만든다. 돌려주는 dict 가 곧 잡 결과이자 빌드 로그다.
|
||||
|
||||
★ **이미 완성된 곡이 있으면 만들지 않는다**(2026-09-15 대표: "재발행할 때 노래 다시
|
||||
생성하면 안 되거든"). 예전에는 `build_service` 가 `publish=True` 마다 이 함수를 불렀고
|
||||
여기에 가드가 없어서, 내용이 하나도 안 바뀐 재발행에도 **Gemini 가사 1회 + Suno 작곡
|
||||
1회**가 그대로 나갔다. 사장님이 발행을 다섯 번 누르면 유료 호출 다섯 번에
|
||||
`place_songs` 행이 다섯 개다. 화면은 최신 READY 한 곡만 쓰므로(`SongCRUD.latest_ready`)
|
||||
나머지는 값을 만들지 않고 돈만 쓴다.
|
||||
★ 곡을 **일부러 다시 만드는 길은 남긴다** — `force=True`. 그 길은 발행이 아니라
|
||||
SONG 잡(`run_song`)이고, 사람이 눌러야 돈다.
|
||||
★ 실패를 예외로 올리지 않는다(사업장을 못 찾는 것 같은 진짜 고장만 예외다).
|
||||
발행이 이 함수를 기다리는데 여기서 예외가 나면 **노래 때문에 발행이 통째로 실패**한다.
|
||||
음악 API 가 느린 날 사장님 사이트가 안 나가는 것은 맞바꿀 수 없는 손해다."""
|
||||
@@ -142,6 +152,17 @@ async def ensure_song(place_id: str, owner_user_id: str) -> dict:
|
||||
LOG.i(f"[song] place={place_id} 건너뜀 — SUNO_API_KEY 미설정")
|
||||
return {"place_id": place_id, "skipped": "SUNO_API_KEY 미설정"}
|
||||
|
||||
if not force:
|
||||
err, ready = await DB_SESSION_MNG.execute_lambda(
|
||||
place_songs.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _song_crud.latest_ready(s, uuid.UUID(place_id)),
|
||||
)
|
||||
# `execute()` 는 리스트를 준다(limit 1 이라 0개 아니면 1개다) — None 비교로 보지 않는다.
|
||||
if err == ErrorType.SUCCESS and ready:
|
||||
LOG.i(f"[song] place={place_id} 건너뜀 — 이미 곡이 있다(재발행은 다시 만들지 않는다)")
|
||||
return {"place_id": place_id, "skipped": "이미 곡이 있다"}
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
|
||||
@@ -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, 전북 군산시)에서
|
||||
@@ -63,7 +64,7 @@ async def _generate_kind(client: httpx.AsyncClient, kind: str, region_label: str
|
||||
{"role": "system", "content": prompts.SYSTEM_PROMPT},
|
||||
{"role": "user", "content": prompts.build_prompt(kind, region_label)},
|
||||
],
|
||||
"max_tokens": perplexity.DEFAULT_MAX_TOKENS,
|
||||
"max_tokens": _MAX_TOKENS.get(kind, perplexity.DEFAULT_MAX_TOKENS),
|
||||
}
|
||||
try:
|
||||
payload = await perplexity.call(body, client=client)
|
||||
@@ -73,12 +74,21 @@ async def _generate_kind(client: httpx.AsyncClient, kind: str, region_label: str
|
||||
LOG.w(f"[story] {kind} 호출 실패 region={region_label}: {ex}")
|
||||
return [], [f"호출 실패: {ex}"]
|
||||
|
||||
items, dropped = grounding.parse_items(payload, kind, prompts.max_items(kind))
|
||||
items, dropped = grounding.parse_items(payload, kind, prompts.max_items(kind), region_label)
|
||||
items = await _attach_images(kind, items, region_label)
|
||||
LOG.i(f"[story] {region_label} {kind}: {len(items)}건 채택, {len(dropped)}건 버림")
|
||||
return items, dropped
|
||||
|
||||
|
||||
# 종류별 응답 토큰 상한. 기본(2048)으로 모자란 종류만 적는다.
|
||||
#
|
||||
# ★ 왜 (실측 2026-09-15) `reading` 은 30~34꼭지 × 서너 문장이라 다른 종류의 서너 배다.
|
||||
# 2048 로 부르면 응답이 **문장 한가운데서 잘려** 오고, 파서는 그걸 "JSON 이 아니다" 로
|
||||
# 통째로 버린다 — 여섯 지역 전부 0건이었다. 잘린 것은 재시도해도 같은 자리에서 잘린다.
|
||||
# ★ 상한만 올린다. 꼭지 수를 줄이면 화면이 매번 5~6개만 뽑는 의미가 없어진다
|
||||
# (`site/sections/items/ReadingSection.tsx`).
|
||||
_MAX_TOKENS = {"reading": 8000}
|
||||
|
||||
# 사진을 무엇으로 찾을지. 종류마다 출처가 다르다.
|
||||
#
|
||||
# chronicle · postcard 공공데이터(TourAPI) — 장소·시설 사진. 공공누리 Type1/Type3 만
|
||||
@@ -278,6 +288,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 로 막는다.
|
||||
|
||||
@@ -18,12 +18,13 @@ from config.server_configs import external_api_config
|
||||
from crud.media_crud import MediaCRUD
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from services.external import gemini
|
||||
from common.job_errors import PermanentJobError
|
||||
|
||||
_media_crud = MediaCRUD()
|
||||
_place_crud = PlaceCRUD()
|
||||
|
||||
|
||||
class VisionAborted(RuntimeError):
|
||||
class VisionAborted(PermanentJobError):
|
||||
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"sky": {
|
||||
"맑음": ["맑은 날에는 잠깐 쉬어 가며 오늘 담은 사진을 골라 보세요.", "분주했던 걸음을 멈추고 느긋하게 쉬어 가도 좋겠습니다.", "오늘 기억하고 싶은 장면을 한 줄 남겨 보세요.", "다음 일정을 서두르기보다 잠시 여유를 가져 보세요.", "좋아하는 책 몇 장을 넘기며 쉬어 가는 건 어떨까요?"],
|
||||
"구름많음": ["구름이 많은 날에는 실내에서 다음 일정을 천천히 골라 보세요.", "여행 사진을 정리하며 잠깐 쉬어 가세요.", "함께 온 사람과 오늘 가장 좋았던 순간을 이야기해 보세요.", "바깥 일정 사이에 여유로운 휴식 시간을 넣어 보세요.", "오늘의 기분을 짧은 글로 남겨도 좋겠습니다."],
|
||||
"흐림": ["흐린 날에는 실내에서 느긋하게 쉬어 가도 좋겠습니다.", "잠깐 책을 읽으며 다음 일정을 기다려 보세요.", "바깥 풍경 대신 오늘 나눈 이야기에 집중해 보세요.", "천천히 쉬면서 돌아갈 때 가져갈 추억을 골라 보세요.", "분주한 일정 사이에 조용한 휴식을 끼워 넣어 보세요."],
|
||||
"비": ["비가 오는 동안에는 실내에서 쉬며 일정을 조정해 보세요.", "서두르지 말고 비가 잦아드는지 확인한 뒤 움직이세요.", "빗소리를 들으며 읽고 싶었던 글을 펼쳐 보세요.", "젖은 물건을 정리하고 잠깐 쉬어 가세요.", "바깥 일정 대신 함께 찍은 사진을 나눠 봐도 좋겠습니다."],
|
||||
"눈": ["눈 오는 날에는 실내에서 쉬며 바깥 상황을 살펴보세요.", "다음 이동을 서두르지 말고 쉬어 가세요.", "따뜻하게 머물며 오늘의 여행을 한 줄 남겨 보세요.", "실내에서 다음 일정과 이동편을 확인해 보세요.", "눈길을 나서기 전에는 여유 있게 준비하세요."]
|
||||
},
|
||||
"temperature": {
|
||||
"혹서": ["더위가 강한 시간에는 바깥 이동을 줄이고 실내 위주로 일정을 잡아 보세요.", "한낮 산책은 짧게 하고 충분히 쉬어 가세요.", "외출 전 기상특보와 방문할 곳의 운영 여부를 확인하세요.", "다음 장소로 이동할 때에는 쉴 시간을 넉넉히 두세요.", "긴 야외 일정은 미루고 가까운 동선부터 살펴보세요."],
|
||||
"더움": ["바깥 일정 사이에 실내에서 쉬는 시간을 넣어 보세요.", "외출할 때에는 물을 챙기고 무리한 이동은 줄이세요.", "주변을 둘러보더라도 한 번에 오래 걷지는 마세요.", "방문할 곳의 운영 시간을 먼저 확인하고 이동하세요.", "더위가 느껴지면 일정을 줄이고 쉬어 가세요."],
|
||||
"선선": ["비나 눈이 없다면 주변을 가볍게 둘러보는 건 어떨까요?", "날씨와 이동 경로를 확인하고 짧은 산책을 계획해 보세요.", "바깥 일정을 잡기 전에 방문할 곳의 운영 여부를 확인하세요.", "편한 신발을 챙기고 자신의 속도로 동네를 둘러보세요.", "비가 오지 않는다면 일정 사이에 잠깐 걸어 보세요."],
|
||||
"쌀쌀": ["외출할 때에는 걸칠 옷을 챙겨 보세요.", "바깥에 오래 머물기보다 쉬어 갈 곳을 함께 정해 두세요.", "일교차에 대비해 옷차림을 조절하세요.", "이동 경로를 짧게 잡고 실내 일정도 함께 살펴보세요.", "돌아오는 시간의 기온도 확인한 뒤 외출하세요."],
|
||||
"추움": ["따뜻한 옷을 챙기고 바깥 이동은 짧게 잡아 보세요.", "찬 바람을 피할 수 있는 실내 일정을 살펴보세요.", "출발 전 눈이나 결빙으로 이동이 어려운 곳은 없는지 확인하세요.", "야외에 오래 머무르지 않도록 쉬는 시간을 충분히 두세요.", "방문할 곳의 운영 여부를 확인하고 따뜻하게 준비하세요."]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"""날씨 안내 계약. 관측값과 분리하고, 확인되지 않은 시설·영업시간은 쓰지 않는다."""
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _templates() -> dict:
|
||||
return json.loads(Path(__file__).with_name("weather_notes.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def weather_notes() -> dict:
|
||||
templates = _templates()
|
||||
sky = {key: list(lines) for key, lines in templates["sky"].items()}
|
||||
temperature = {key: list(lines) for key, lines in templates["temperature"].items()}
|
||||
return {
|
||||
"notes": {key: lines[0] for key, lines in sky.items()},
|
||||
"tempNotes": {key: lines[0] for key, lines in temperature.items()},
|
||||
"noteSets": sky,
|
||||
"tempNoteSets": temperature,
|
||||
}
|
||||
Reference in new issue
Block a user