import asyncio from dataclasses import dataclass from datetime import date, timedelta from typing import Optional import httpx from fastapi import Depends from redis.exceptions import RedisError from common.cache.lock import redis_lock from common.cache.redis_client import REDIS from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import Event, Place, Region, WeatherDaily from common.enums import ErrorType, EventKind, RainType, Sky from common.logger import LOG from common.utils.geo import haversine_km from common.utils.kma_time import KST, kst_midnight, now_kst from common.utils.text import hour_label from crud.index_crud import IndexCRUD from crud.region_crud import RegionCRUD from crud.weather_crud import WeatherCRUD from crud.week_crud import WeekCRUD from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.kasi import fetch_holidays from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT from services.external.tour_api import fetch_festivals, parse_festivals from services.index_service import IndexService DAYS = 11 # 중기예보가 닿는 오늘+10일까지 EVENT_DAYS = 30 # 몇 달씩 이어지는 상설 행사는 '이번 주 행사'로 보이지 않게 뺀다. MAX_EVENT_DAYS = 60 EVENT_RADIUS_KM = 30 # 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다. _SIDO_REACH_KM = EVENT_RADIUS_KM + 20 _ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") _SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} _RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비·눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"} @dataclass class DayPlan: day: date weekday: str holiday: Optional[str] icon: str temp_min_c: Optional[float] temp_max_c: Optional[float] headline: str summary: str pick: str rain_hours: Optional[tuple[int, int]] is_rainy: bool rain_prob: int @dataclass class PlaceItem: place: Place is_good: bool @dataclass class EventItem: event: Event status: str status_label: str fit: Optional[str] distance_km: Optional[float] = None def _icon(sky: Sky, rain: RainType) -> str: if rain is RainType.SNOW: return "snow" if rain is not RainType.NONE: return "rain" return {Sky.CLEAR: "sun", Sky.PARTLY: "sun_cloud", Sky.CLOUDY: "cloud"}[sky] def _weather_word(d: WeatherDaily, rain_hours: Optional[tuple[int, int]]) -> str: rain = RainType(d.rain_type) if rain is not RainType.NONE: return f"{hour_label(rain_hours[0])}부터 {_RAIN_WORD[rain]}" if rain_hours else _RAIN_WORD[rain] return _SKY_WORD[Sky(d.sky)] def _rain_hours(rows) -> Optional[tuple[int, int]]: rainy = [r.forecast_at.astimezone(KST).hour for r in rows if r.rain_type != RainType.NONE.value] return (rainy[0], rainy[-1] + 1) if rainy else None def image_credit(e: Event) -> Optional[str]: """사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None.""" if not e.image_url or e.source_id is None: return None return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT _MIX_ORDER = (EventKind.FESTIVAL, EventKind.POPUP, EventKind.EXHIBITION, EventKind.CONCERT) def mix_kinds(items: list[EventItem]) -> list[EventItem]: """종류(축제→팝업→전시→콘서트)를 돌아가며 하나씩. 같은 종류 안에서는 받은 순서를 지킨다.""" queues = [[e for e in items if e.event.kind == k] for k in _MIX_ORDER] queues.append([e for e in items if e.event.kind not in _MIX_ORDER]) mixed = [] while any(queues): for q in queues: if q: mixed.append(q.pop(0)) return mixed def nearby_sidos(region: Region, regions: list[Region]) -> list[str]: """반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에.""" lat, lon = float(region.lat), float(region.lon) near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM} return [region.code[:2]] + sorted(near - {region.code[:2]}) def event_distance(region: Region, e: Event) -> Optional[float]: if e.lat is None or e.lon is None: return None return round(haversine_km(float(region.lat), float(region.lon), float(e.lat), float(e.lon)), 1) def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool: """좌표가 있으면 반경 안, 없으면 같은 구(구를 아는 행사) 또는 같은 시도.""" if distance_km is not None: return distance_km <= EVENT_RADIUS_KM if e.region_code is not None: return e.region_code == region.code return e.sido_code == region.code[:2] def _status(e: Event, today: date) -> tuple[str, str]: if e.start_date <= today <= e.end_date: return "live", "진행 중" days = (e.start_date - today).days if days <= 7 and e.start_date.weekday() >= 5: return "soon", f"이번 {_WEEKDAY_KO[e.start_date.weekday()]}요일" return "soon", f"D-{days}" async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str) -> list[dict]: """문화정보원 전시·콘서트. 실패해도 TourAPI 행사는 그대로 넣게 여기서 로그만 남긴다.""" try: return parse_exhibitions(await fetch_exhibitions(client, sido, today, EVENT_DAYS, realm), sido, today, realm) except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e: LOG.error(f"[week] culture {realm} {sido}: {e}") return [] async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]: """시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다.""" try: async with httpx.AsyncClient(timeout=30) as client: festivals = parse_festivals(await fetch_festivals(client, sido, today), sido) exhibitions = await _culture(client, sido, today, EXHIBITION) concerts = await _culture(client, sido, today, CONCERT) except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e: LOG.error(f"[week] events {sido}: {e}") return ErrorType.EXTERNAL_API_ERROR, {} rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)]) LOG.info(f"[week] events {sido} {len(rows)}: {err.name}") return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)} class WeekService: def __init__( self, regions: RegionCRUD = Depends(RegionCRUD), crud: WeekCRUD = Depends(WeekCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), index_crud: IndexCRUD = Depends(IndexCRUD), index_service: IndexService = Depends(IndexService), ) -> None: self.regions, self.crud, self.weather, self.index_crud, self.index_service = regions, crud, weather, index_crud, index_service async def _region(self, code: str) -> tuple[ErrorType, Optional[Region]]: err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code)) if err is ErrorType.SUCCESS and region is None: return ErrorType.NOT_FOUND, None return err, region async def week(self, region_code: str) -> tuple[ErrorType, list[DayPlan]]: err, region = await self._region(region_code) if err is not ErrorType.SUCCESS: return err, [] now = now_kst() today = now.date() await asyncio.gather(self.index_service.ensure(region, now), self._ensure_holidays(today)) last = today + timedelta(days=DAYS - 1) start = kst_midnight(today) err, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, today, last)) _, hourly = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start, start + timedelta(days=DAYS))) _, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, last)) _, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index_crud.definitions(s)) _, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.index_crud.scores(s, region.code, today, last)) if err is not ErrorType.SUCCESS: return err, [] names = {d.index_id: d.name for d in defs or []} plans = [] for d in daily: rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date] rain_hours = _rain_hours(rows) top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: x.score, reverse=True)[:2] holiday = (holidays or {}).get(d.forecast_date) weekday = _WEEKDAY_KO[d.forecast_date.weekday()] word = _weather_word(d, rain_hours) temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else "" is_rainy = d.rain_type != RainType.NONE.value if top: summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top) pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천" else: summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요") plans.append(DayPlan( day=d.forecast_date, weekday=weekday, holiday=holiday, icon=_icon(Sky(d.sky), RainType(d.rain_type)), temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None, temp_max_c=float(d.temp_max_c) if d.temp_max_c is not None else None, headline=f"{weekday}요일 · {word}{temps}", summary=summary, pick=pick, rain_hours=rain_hours, is_rainy=is_rainy, rain_prob=d.rain_prob, )) return ErrorType.SUCCESS, plans async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str]]: err, region = await self._region(region_code) if err is not ErrorType.SUCCESS: return err, [], [] err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2])) _, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day)) if err is not ErrorType.SUCCESS: return err, [], [] rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value areas = list(dict.fromkeys(p.area for p in places)) picked = [p for p in places if area is None or p.area == area] picked.sort(key=lambda p: (p.is_outdoor if rainy else not p.is_outdoor, p.sort_order)) return ErrorType.SUCCESS, [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor) for p in picked], areas async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]: err, region = await self._region(region_code) if err is not ErrorType.SUCCESS: return err, [] now = now_kst() today = now.date() err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.search(s)) if err is not ErrorType.SUCCESS: return err, [] sidos = nearby_sidos(region, regions) await asyncio.gather( self.index_service.weather_service.ensure_vilage(region, now), self.index_service.weather_service.ensure_mid(region, now), ) err, events = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.events(s, sidos, today, today + timedelta(days=EVENT_DAYS))) _, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, today, today + timedelta(days=DAYS - 1))) if err is not ErrorType.SUCCESS: return err, [] by_day = {d.forecast_date: d for d in daily or []} items = [] near = [(e, event_distance(region, e)) for e in events if (e.end_date - e.start_date).days <= MAX_EVENT_DAYS] near = sorted(((e, d) for e, d in near if is_nearby(region, e, d)), key=lambda x: (abs((x[0].start_date - today).days), x[1] if x[1] is not None else EVENT_RADIUS_KM)) for e, dist in near: if area is not None and e.area not in (None, area): continue status, label = _status(e, today) first = max(e.start_date, today) d = by_day.get(first) fit = None if d is not None: temp = f" {round(float(d.temp_max_c))}°" if d.temp_max_c is not None else "" fit = f"{_WEEKDAY_KO[first.weekday()]}요일 {_weather_word(d, None)}{temp}" items.append(EventItem(event=e, status=status, status_label=label, fit=fit, distance_km=dist)) return ErrorType.SUCCESS, items async def _ensure_holidays(self, today: date) -> None: for year in sorted({today.year, (today + timedelta(days=DAYS)).year}): key = f"holiday:{year}" try: if await REDIS.conn.exists(key): continue err, count = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holiday_count(s, year)) if err is ErrorType.SUCCESS and count: await REDIS.conn.set(key, "1", ex=30 * 86400) continue async with redis_lock(f"lock:{key}", ttl_sec=60) as acquired: if not acquired: continue async with httpx.AsyncClient(timeout=20) as client: rows = [r for m in range(1, 13) for r in await fetch_holidays(client, year, m)] err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_holidays(s, rows)]) if err is ErrorType.SUCCESS: await REDIS.conn.set(key, "1", ex=30 * 86400) except _ERRORS as e: LOG.error(f"[week] holidays {year}: {e}")