"""TourAPI 키워드 검색으로 노을 명소 후보를 모아 seed/sunset_spot_tourapi.csv 로 쓴다 (일회성). 사람이 이 파일을 훑어 노을과 무관한 곳·중복을 걸러 seed/sunset_spot.csv 로 옮긴다. 실행: docker exec o2o-weather-backend-1 python scripts/fetch_sunset_spots.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 read_regions # noqa: E402 from services.external.data_go_kr import DataGoKrRequestFailed, get_all_items, get_body # noqa: E402 SEARCH_URL = "https://apis.data.go.kr/B551011/KorService2/searchKeyword2" DETAIL_URL = "https://apis.data.go.kr/B551011/KorService2/detailCommon2" KEYWORDS = ("노을", "일몰", "낙조", "석양", "해넘이") # 이름엔 노을 낱말이 없어도 개요에 일몰 명소라고 나오는 곳을 찾으려고 지형 낱말로 더 뒤진다. 수도권은 촘촘히, 그다음 광역시·서남해안. _SEA = ("해수욕장", "해변", "포구", "갯벌", "방조제", "해안") AREA_KEYWORDS = { "11": ("한강공원", "전망대", "공원", "호수공원", "섬"), "28": ("전망대", "공원", "호수공원", "섬", "항", "등대") + _SEA, "41": ("한강공원", "전망대", "호수공원", "섬", "항", "등대") + _SEA, "26": ("전망대", "공원", "등대") + _SEA, "27": ("전망대",), "30": ("전망대",), "31": ("전망대", "해수욕장", "해안"), "12": ("전망대",) + _SEA, "44": _SEA, "52": _SEA, "50": _SEA + ("오름",), } SUNSET_WORDS = re.compile("노을|일몰|낙조|석양|해넘이|해질녘|해 질") TOURIST_SPOT = "12" OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "sunset_spot_tourapi.csv") _BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak"} def _clean(text: str) -> str: return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text or "")).strip() def _snippet(overview: str) -> str: """개요에서 노을 낱말이 든 문장 하나.""" for sentence in re.split(r"(?<=[.!?다])\s+", overview): if SUNSET_WORDS.search(sentence): return sentence[:200] return "" async def main() -> int: regions = read_regions() found: dict[str, dict] = {} async with httpx.AsyncClient(timeout=30) as client: for kw in KEYWORDS: items = await get_all_items(client, SEARCH_URL, {**_BASE, "keyword": kw, "contentTypeId": TOURIST_SPOT}, page_size=100) print(f"{kw}: {len(items)}") for it in items: if it.get("mapx") and it.get("mapy"): found.setdefault(str(it["contentid"]), it) for sido, kws in AREA_KEYWORDS.items(): for kw in kws: items = await get_all_items(client, SEARCH_URL, {**_BASE, "keyword": kw, "contentTypeId": TOURIST_SPOT, "lDongRegnCd": sido}, page_size=100) for it in items: if it.get("mapx") and it.get("mapy"): found.setdefault(str(it["contentid"]), it) print(f"{sido}: total {len(found)}") rows = [] for cid, it in found.items(): try: body = await get_body(client, DETAIL_URL, {**_BASE, "contentId": cid}) except DataGoKrRequestFailed as e: print(f"detail {cid}: {e}") continue raw = (body.get("items") or {}).get("item") or [{}] overview = _clean((raw[0] if isinstance(raw, list) else raw).get("overview", "")) title = _clean(it.get("title", "")) in_title = bool(SUNSET_WORDS.search(title)) snippet = _snippet(overview) if not in_title and not snippet: 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.append({ "source": f"tourapi:{cid}", "region_name": near["name"], "name": title, "addr": _clean(it.get("addr1", "")), "lat": lat, "lon": lon, "in_title": int(in_title), "snippet": snippet, }) rows.sort(key=lambda r: (r["region_name"], r["name"])) with open(OUT, "w", encoding="utf-8", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0]) if rows else ["source"]) w.writeheader() w.writerows(rows) print(f"candidates {len(found)}, kept {len(rows)} -> {OUT}") return 0 if __name__ == "__main__": sys.exit(asyncio.run(main()))