Files
o2o-weather/backend/scripts/fetch_sunset_spots.py
T
minaChoi ddf05aeb5c feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?'
- 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준
- 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수
- 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리
- 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정
- 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성
- 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시
- 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집
- 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
2026-10-06 16:36:11 +09:00

107 lines
4.8 KiB
Python

"""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()))