Files
o2o-weather/backend/scripts/fetch_date_places.py
T

85 lines
4.1 KiB
Python

"""TourAPI 분류(lclsSystm3)에서 데이트에 맞는 관광지를 전국으로 모아 seed/place_tourapi.csv 로 쓴다 (일회성, 다시 돌리면 덮어씀).
손으로 고른 seed/place.csv 와 같은 곳(contentid)은 뺀다.
실행: docker exec o2o-weather-backend-1 python scripts/fetch_date_places.py
"""
import asyncio
import csv
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import httpx # noqa: E402
from common.utils.geo import haversine_km # noqa: E402
from scripts.load_seed import SEED_DIR, read_regions # noqa: E402
from services.external.data_go_kr import get_all_items # noqa: E402
LIST_URL = "https://apis.data.go.kr/B551011/KorService2/areaBasedList2"
OUT = os.path.join(SEED_DIR, "place_tourapi.csv")
_BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak", "arrange": "A"}
# lclsSystm3 → (야외, 아이콘, 한 줄 이유, 추천 시간). 이유는 분류에서 나오는 말만 쓴다.
CATEGORIES = {
"VE030100": (True, "picnic", "공원 산책·피크닉", "낮 12시~4시"),
"VE010200": (True, "stars", "전망대에서 보는 경치·야경", "해 진 뒤"),
"VE010300": (True, "stars", "다리 위 야경 산책", "해 진 뒤"),
"VE040300": (True, "walk", "둘레길 함께 걷기", "선선한 오후"),
"NA010200": (True, "walk", "숲길 산책", "오전 10시~"),
"NA020200": (True, "walk", "호숫가 산책", "선선한 저녁"),
"NA040700": (True, "garden", "수목원·정원 꽃길 산책", "오전 10시~"),
"VE040100": (True, "photo", "골목·카페거리 구경", "오후 2시~"),
"NA020900": (True, "sunset", "바닷가 산책", "노을 무렵"),
"VE020400": (False, "rain", "비 와도 실내 아쿠아리움", "비 오는 오후"),
"VE070600": (False, "bulb", "비 오면 미술관으로", "비 오는 날"),
}
FIELDS = ["source", "region_name", "area", "name", "is_outdoor", "icon", "reason", "best_time", "lat", "lon", "image_url"]
def _clean(text: str) -> str:
return re.sub(r"\s+", " ", text or "").strip()
def _manual_ids() -> set[str]:
with open(os.path.join(SEED_DIR, "place.csv"), encoding="utf-8") as f:
return {r["source"].removeprefix("tourapi:") for r in csv.DictReader(f) if r["source"].startswith("tourapi:")}
async def main() -> int:
regions = read_regions()
skip = _manual_ids()
rows: dict[str, dict] = {}
async with httpx.AsyncClient(timeout=30) as client:
for code, (outdoor, icon, reason, best_time) in CATEGORIES.items():
params = {**_BASE, "lclsSystm1": code[:2], "lclsSystm2": code[:4], "lclsSystm3": code}
items = await get_all_items(client, LIST_URL, params, page_size=500)
kept = 0
for it in items:
cid, title = str(it["contentid"]), _clean(it.get("title", ""))
if cid in skip or cid in rows or not title or not it.get("mapx") or not it.get("mapy"):
continue
lat, lon = round(float(it["mapy"]), 5), round(float(it["mapx"]), 5)
if not (33 <= lat <= 39 and 124 <= lon <= 132):
print(f"skip {cid} {title}: 좌표가 국내 밖 ({lat}, {lon})")
continue
near = min(regions, key=lambda r: haversine_km(lat, lon, r["lat"], r["lon"]))
rows[cid] = {
"source": f"tourapi:{cid}", "region_name": near["name"], "area": near["short_name"], "name": title[:60],
"is_outdoor": int(outdoor), "icon": icon, "reason": reason, "best_time": best_time, "lat": lat, "lon": lon,
"image_url": (it.get("firstimage") or "").replace("http://", "https://", 1),
}
kept += 1
print(f"{code}: {len(items)} -> {kept}")
out = sorted(rows.values(), key=lambda r: (r["region_name"], r["name"]))
with open(OUT, "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=FIELDS)
w.writeheader()
w.writerows(out)
print(f"place {len(out)} -> {OUT}")
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))