Merge branch 'feature/stay-parity'

This commit is contained in:
HyeongBaeYang committed 2026-09-10 16:15:29 +09:00
commit 25f7e5c0c8
25 files changed
+987 -70

No files matched your search

@@ -31,6 +31,7 @@ from common.utils.gtime import GTime
from common.logger import LOG
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.prompts import story as prompts
@@ -73,10 +74,93 @@ async def _generate_kind(client: httpx.AsyncClient, kind: str, region_label: str
return [], [f"호출 실패: {ex}"]
items, dropped = grounding.parse_items(payload, kind, prompts.max_items(kind))
items = await _attach_images(kind, items, region_label)
LOG.i(f"[story] {region_label} {kind}: {len(items)}건 채택, {len(dropped)}건 버림")
return items, dropped
# 사진을 무엇으로 찾을지. 종류마다 출처가 다르다.
#
# chronicle · postcard 공공데이터(TourAPI) — 장소·시설 사진. 공공누리 Type1/Type3 만
# people 위키미디어 — 사람 얼굴. 상업 이용 가능 라이선스만
#
# ★ 가요·퀴즈는 찾지 않는다. 시안에도 그 자리에 사진이 없다.
_PLACE_IMAGE_KEYS = {
"chronicle": ("place", "title"), # 그 해의 장소 → 없으면 사건 이름
"postcard": ("place", "postmark"), # 엽서 앞면이 될 장소
}
# 한 종류에서 사진을 찾아볼 항목 수 상한. 건당 0.3~1초라 열두 개를 다 찌르면 생성이 두 배 걸린다.
_IMAGE_LOOKUP_LIMIT = 12
# ★ 사진이 없으면 항목 자체를 버리는 종류.
# 엽서는 **앞면 사진이 본체**다. 사진이 없으면 뒷면(문장·우표·소인)만 남아 카드가 반쪽이 되고,
# 시안과 나란히 놓으면 빈 카드로 보인다(실측 2026-09-10). 연표는 다르다 — 활자만으로도
# 레일 위에 서므로 사진 없는 항목을 버리면 연표에 구멍이 난다.
_IMAGE_REQUIRED_KINDS = {"postcard"}
def _region_token(region_label: str) -> str:
"""주소 대조에 쓸 지역 토막("전북 군산시" → "군산"). 시/군/구 접미사를 뗀다 —
TourAPI 주소는 '전북특별자치도 군산시 …' 라 표기가 우리와 다를 수 있다."""
for tok in reversed((region_label or "").split()):
if tok.endswith(("시", "군", "구")) and len(tok) > 1:
return tok[:-1]
return (region_label or "").split()[-1] if region_label else ""
async def _attach_images(kind: str, items: list[dict], region_label: str) -> list[dict]:
"""항목에 사진을 붙이고, 사진이 본체인 종류는 못 붙은 항목을 버린다.
★ **수집하는 그 자리에서 함께 가져온다.** 이미 DB 에 있는 사진을 가져다 쓰지 않는다 —
그건 "이 항목의 사진" 이 아니라 "마침 우리가 갖고 있던 사진" 이고, 엉뚱한 장소가
그 해의 사진으로 붙는다.
★ **같은 사진을 두 번 쓰지 않는다.** 네 항목이 같은 시설을 말하면 검색이 같은 사진을
네 번 준다 — 화면에는 같은 그림 넷이 늘어선다(실측 2026-09-10, 군산근대역사박물관).
두 번째부터는 사진 없는 것으로 친다.
★ 권리 판정은 부르는 쪽이 아니라 각 출처 모듈이 한다(tour_api.find_image · wikimedia).
"""
found = 0
used: set[str] = set()
if kind == "people":
async with wikimedia.make_client() as client:
for item in items[:_IMAGE_LOOKUP_LIMIT]:
hit = await wikimedia.find_person_image(client, str(item.get("name") or ""))
if not hit or hit.url in used:
continue
item["imageUrl"], item["imageCredit"] = hit.url, hit.credit
used.add(hit.url)
found += 1
elif kind in _PLACE_IMAGE_KEYS:
fields = _PLACE_IMAGE_KEYS[kind]
token = _region_token(region_label)
async with tour_api.make_client() as client:
for item in items[:_IMAGE_LOOKUP_LIMIT]:
keyword = next((str(item.get(f) or "").strip() for f in fields if item.get(f)), "")
if not keyword:
continue
url = await tour_api.find_image(client, keyword, token)
if not url or url in used:
continue
item["imageUrl"] = url
# 공공누리 제1유형도 출처 표시가 조건이다. 사진을 준 곳을 그대로 적는다.
item["imageCredit"] = "한국관광공사"
used.add(url)
found += 1
if kind in _IMAGE_REQUIRED_KINDS:
kept = [i for i in items if i.get("imageUrl")]
if len(kept) != len(items):
LOG.i(f"[story] {region_label} {kind}: 사진 없는 {len(items) - len(kept)}건 제외 "
f"(이 종류는 사진이 본체다)")
items = kept
if found:
LOG.i(f"[story] {region_label} {kind}: 사진 {found}장 붙임")
return items
async def generate_region_stories(region_code: str, region_label: str, kinds: list[str] | None = None) -> dict:
"""지역 하나의 이야기를 생성해 `area_contents` 에 넣는다. 종류별 채택 건수를 돌려준다.