import asyncio import csv import json import os import sys from datetime import date sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from sqlalchemy import update # noqa: E402 from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402 from common.database.model.models import Region # noqa: E402 from common.enums import ErrorType # noqa: E402 from crud.index_crud import IndexCRUD # noqa: E402 from crud.region_crud import RegionCRUD # noqa: E402 from crud.season_crud import SeasonCRUD # noqa: E402 from crud.sky_crud import SkyCRUD # noqa: E402 from crud.week_crud import WeekCRUD # noqa: E402 # 출처: 기상청 단기예보 활용가이드 격자·위경도 표(시군구 줄) + 특보구역·중기예보구역 코드표. SEED_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed") _INT = {"nx", "ny"} _FLOAT = {"lat", "lon"} def read_regions() -> list[dict]: with open(os.path.join(SEED_DIR, "region.csv"), encoding="utf-8") as f: return [{k: int(v) if k in _INT else float(v) if k in _FLOAT else v for k, v in row.items()} for row in csv.DictReader(f)] def _read(name: str) -> list[dict]: with open(os.path.join(SEED_DIR, name), encoding="utf-8") as f: return list(csv.DictReader(f)) def _json(name: str) -> list[dict]: with open(os.path.join(SEED_DIR, name), encoding="utf-8") as f: return json.load(f) async def _set_ranking_spots(s, spots: list[dict]) -> None: await s.execute(update(Region).values(is_ranking_spot=False, ranking_note=None)) for row in spots: res = await s.execute(update(Region).where(Region.name == row["name"]).values(is_ranking_spot=True, ranking_note=row["note"])) if res.rowcount != 1: raise ValueError(f"ranking_spot.csv: region not found {row['name']}") async def main() -> int: rows = read_regions() code_by_name = {r["name"]: r["code"] for r in rows} spots = [ {"region_code": code_by_name[r["region_name"]], "name": r["name"], "description": r["description"], "lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": int(r["sort_order"])} for r in _read("sunset_spot.csv") ] places = [ {"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1", "icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r["sort_order"])} for r in _read("place.csv") ] # 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다. events = [ {"region_code": code_by_name[r["region_name"]], "sido_code": code_by_name[r["region_name"]][:2], "area": r["area"] or None, "name": r["name"], "place_name": r["place_name"], "icon": r["icon"], "start_date": date.fromisoformat(r["start_date"]), "end_date": date.fromisoformat(r["end_date"]), "is_confirmed": False, "source_url": r["source_url"] or None} for r in _read("event.csv") ] articles = [ {**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None, "show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None} for a in _json("article.json") ] weeks = _json("season_week.json") ranking = _read("ranking_spot.csv") indices = _json("index_definition.json") err = await DB_SESSION_MNG.execute_lambda_run([ lambda s: RegionCRUD().upsert_many(s, rows), lambda s: _set_ranking_spots(s, ranking), lambda s: SkyCRUD().replace_spots(s, spots), lambda s: IndexCRUD().upsert_definitions(s, indices), lambda s: WeekCRUD().replace_places(s, places), lambda s: WeekCRUD().replace_manual_events(s, events), lambda s: SeasonCRUD().upsert_articles(s, articles), lambda s: SeasonCRUD().upsert_weeks(s, weeks), ]) await DB_SESSION_MNG.stop() print(f"region {len(rows)}, ranking {len(ranking)}, sunset_spot {len(spots)}, index {len(indices)}, place {len(places)}, event {len(events)}, article {len(articles)}, season_week {len(weeks)}: {err.name}") return 0 if err is ErrorType.SUCCESS else 1 if __name__ == "__main__": sys.exit(asyncio.run(main()))