[feat] solution,admin,postgres-init: 주변정보를 업장 좌표 기준으로 — 시군구 캐시는 "가까운 곳"을 못 준다

지역 정보(맛집·관광지·축제)는 행정구역 코드(local_contents.region_code) 단위로 캐시돼
"그 시군구에 있는 것"을 줬다. 양양군 업장 옆 5km 속초 관광지는 빠지고 같은 군 반대편
30km 맛집이 붙는 구조라, 캔버스의 지역 정보 섹션은 늘 "준비 중"이었다. 업장 좌표로
TourAPI 를 직접 물어 업장 단위(place_contents)에 담고, 캔버스는 스크린샷으로 받은
형식(도보 시간 필터 + 카드 캐러셀)으로 통일했다.
This commit is contained in:
skkim committed 2026-09-08 11:46:03 +09:00
1 parent 238d4c25c4
commit 01824a7a91
38 files changed
+1854 -576

No files matched your search

+24 -1
View File
@@ -43,9 +43,10 @@ _BASE_URL = "https://dapi.kakao.com"
_KEYWORD_URL = f"{_BASE_URL}/v2/local/search/keyword.json"
_COORD2REGION_URL = f"{_BASE_URL}/v2/local/geo/coord2regioncode.json"
_CATEGORY_URL = f"{_BASE_URL}/v2/local/search/category.json"
_ADDRESS_URL = f"{_BASE_URL}/v2/local/search/address.json"
# 초과 단가(원). 로그에 함께 남겨 어떤 호출이 비싼지 바로 보이게 한다.
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5}
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5, "address": 0.5}
# 프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거.
_CALL_COUNTS: Counter = Counter()
@@ -362,6 +363,28 @@ class KakaoLocalClient:
picked = next((d for d in docs if d.get("region_type") == "H"), docs[0])
return RegionCode.from_document(picked)
# ---- 2-1) 주소 → 좌표 ----
async def geocode_address(self, address: str) -> Optional[tuple[float, float]]:
"""도로명·지번 주소 → (위도, 경도). 결과가 없으면 None — 좌표를 지어내지 않는다.
★ 쓰는 곳: 좌표 없이 검증된 사업장의 주변 정보 수집(local_content_service.sync_place).
동일 업소 검증(카카오 후보·네이버 상세)은 좌표를 같이 주므로 보통은 비어 있지 않다 —
비는 건 옛 데이터나 좌표 없는 후보를 고른 경우다. 그때 주소로 한 번 더 찾는다.
싸다(초과 시 건당 0.5원). 결과는 places 에 박제하므로 사업장당 1회다.
"""
query = (address or "").strip()
if not query:
return None
data = await self._get(_ADDRESS_URL, {"query": query, "size": "1"}, "address")
docs = data.get("documents") or []
if not docs:
LOG.i(f"[kakao] 주소 → 좌표 결과 없음: {query[:60]}")
return None
lat, lon = _to_float(docs[0].get("y")), _to_float(docs[0].get("x")) # ★ y=위도 · x=경도
if lat is None or lon is None:
return None
return lat, lon
# ---- 3) 주변 맛집·시설 ----
async def search_category(
self,
+263 -49
View File
@@ -1,17 +1,58 @@
"""공공데이터포털 전국문화축제표준데이터 클라이언트.
"""한국관광공사 TourAPI(KorService2) — **업장 반경** 주변정보 수집 클라이언트.
설정 키 이름은 기존 배포 계약을 유지하기 위해 TOUR_API_KEY를 그대로 사용한다.
collector/tour_api_adapter.py 가 '사업장 1곳'의 fact 를 캐는 쪽이라면, 여기는
업장 좌표 반경 안의 곁들이 정보(맛집·관광지·축제·여행코스)를 긁는 쪽이다.
결과는 place_contents(업장 단위 캐시)에 들어가 발행본·캔버스의 지역 정보 섹션이 된다.
★ 왜 행정구역이 아니라 좌표인가 (2026-09-04, specs/2026-09-04-tourapi-radius-spike.md)
처음엔 법정동 코드로 areaBasedList2 를 불렀다. 그건 '그 시군구에 있는 것'이지
'이 업장에서 가까운 것'이 아니다 — 양양군 업장 옆 5km 속초 관광지가 빠지고,
같은 시군구 반대편 30km 맛집이 붙는다. locationBasedList2 는 좌표+반경으로 묻고
거리(dist)까지 준다. 실측(군산 절골길 18): 10km 안 133건, 5km 안 100건.
★ 호출 수 — 업장당 종류별 1회 (맛집·관광지·축제)
2026-09-08 부터 종류마다 **따로** 부른다(맛집 5km · 관광지 10km · 축제는 시도 전체, 반경 없음) —
한 걸음에 갈 맛집과 차 타고 갈 축제를 같은 반경으로 재는 게 맞지 않았다.
여행코스(25)는 실측 결과 반경을 넓혀도 데이터가 거의 없어(전북 전체 3건) 뺐다.
★ 축제는 locationBasedList2 가 아니라 searchFestival2 를 쓴다 (2026-09-08 교체)
locationBasedList2(contentTypeId=15) 의 위치 색인은 못 믿는다 — 실측(군산 절골길 18):
반경 20km 를 아무리 넓혀도 2023년에 끝난 서천 전시 1건만 나오고, 코앞 500m 의
진행 예정 축제(군산시간여행축제 등)는 끝내 안 잡혔다. searchFestival2 는 법정동(시도)
단위로 묻지만 정확하고 기간까지 함께 준다 — 그래서 시도 전체를 받아 우리가 거리로 거른다.
eventStartDate 는 파라미터로 준 날짜 **이후 시작하는** 행사만 거른다(이전에 시작해 아직
진행 중인 행사는 잡히지 않는다 — 실측). 그래서 항상 **그 해 1월 1일**로 고정해 부르고,
이미 끝난 행사(eventenddate < 오늘)만 우리가 한 번 더 거른다.
★ 이미지 저작권 — 수집 단계에서 끝낸다 (collector/tour_api_adapter.py 와 같은 규칙)
firstimage 는 공공누리 Type1(출처표시)·Type3(출처표시+변경금지)만 남긴다.
발행본은 상업적 이용이라 Type2·Type4 는 싣지 못한다. 유형을 모르면 버린다.
"""
import hashlib
from datetime import date
from urllib.parse import unquote
from typing import Optional
from urllib.parse import unquote, urlencode
import httpx
from common.enums import LocalContentType
from common.utils.geo import haversine_m
from config.server_configs import external_api_config
_URL = "https://api.data.go.kr/openapi/tn_pubr_public_cltur_fstvl_api"
BASE_URL = "https://apis.data.go.kr/B551011/KorService2"
REQUEST_TIMEOUT = 25
PAGE_SIZE = 100
# 반경 10km 도심은 300건을 넘지 않는다(실측 133건). 그 이상은 어차피 종류별 20건 상한에 안 든다.
MAX_PAGES = 4
# TourAPI contentTypeId ↔ 우리 종류 코드(locationBasedList2 용). 축제(15)는 여기 없다 —
# searchFestival2 로 따로 받는다(위 모듈 docstring 참고). 여행코스(25)도 뺐다(데이터 부족).
CONTENT_TYPE_MAP = {
"39": LocalContentType.RESTAURANT.value,
"12": LocalContentType.ATTRACTION.value,
}
# 상업적 이용이 허용된 공공누리 유형(tour_api_adapter 와 동일 규칙·동일 이유).
_COMMERCIAL_OK_LICENSES = frozenset({"type1", "type3"})
class TourApiNotConfigured(RuntimeError):
@@ -22,52 +63,225 @@ class TourApiRequestFailed(RuntimeError):
pass
def _normalize(item: dict) -> dict:
"""표준데이터 필드명을 화면/저장소의 공통 축제 필드로 변환한다."""
identity = "|".join(str(item.get(key) or "") for key in ("fstvlNm", "fstvlStartDate", "fstvlEndDate", "insttCode"))
return {
"contentid": hashlib.sha256(identity.encode("utf-8")).hexdigest()[:32],
"title": item.get("fstvlNm"),
"eventstartdate": str(item.get("fstvlStartDate") or "").replace("-", ""),
"eventenddate": str(item.get("fstvlEndDate") or "").replace("-", ""),
"addr1": item.get("rdnmadr") or item.get("lnmadr") or item.get("eventPlace"),
"mapx": item.get("longitude"),
"mapy": item.get("latitude"),
"tel": item.get("phoneNumber"),
"homepage": item.get("homepageUrl"),
"organizer": item.get("suprtInsttNm"),
"overview": item.get("relateInfo") or item.get("opar"),
"raw": item,
}
# ── HTTP ───────────────────────────────────────────────────────────────
async def search_festivals(*, start_date: date, area_code: str | None = None, rows: int = 100) -> list[dict]:
def _service_key() -> str:
key = (external_api_config.tour_api_key or "").strip()
if not key:
raise TourApiNotConfigured("TOUR_API_KEY is not configured")
params = {
# 포털의 "Encoding" 키를 넣어도 httpx가 이중 인코딩하지 않도록 원문으로 되돌린다.
"serviceKey": unquote(key),
"type": "json",
"numOfRows": max(1, min(rows, 1000)),
"pageNo": 1,
}
return key
async def _call(client: httpx.AsyncClient, op: str, **params) -> tuple[list[dict], int]:
"""오퍼레이션 1회 → (항목, totalCount). 결과 없음은 빈 목록 — 없는 것과 실패를 구분한다.
★ 포털의 'Encoding' 키를 그대로 넣어도 이중 인코딩되지 않도록 원문으로 되돌린다
(collector/tour_api_adapter._call 과 같은 처리).
"""
query = urlencode(
{"serviceKey": unquote(_service_key()), "MobileOS": "ETC", "MobileApp": "o2o-web4ai",
"_type": "json", "numOfRows": str(PAGE_SIZE), "pageNo": "1", **params},
safe="",
)
res = await client.get(f"{BASE_URL}/{op}?{query}")
if res.status_code != 200:
raise TourApiRequestFailed(f"{op} HTTP {res.status_code}")
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(20.0, connect=5.0)) as client:
response = await client.get(_URL, params=params)
response.raise_for_status()
payload = response.json()
response_data = payload.get("response", payload)
header = response_data.get("header", {})
if header.get("resultCode") not in (None, "00", "0000"):
raise TourApiRequestFailed(header.get("resultMsg") or "TourAPI returned an error")
items_node = response_data.get("body", {}).get("items", [])
items = items_node.get("item", []) if isinstance(items_node, dict) else items_node
if isinstance(items, dict):
items = [items]
normalized = [_normalize(item) for item in (items or [])]
# API가 날짜 필터를 제공하지 않으므로 종료된 축제는 애플리케이션에서 제외한다.
cutoff = start_date.strftime("%Y%m%d")
return [item for item in normalized if not item["eventenddate"] or item["eventenddate"] >= cutoff]
except (httpx.HTTPError, ValueError, TypeError) as ex:
raise TourApiRequestFailed(str(ex)) from ex
payload = res.json()
except ValueError:
# 인증 실패·쿼터 초과는 XML 로 온다. 본문 앞부분을 그대로 올려 원인을 감추지 않는다.
raise TourApiRequestFailed(f"{op} 응답이 JSON 이 아니다: {res.text[:160]}")
# 게이트웨이 오류(미등록 키 등)는 200 + JSON 이지만 response 가 없다. 그것도 원인을 드러낸다.
if "response" not in payload:
raise TourApiRequestFailed(f"{op} 게이트웨이 오류: {str(payload)[:160]}")
header = payload["response"].get("header", {})
code = str(header.get("resultCode") or "")
if code not in ("0000", "00"):
raise TourApiRequestFailed(f"{op} 실패 [{code}] {header.get('resultMsg')}")
body = payload["response"].get("body", {}) or {}
items = (body.get("items") or {}).get("item") if isinstance(body.get("items"), dict) else None
if isinstance(items, dict):
items = [items]
total = int(body.get("totalCount") or 0)
return items or [], total
# ── 정규화 ──────────────────────────────────────────────────────────────
def _int(value) -> Optional[int]:
try:
return int(float(str(value).strip()))
except (TypeError, ValueError):
return None
def _normalize(item: dict) -> Optional[dict]:
"""locationBasedList2 항목 1건 → place_contents.body. contentid·title·거리·종류 없으면 버린다."""
content_id = str(item.get("contentid") or "").strip()
title = str(item.get("title") or "").strip()
kind = CONTENT_TYPE_MAP.get(str(item.get("contenttypeid") or "").strip())
distance = _int(item.get("dist"))
if not content_id or not title or kind is None or distance is None:
return None
body = {"contentid": content_id, "title": title, "content_type": kind, "distance_m": distance}
# lclsSystm1~3 = 분류체계 대/중/소. ★ 중분류(lclsSystm2)가 주변 맛집에서 같은 업태(경쟁 업소)를 빼는 기준이다.
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
"lclsSystm1", "lclsSystm2", "lclsSystm3"):
value = str(item.get(key) or "").strip()
if value:
body[key] = value
# 사진은 상업적 이용이 허용된 공공누리 유형일 때만 싣는다. 유형을 모르면 버린다.
image = str(item.get("firstimage") or "").strip()
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
if image and license_code in _COMMERCIAL_OK_LICENSES:
body["firstimage"] = image
body["license"] = license_code
thumb = str(item.get("firstimage2") or "").strip()
if thumb:
body["firstimage2"] = thumb
return body
# ── 공개 API ────────────────────────────────────────────────────────────
def make_client() -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=REQUEST_TIMEOUT)
async def fetch_nearby(client: httpx.AsyncClient, latitude: float, longitude: float,
*, radius_m: int, content_type_id: str) -> list[dict]:
"""업장 좌표 반경 안의 한 종류(정규화, 거리순). 종류마다 반경이 달라 호출도 따로 한다.
★ mapX=경도 · mapY=위도. 뒤집으면 엉뚱한 지역이 붙는다(카카오와 같은 함정).
"""
out: list[dict] = []
seen: set[str] = set()
for page in range(1, MAX_PAGES + 1):
items, total = await _call(
client, "locationBasedList2",
mapX=str(longitude), mapY=str(latitude), radius=str(radius_m),
contentTypeId=content_type_id, arrange="E", pageNo=str(page),
)
for item in items:
body = _normalize(item)
if body and body["contentid"] not in seen:
seen.add(body["contentid"])
out.append(body)
if not items or page * PAGE_SIZE >= total:
break
out.sort(key=lambda b: b["distance_m"])
return out
def _normalize_festival(item: dict, distance_m: int) -> Optional[dict]:
"""searchFestival2 항목 1건 → place_contents.body. locationBasedList2 와 달리 `dist` 를
안 주므로(호출측이 haversine 으로 잰 값을) 그대로 받는다. 기간은 여기 이미 있다."""
content_id = str(item.get("contentid") or "").strip()
title = str(item.get("title") or "").strip()
if not content_id or not title:
return None
body = {"contentid": content_id, "title": title,
"content_type": LocalContentType.FESTIVAL.value, "distance_m": distance_m}
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
"lclsSystm1", "lclsSystm2", "lclsSystm3", "eventstartdate", "eventenddate"):
value = str(item.get(key) or "").strip()
if value:
body[key] = value
image = str(item.get("firstimage") or "").strip()
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
if image and license_code in _COMMERCIAL_OK_LICENSES:
body["firstimage"] = image
body["license"] = license_code
thumb = str(item.get("firstimage2") or "").strip()
if thumb:
body["firstimage2"] = thumb
return body
def _festival_not_ended(body: dict, today: date) -> bool:
"""종료일이 지났으면 끝난 축제 — 신지 않는다. 기간을 아예 모르면 못 믿으니 역시 뺀다.
종료일 없이 시작일만 있으면(무기한 진행) 유지한다 — 끝났다는 증거가 없다."""
end, start = body.get("eventenddate"), body.get("eventstartdate")
ymd = today.strftime("%Y%m%d")
if end:
return len(end) == 8 and end.isdigit() and end >= ymd
return bool(start)
async def fetch_festivals_in_sido(client: httpx.AsyncClient, latitude: float, longitude: float,
*, sido_code: str, today: date) -> list[dict]:
"""업장이 속한 시도의 축제 **전부**(정규화, 거리순, 이미 끝난 것 제외). 반경으로 자르지 않는다.
★ 반경을 안 두는 이유(2026-09-08 결정): 축제는 차로 가는 행사라 20km 로 자르면 시도 안의
큰 축제가 빠진다. 시도 전체를 그대로 싣고, 거리는 정렬·표시용으로만 잰다.
(종류별 노출 상한은 스냅샷이 20건으로 자른다 — 사진 있는 것 우선 → 가까운 순.)
★ locationBasedList2 의 위치 색인은 못 믿어서 searchFestival2 를 쓴다(위 모듈 docstring).
eventStartDate 는 그 해 1월 1일로 **고정** — "오늘" 을 넣으면 그 이전에 시작해 아직 진행 중인
축제가 파라미터 자체에서 빠진다(실측). 연초부터 전부 받고, 끝난 것만 여기서 거른다.
★ 좌표 없는 항목은 뺀다 — distance_m 이 NOT NULL 이고, 거리 없는 카드는 도보 필터에 못 얹는다.
"""
start_date = date(today.year, 1, 1).strftime("%Y%m%d")
out: list[dict] = []
seen: set[str] = set()
for page in range(1, MAX_PAGES + 1):
items, total = await _call(
client, "searchFestival2",
eventStartDate=start_date, lDongRegnCd=sido_code, pageNo=str(page),
)
for item in items:
lnglat = _mapxy(item) # (경도, 위도) — 좌표가 없으면 거리를 잴 수 없다
if lnglat is None:
continue
lng, lat = lnglat
distance = haversine_m(latitude, longitude, lat, lng) # 자르지 않는다 — 정렬·표시용
body = _normalize_festival(item, round(distance))
if not body or body["contentid"] in seen:
continue
if not _festival_not_ended(body, today):
continue
seen.add(body["contentid"])
out.append(body)
if not items or page * PAGE_SIZE >= total:
break
out.sort(key=lambda b: b["distance_m"])
return out
def _mapxy(item: dict) -> Optional[tuple[float, float]]:
"""(경도, 위도). 좌표가 없거나 숫자가 아니면 None — 거리를 잴 수 없는 항목은 반경으로 못 거른다."""
try:
return float(item.get("mapx")), float(item.get("mapy"))
except (TypeError, ValueError):
return None
async def fetch_content_class(client: httpx.AsyncClient, content_id: str) -> Optional[str]:
"""콘텐츠 1건의 중분류 코드(lclsSystm2). 못 구하면 None.
업장 자신이 TourAPI 에 등록돼 있을 때(place_links 의 tour:// 링크) 그 업장의 업태를 여기서 읽는다 —
주변 맛집에서 같은 중분류를 빼기 위해서다. 외부 분류 문자열 매핑보다 이 값이 우선이다(같은 체계라 오차가 없다).
"""
items, _ = await _call(client, "detailCommon2", contentId=content_id)
if not items:
return None
code = str(items[0].get("lclsSystm2") or "").strip()
return code or None
def festival_is_current(period: Optional[tuple[str, str]], today: date) -> bool:
"""종료일이 지났으면 끝난 축제 — 싣지 않는다. 기간을 아예 모르면(None) 못 믿으니 역시 뺀다.
종료일 없이 시작일만 있으면(무기한 진행) 시작일이 지났어도 유지한다 — 끝났다는 증거가 없다."""
if not period:
return False
start, end = period
ymd = today.strftime("%Y%m%d")
if end:
return len(end) == 8 and end.isdigit() and end >= ymd
return bool(start)