[feat] solution,postgres-init: 지역 이야기를 서버가 채운다 · 공용과 개인화를 이름으로 가른다
가요·인물·연표·엽서·퀴즈는 생성기가 없어 **사람이 손으로 넣지 않으면 영영 빈칸**이었다.
`/s/stay` 시안이 다섯을 다 갖고 있는 건 그때 손으로 채웠기 때문이고, 새 업장은 옛 항구
템플릿을 골라도 그 자리가 비었다. 실측(2026-09-09, 전북 군산시): 생성 54건 · 62초 · 버린 항목 0.
**생성**
- Perplexity 종류당 1회, 지역당 1세트. 순차로 돈다 — 동시에 다섯을 띄웠더니 둘이 HTTP 429 였다
(같은 키라 한 지역이 자기를 막는다). 순차도 건당 9~15초다. 타임아웃 240s — 가요 다방이
기본 90s 를 넘겼다(후보를 넓게 훑는 프롬프트다).
- 출처 없는 항목은 버린다. 항목 자신의 출처가 없어 검색 출처로 때운 것은 모델이 "확인" 이라
우겨도 "확인필요" 로 내린다. 항목 **모양은 검사하지 않는다** — shared 계약을 파이썬에
한 벌 더 적으면 필드가 는 날 서버가 조용히 떨어뜨린다.
- 프롬프트는 한 벌이다(`shared/section-prompts.ts`). 사장님이 [콘텐츠] 탭에서 복사해 가던
그 문장을 서버도 그대로 쓴다. `npm run export:prompts` 가 백엔드용 JSON 으로 뽑는다(커밋).
- 트리거는 수집 완료 직후다. 전에는 에디터 캔버스가 주변정보를 처음 부를 때 시작해서
사장님이 처음 보는 화면이 **늘 절반만 그려진 상태**였다.
**자리 가르기**
area_* = 공용. 지역 단위, 여러 사이트가 나눠 쓴다 → 렌더러 모양 그대로.
site_sections = 개인화 싸그리. 사이트마다 달라지는 것 전부(거리·숨김·순서·편집).
- `area_contents.body` 가 TourAPI 원문 이름이라 빌드마다 렌더러 이름으로 바꿔 실었다 —
같은 변환을 발행할 때마다 다시 하는 셈이었다. 수집 시점에 바꿔 넣는다.
- 거리·숨김은 사이트마다 다르니 `site_sections('local').data.places` 맵으로. **맵이지
배열이 아니다** — 화면에 순서대로 서는 항목이 아니라 ref → 값 조회표다. 정렬 기준은
읽는 쪽이 갖는다.
- ★ 유일 인덱스 함정 둘. `uq_local_contents_single` 이 kind 를 안 봐서 이야기 다섯 중
**첫 종류만 저장되고 잡은 "성공" 으로 끝났고**, backfill 때는 인덱스를 먼저 떼지 않으면
UPDATE 가 통째로 막힌다(`(gunsan, festival) already exists`). 둘 다 조용히 틀리는 종류다.
- 검수 게이트는 두지 않는다(사장님이 에디터에서 뺀다). 근거는 DECISIONS.md 6절.
검증: 지역 이야기 단위 테스트 12건 통과 · 군산 실행 후 payload.local.story 에
songs 8 · people 10 · chronicle 12 · postcard 12 · quiz 12.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
64ce467f21
commit
c4af53613e
27 files changed
+1502
-190
No files matched your search
@@ -22,7 +22,10 @@ from sqlalchemy import or_, select
|
||||
|
||||
from common.category_schema import get_schema
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import place_facts, place_faqs, area_contents, place_photos, place_area_refs, place_units
|
||||
from common.database.model.models import (
|
||||
place_facts, place_faqs, area_contents, place_photos, place_area_refs, place_units,
|
||||
site_sections, sites,
|
||||
)
|
||||
from common.enums import (
|
||||
PUBLISHABLE_FACT_STATUSES,
|
||||
DBWRType,
|
||||
@@ -44,6 +47,9 @@ _PUBLISHABLE = tuple(s.value for s in PUBLISHABLE_FACT_STATUSES)
|
||||
# 두 캐시(지역 수기 항목 + 업장 반경)를 **합쳐서** 센다 — 따로 세면 최대 40건이 나간다.
|
||||
_LOCAL_MAX_PER_TYPE = 20
|
||||
|
||||
# ★ 지역 이야기는 종류당 **한 행**이다(항목은 body.items 안에 있다 — migrations/0004
|
||||
# `uq_local_contents_kind`). 그래서 다섯 종류가 위 상한 안에서 나란히 선다.
|
||||
|
||||
# 지역 원문(body)에서 스냅샷으로 옮기지 않는 키.
|
||||
# ★ TourAPI 원본을 통째로 담은 필드라 정규화된 값과 100% 중복이고, 축제 1건의 크기를 두 배로 만든다.
|
||||
# site_payload 는 정규화된 키만 읽는다.
|
||||
@@ -208,6 +214,11 @@ async def _local_contents(place) -> dict:
|
||||
.where(
|
||||
area_contents.region_code == region_code,
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
# ★ **지역 단위 항목만** 본다 — 날씨와 지역 이야기다(external_id 없이 지역에 한 벌).
|
||||
# 관광지·맛집·축제는 같은 표에 있지만 업장마다 거리가 달라, 아래 사이트 쪽에서
|
||||
# 개인화 값과 함께 읽는다. 여기서 같이 긁으면 거리 없는 항목이 먼저 들어와
|
||||
# 종류별 상한을 채워 버린다(실측 2026-09-09: 주변 12건이 전부 거리 없이 나갔다).
|
||||
area_contents.external_id.is_(None),
|
||||
area_contents.status == LocalContentStatus.PUBLISHED.value,
|
||||
or_(area_contents.display_start_at.is_(None), area_contents.display_start_at <= now),
|
||||
or_(area_contents.display_end_at.is_(None), area_contents.display_end_at > now),
|
||||
@@ -223,70 +234,122 @@ async def _local_contents(place) -> dict:
|
||||
rows = []
|
||||
contents += _local_rows(rows or [], seen)
|
||||
|
||||
# ── 업장 반경 캐시(place_area_refs): 맛집·관광지·축제·여행코스 ──
|
||||
# ★ 정렬은 **사진 있는 것 우선 → 가까운 순**(2026-09-07 결정). 종류별 상한 안에 들려면
|
||||
# 사진 없는 가까운 곳보다 사진 있는 조금 먼 곳이 이긴다 — 화면이 카드라 사진이 없으면 자리가 빈다.
|
||||
# ── 업장 주변: 공용 실체(area_contents) × 사이트 개인화(site_sections) ──
|
||||
# ★ 2026-09-09 에 자리를 갈랐다. 공용 실체는 지역이 나눠 쓰고(거리를 담을 수 없다),
|
||||
# 거리·숨김은 사이트마다 다르다. 그래서 관계 테이블이 아니라 **사이트 섹션**에서 읽는다.
|
||||
# 정렬은 여기가 한다 — 사진 있는 것 먼저, 그다음 가까운 순(2026-09-07 결정).
|
||||
# 저장 쪽에 정렬을 구워 두면 기준이 바뀔 때 전 사이트를 다시 써야 한다.
|
||||
place_id = getattr(place, "place_id", None)
|
||||
if place_id is not None:
|
||||
# ★ 실체(area_contents)와 관계(place_area_refs)를 조인한다 — 2026-09-09 에 값과 관계를
|
||||
# 갈랐다. 사진 유무는 body.firstimage 로 판단한다(같은 사실을 컬럼으로 또 두지 않는다).
|
||||
nearby_q = (
|
||||
select(
|
||||
area_contents.content_type,
|
||||
area_contents.external_id,
|
||||
area_contents.title,
|
||||
area_contents.body,
|
||||
area_contents.display_end_at,
|
||||
# ★ _local_rows 가 읽는 필드는 빠짐없이 넣는다 — 조인으로 바꾸면서
|
||||
# source·collected_at 이 빠져 AttributeError 로 스냅샷이 통째로 죽었다.
|
||||
area_contents.source,
|
||||
area_contents.collected_at,
|
||||
place_area_refs.distance_m,
|
||||
)
|
||||
.join(place_area_refs, place_area_refs.local_content_id == area_contents.local_content_id)
|
||||
.where(
|
||||
place_area_refs.place_id == place_id,
|
||||
place_area_refs.deleted == False, # noqa: E712
|
||||
place_area_refs.hidden == False, # noqa: E712
|
||||
personal = await _site_places(place_id)
|
||||
if personal:
|
||||
ids = [uuid.UUID(k) for k in personal if _is_uuid(k)]
|
||||
shared_q = select(area_contents).where(
|
||||
area_contents.local_content_id.in_(ids),
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
or_(area_contents.display_end_at.is_(None), area_contents.display_end_at > now),
|
||||
)
|
||||
.order_by(
|
||||
area_contents.content_type.asc(),
|
||||
# 사진 있는 것이 먼저 — 화면이 카드라 사진이 없으면 자리가 빈다.
|
||||
(area_contents.body["firstimage"].astext != "").desc().nullslast(),
|
||||
place_area_refs.distance_m.asc(),
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
area_contents.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: DB_SESSION_MNG.execute(s, shared_q),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
|
||||
rows = []
|
||||
|
||||
merged = []
|
||||
for row in rows or []:
|
||||
mine = personal.get(str(row.local_content_id)) or {}
|
||||
if mine.get("hidden"):
|
||||
continue
|
||||
body = dict(row.body if isinstance(row.body, dict) else {})
|
||||
# 거리만 얹는다. 공용 실체는 이미 렌더러 모양이라 여기서 이름을 바꾸지 않는다.
|
||||
if mine.get("distanceMeters") is not None:
|
||||
body["distanceMeters"] = mine["distanceMeters"]
|
||||
merged.append((row, body, mine.get("distanceMeters")))
|
||||
|
||||
merged.sort(key=lambda t: (not bool(t[1].get("imageUrl")), t[2] if t[2] is not None else 1 << 30))
|
||||
contents += _local_rows(
|
||||
[_Row(r, b) for r, b, _ in merged], seen, source=LocalSource.TOUR_API.value
|
||||
)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
place_area_refs.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, nearby_q)
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
|
||||
rows = []
|
||||
contents += _local_rows(rows or [], seen, source=LocalSource.TOUR_API.value)
|
||||
|
||||
return {"region_code": region_code or None, "contents": contents}
|
||||
|
||||
|
||||
class _Row:
|
||||
"""area_contents 행 + 사이트 값이 얹힌 body. `_local_rows` 가 두 캐시를 같은 모양으로 읽게 한다."""
|
||||
|
||||
__slots__ = ("content_type", "source", "title", "body", "collected_at", "kind",
|
||||
"latitude", "longitude")
|
||||
|
||||
def __init__(self, row, body):
|
||||
self.content_type, self.source = row.content_type, row.source
|
||||
self.title, self.body, self.collected_at, self.kind = row.title, body, row.collected_at, row.kind
|
||||
self.latitude, self.longitude = row.latitude, row.longitude
|
||||
|
||||
|
||||
def _is_uuid(value: str) -> bool:
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
async def _site_places(place_id) -> dict:
|
||||
"""이 사이트의 주변 개인화 맵(ref → {kind, distanceMeters, hidden}).
|
||||
|
||||
★ 사이트가 없으면 빈 맵이다 — 발행 전 업장은 주변 정보가 안 나간다. 그건 옳다.
|
||||
개인화 값이 없다는 건 "이 사이트에 그 항목이 붙은 적이 없다"는 뜻이다.
|
||||
"""
|
||||
q = (
|
||||
select(site_sections.data)
|
||||
.join(sites, sites.site_id == site_sections.site_id)
|
||||
.where(
|
||||
sites.place_id == place_id,
|
||||
sites.deleted == False, # noqa: E712
|
||||
site_sections.section_id == "local",
|
||||
site_sections.deleted == False, # noqa: E712
|
||||
)
|
||||
.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)
|
||||
)
|
||||
if err != ErrorType.SUCCESS or not rows:
|
||||
return {}
|
||||
data = rows[0]
|
||||
return (data or {}).get("places") or {} if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
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:
|
||||
continue
|
||||
seen[content_type] = taken + 1
|
||||
body = row.body if isinstance(row.body, dict) else {}
|
||||
out.append({
|
||||
entry = {
|
||||
"content_type": content_type,
|
||||
"source": source if source is not None else row.source,
|
||||
"title": row.title,
|
||||
"body": {k: v for k, v in body.items() if k not in _LOCAL_BODY_DROP},
|
||||
"collected_at": _iso(row.collected_at),
|
||||
})
|
||||
}
|
||||
if kind:
|
||||
entry["kind"] = kind
|
||||
# ★ 좌표는 **컬럼**에서 온다(2026-09-09). 예전에는 body.mapx/mapy 였는데, 같은 값이
|
||||
# 컬럼에도 있어 한쪽만 갱신될 자리였다. 일정 조립(services/itinerary)이 이걸 읽는다.
|
||||
for key, value in (("latitude", getattr(row, "latitude", None)),
|
||||
("longitude", getattr(row, "longitude", None))):
|
||||
if value is not None:
|
||||
entry[key] = str(value)
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user