import asyncio import random from dataclasses import dataclass, field from datetime import date, datetime, time, timedelta from typing import Optional 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 Article, OpenMeteoHourly, Post, Region, WeatherHourly from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType from common.logger import LOG from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst from common.utils.text import compass, day_range, hour_label, short_day from crud.feed_crud import FeedCRUD from crud.region_crud import RegionCRUD from crud.season_crud import SeasonCRUD from crud.weather_crud import WeatherCRUD from router.v1.feed.protocol import ( BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide, PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide, ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import pm10_grade, pm25_grade from services.calc.moon import illumination, nearest, phase_name from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE from services.calc.sun import sun_times from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label from services.index_service import IndexBoard, IndexItem, IndexService from services.now_service import NowService, NowWeather from services.season_service import SeasonService from services.sky_service import SkyService, SkyView, day_verdict from services.sky_service import outlook as sky_outlook from services.weather_service import TodayWeather, WeatherService from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds from services.weekend_plan import day_plan, forecast, pick_events from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days # 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드_기획.html). LINEUP = [ (1, PostType.WEATHER, RefType.NONE, None), (2, PostType.ALERT, RefType.NONE, None), (3, PostType.GAK, RefType.NONE, 1), (4, PostType.GAK, RefType.NONE, 2), (5, PostType.GAK, RefType.NONE, 3), (6, PostType.SUNSET, RefType.NONE, None), (7, PostType.TOMORROW, RefType.NONE, None), (8, PostType.WEEK, RefType.NONE, None), (9, PostType.EVENT, RefType.NONE, 1), (10, PostType.SEASON, RefType.ARTICLE, None), (11, PostType.TIP, RefType.ARTICLE, None), (12, PostType.QUOTE, RefType.NONE, None), (13, PostType.EVENT, RefType.NONE, 2), (14, PostType.EVENT, RefType.NONE, 3), (15, PostType.WEEKEND_PLAN, RefType.NONE, 1), # 이번 주말 첫째 날 (보통 토요일) (16, PostType.WEEKEND_PLAN, RefType.NONE, 2), (17, PostType.AIR, RefType.NONE, None), (18, PostType.DAY_TRIP, RefType.NONE, None), (19, PostType.MOON, RefType.NONE, None), (20, PostType.UV, RefType.NONE, None), ] # 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위. ORDER = { "morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE], "day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE], "evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE], "night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE], } _SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"} _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"} _FEED_TTL_MAX = 3600 _PARTIAL_TTL = 60 _SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용 _NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤 _RAIN_PROB = 40 _UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다 _HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸 _SUNSET_FULL = 60 _FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다 _COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19)) _RAIN_LOOK = ("umbrella", "☔ 우산 챙겨!") # 특보 종류 → (아이콘, 공유 문구 끝, 본문 한 줄) _WARNING_LOOK = { WarningType.RAIN: (*_RAIN_LOOK, "하천·저지대 근처는 피해 다녀요."), WarningType.TYPHOON: ("rain", "🌀 오늘은 집콕!", "창문 단단히 닫고 외출은 줄여요."), WarningType.SNOW: ("snow", "❄️ 눈길 조심!", "길이 미끄러우니 대중교통이 좋아요."), WarningType.HEAT: ("thermo", "🥵 물 자주 마시고 그늘로!", "낮 12시~5시엔 그늘에서 쉬어 가요."), WarningType.TROPICAL_NIGHT: ("muggy", "🥵 오늘 밤 시원하게 자!", "자기 전 미지근한 물로 씻으면 잠이 잘 와요."), WarningType.COLD: ("coldwind", "🥶 따뜻하게 껴입어!", "장갑·목도리 챙기고 수도관 얼지 않게 해요."), WarningType.WIND: ("coldwind", "🌬️ 바람 조심!", "간판·화분처럼 날아갈 물건을 조심해요."), WarningType.STORM_SURGE: ("coldwind", "🌊 바닷가 조심!", "바닷가·방파제엔 가지 마세요."), WarningType.HIGH_SEAS: ("coldwind", "🌊 바닷가 조심!", "바닷가·방파제엔 가지 마세요."), WarningType.DRY: ("fallen_leaf", "🔥 불조심!", "산·들에서 불 피우지 마세요."), WarningType.YELLOW_DUST: ("cloud", "😷 마스크 챙겨!", "마스크 쓰고 창문은 닫아 둬요."), } _AIR_STALE = timedelta(hours=3) # 등급 → (큰 줄, 공유 문구 끝) _AIR_LINE = { AirGrade.GOOD: ("공기 맑아요,\n창문 활짝 열어도 돼요", "🍃 환기하자!"), AirGrade.NORMAL: ("공기 무난해요,\n평소대로 다녀도 돼요", "🙂 괜찮대"), AirGrade.BAD: ("공기가 탁해요,\n마스크 챙겨요", "😷 마스크 챙겨!"), AirGrade.VERY_BAD: ("공기가 많이 탁해요,\n바깥은 짧게", "😷 오늘은 실내로!"), } _AIR_ADVICE = { AirGrade.BAD: "KF80 마스크 쓰고, 오래 뛰는 바깥 운동은 줄여요", AirGrade.VERY_BAD: "외출은 줄이고 창문은 닫아 둬요. 나가면 KF94 마스크", } _QUOTE_MOOD = {"rain": "비 오는 오늘", "cloud": "흐린 오늘", "clear": "맑은 오늘"} _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") def _pick(articles: list[Article], day: date) -> Optional[Article]: """날짜마다 돌아가며 하나씩.""" return articles[day.toordinal() % len(articles)] if articles else None def _discomfort_label(v: int) -> str: return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌" def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float]) -> HeroInput: temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else [] rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else [] ahead = [x for x in today.slots if x.row and x.at > now] if today else [] later = next((x.at for x in ahead if x.row.rain_type != RainType.NONE.value or x.row.rain_prob >= _HERO_RAIN_PROB), None) return HeroInput( now=now, night=slot in ("evening", "night"), rain_at=rainy[0].at if rainy else None, rain_later_at=later, today_known=bool(ahead), air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv, temp_min=min(temps, default=None), temp_max=max(temps, default=None), temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None, moon=phase_name(_tonight(now)), ) def feed_day(now: datetime) -> date: return (now - timedelta(hours=_FEED_DAY_START)).date() def slot_of(now: datetime, sunset_at: datetime) -> str: """아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다.""" h = now.hour if 5 <= h < 11: return "morning" if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET: return "day" if now < sunset_at - timedelta(hours=2) else "evening" return "night" def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int: """다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽.""" day = now.date() at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731 sunset = sunset_at.astimezone(KST) changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET, at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)] air = now.replace(minute=20, second=0, microsecond=0) changes.append(air if air > now else air + timedelta(hours=1)) nxt = min(c for c in changes if c > now) return max(60, min(_FEED_TTL_MAX, int((nxt - now).total_seconds()))) def _gak_key(item: IndexItem, hour: int) -> tuple[int, int, int]: """하기 좋은 시간이 가까운 각을 앞에, 오늘 시간이 지난 각을 뒤에.""" spans = [_span(w) for w in item.definition.windows or []] ahead = [(lo, hi) for lo, hi in spans if hi > hour] if not ahead: return 1, 0, item.rank return 0, min(max(0, lo - hour) for lo, _ in ahead), item.rank def _span(w: dict) -> tuple[int, int]: if w.get("around") == "sunset": return _SUNSET_HOUR - w.get("hours", 1), _SUNSET_HOUR + w.get("hours", 1) + 1 return w["from"], w["to"] def _weekends(days: list[DayPlan]) -> list[list[DayPlan]]: """예보가 있는 토·일을 주마다 묶는다. 다음 주말은 예보가 닿는 날(오늘+10일)부터 보인다.""" out: dict[date, list[DayPlan]] = {} for d in days: if d.day.weekday() >= 5: out.setdefault(d.day - timedelta(days=d.day.weekday()), []).append(d) return list(out.values()) def _spread(cards: list[PostData]) -> list[PostData]: """같은 종류가 붙으면 뒤에서 다른 종류를 당겨 끼운다.""" out = list(cards) for i in range(1, len(out)): if out[i].post_type is out[i - 1].post_type: j = next((k for k in range(i + 1, len(out)) if out[k].post_type is not out[i - 1].post_type), None) if j is not None: out.insert(i, out.pop(j)) return out def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime, has_warning: bool, seed: str = "") -> list[PostData]: """켜진 카드만 그 시간대 순서로 놓고, 행사 카드는 seed 로 정한 자리에 끼운다.""" order = list(ORDER[slot]) if slot == "evening" and now.weekday() == 4: order.remove(PostType.WEEK) order.insert(1, PostType.WEEK) if slot == "evening" and now >= sunset_at: order.remove(PostType.SUNSET) order.insert(2, PostType.SUNSET) pool: dict[PostType, list[PostData]] = {} for c in cards: pool.setdefault(c.post_type, []).append(c) # 특보는 히어로 바로 아래, 그다음 오늘 하루 날씨 head_types = [PostType.ALERT, PostType.WEATHER] if has_warning else [PostType.WEATHER] head = [pool[t].pop(0) for t in head_types if pool.get(t)] rest = _spread([pool[t].pop(0) for t in order if t not in head_types and pool.get(t)]) if slot == "night": rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE] events = pool.get(PostType.EVENT, []) gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True) for gap, e in zip(gaps, reversed(events[:len(gaps)])): rest.insert(gap, e) return head + rest def _top(i: IndexItem) -> TopIndex: d = i.definition return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary) async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType: """그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다.""" err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day)) if err is not ErrorType.SUCCESS: return err lineup = [x for x in LINEUP if x[0] not in made] if not lineup: return err _, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value)) _, tips = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.TIP.value)) refs = {PostType.SEASON: _pick(season or [], day), PostType.TIP: _pick(tips or [], day)} start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START) end = start + timedelta(days=1) rows = [] for position, post_type, ref_type, rank in lineup: ref = refs.get(post_type) if ref_type is RefType.ARTICLE and ref is None: continue rows.append({ "feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value, "ref_id": ref.article_id if ref is not None else None, "index_rank": rank, "published_at": start, "end_at": end, }) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.insert_day(s, rows)]) LOG.info(f"[feed] build {day} posts {len(rows)}: {err.name}") return err async def clear_feed_cache() -> None: try: keys = [k async for k in REDIS.conn.scan_iter("feed:*")] if keys: await REDIS.conn.delete(*keys) except RedisError as e: LOG.error(f"[feed] cache clear: {e}") class FeedService: def __init__( self, regions: RegionCRUD = Depends(RegionCRUD), crud: FeedCRUD = Depends(FeedCRUD), season_crud: SeasonCRUD = Depends(SeasonCRUD), weather_crud: WeatherCRUD = Depends(WeatherCRUD), weather: WeatherService = Depends(WeatherService), now_service: NowService = Depends(NowService), sky: SkyService = Depends(SkyService), index: IndexService = Depends(IndexService), week: WeekService = Depends(WeekService), season: SeasonService = Depends(SeasonService), ) -> None: self.regions, self.crud, self.season_crud, self.weather_crud = regions, crud, season_crud, weather_crud self.weather, self.now_service, self.sky, self.index, self.week, self.season = weather, now_service, sky, index, week, season async def feed(self, region_code: str) -> tuple[ErrorType, Optional[Res_Feed]]: err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) if err is not ErrorType.SUCCESS: return err, None if region is None: return ErrorType.NOT_FOUND, None now = now_kst() sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at slot = slot_of(now, sunset_at) key = f"feed:{region.code}:{slot}" try: cached = await REDIS.conn.get(key) if cached: return ErrorType.SUCCESS, Res_Feed.model_validate_json(cached) except RedisError as e: LOG.error(f"[feed] cache get: {e}") day = feed_day(now) async with redis_lock("lock:feed:build", ttl_sec=20): await build_feed_day(day, self.crud, self.season_crud) res, partial = await self._assemble(region, now, day, slot, sunset_at) try: await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at)) except RedisError as e: LOG.error(f"[feed] cache set: {e}") return ErrorType.SUCCESS, res async def _assemble(self, region: Region, now: datetime, day: date, slot: str, sunset_at: datetime) -> tuple[Res_Feed, bool]: """피드와 '일부 재료를 못 가져왔는지'. 빠진 피드는 짧게만 캐시해 다음 요청이 다시 채우게 한다.""" (err_t, today), (err_tm, tomorrow), (err_n, now_w), (err_s, sky), (err_i, board), (err_w, days), (err_e, events) = await asyncio.gather( self.weather.today(region.code), self.weather.today(region.code, now.date() + timedelta(days=1)), self.now_service.now(region.code), self.sky.view(region.code), self.index.board(region.code), self.week.week(region.code), self.week.events(region.code, None), ) partial = any(e is not ErrorType.SUCCESS for e in (err_t, err_tm, err_n, err_s, err_i, err_w, err_e)) today = today if err_t is ErrorType.SUCCESS else None tomorrow = tomorrow if err_tm is ErrorType.SUCCESS else None now_w = now_w if err_n is ErrorType.SUCCESS else None sky = sky if err_s is ErrorType.SUCCESS else None board = board if err_i is ErrorType.SUCCESS else None days = days if err_w is ErrorType.SUCCESS else [] events = events if err_e is ErrorType.SUCCESS else [] trip, trip_partial = await self._trip(region, now) partial = partial or trip_partial weekend = _weekends(days)[:1] suns = await asyncio.gather(*(self.weather.sun(region, d.day) for d in (weekend[0] if weekend else []))) sunsets = {x.sun_date: x.sunset_at for x in suns if x is not None} hour = now.replace(minute=0, second=0, microsecond=0) _, hourly = await DB_SESSION_MNG.execute_lambda( lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2))) ) _, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day)) _, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None)) by_article = {a.article_id: a for a in articles or []} quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value] ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, tomorrow=tomorrow, now_w=now_w, sky=sky, board=board, days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip, uv=await self._uv_today(region.code, now)) gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else [] cards = [] for p in posts or []: if PostType(p.post_type) is PostType.GAK: continue data = self._render(p, ctx) if data is not None: cards.append(data) gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0) for p, item in zip(gak_posts, gak): cards.append(self._gak(p, item)) has_warning = bool(now_w and now_w.warnings) items = board.items if board else [] feed = Res_Feed( region_code=region.code, region_name=region.name, slot=slot, hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour)), stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), bands=Bands( events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon, image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]], top5=[_top(i) for i in items[:5]], season=[ BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon) for a in articles or [] if a.category == ArticleCategory.SEASON.value ], ), ) return feed, partial async def _trip(self, region: Region, now: datetime) -> tuple[Optional[tuple[TripPick, list[EventItem]]], bool]: """당일치기 도시와 그날 그 도시 근처 행사, 그리고 재료를 못 가져왔는지. 주말 점수는 워커가 미리 계산해 둔 것만 쓴다.""" rank = WeekendRank() err, scores = await rank.scores(now, compute=False) if err is not ErrorType.SUCCESS: return None, True err, _, cities = await rank.targets() if err is not ErrorType.SUCCESS: return None, True pick = pick_trip(region, scores, cities, weekend_days(now.date())) if pick is None: return None, False err, items = await self.week.events(pick.city.code, None) if err is not ErrorType.SUCCESS: return (pick, []), True return (pick, pick_events(pick.best.day, items)), False async def _uv_today(self, region_code: str, now: datetime) -> list[OpenMeteoHourly]: """오늘 09~18시 3시간 칸 끝 시각의 자외선 (Open-Meteo).""" day = kst_midnight(now.date()) err, rows = await DB_SESSION_MNG.execute_lambda( lambda s: self.weather_crud.openmeteo_between(s, region_code, day + timedelta(hours=9), day + timedelta(hours=18)) ) return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else [] async def _uv(self, region_code: str, hour: datetime) -> Optional[float]: err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour)) if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None: return None return float(rows[0].uv_index) def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard], today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero: top = board.items[0] if board and board.items else None bubble = None if top is not None: bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요" return Hero( now_at=now, sky_mode=_SKY_MODE[slot], temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None, rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None, weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble, moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100), stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv))], ) @staticmethod def _base(p: Post) -> dict: return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count, published_at=p.published_at.astimezone(KST)) def _gak(self, p: Post, i: IndexItem) -> PostData: d = i.definition return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i), slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)], share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"]) def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]: """카드 하나를 그 구 데이터로 채운다. 켜질 조건이 안 맞거나 채울 데이터가 없으면 None.""" base = self._base(p) t = PostType(p.post_type) if t is PostType.WEATHER and c.today is not None: days = [("오늘 하루", c.today)] + ([("내일", c.tomorrow)] if c.tomorrow is not None else []) slides = [HoursSlide(kind="hours", eyebrow=f"{label} · 3시간마다", line=w.headline, hours=[ HourCell(label=f"{x.at.astimezone(KST).hour}시", icon=x.icon, temp_c=float(x.row.temp_c) if x.row else None, tone=x.tone) for x in w.slots ]) for label, w in days] caption = (c.now_w.rain_2h_text if c.now_w else None) or "3시간마다 바뀌는 하늘을 넘겨 보세요" return PostData(**base, title="오늘·내일 날씨", icon=c.today.slots[4].icon, caption=caption, slides=slides, share_messages=[f"{c.region.short_name} 오늘 날씨: {c.today.headline}"]) if t is PostType.ALERT: return self._alert(base, c) if t is PostType.AIR: return self._air(base, c) if t is PostType.SUNSET and c.sky is not None: return self._sunset(base, c) if t is PostType.TOMORROW and c.now_w is not None: return self._tomorrow(base, c) if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles: a = c.articles[p.ref_id] return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0], slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title]) if t is PostType.EVENT: soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()]) rank = p.index_rank or 1 if len(soon) < rank: return None e = soon[rank - 1] rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))] caption = _event_caption(e) return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption, slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))], share_messages=[f"{e.event.name} 같이 갈래?"]) if t is PostType.WEEK and c.days: weekends = _weekends(c.days) if not weekends: return None slides = [] for label, w in zip(("이번 주말", "다음 주말"), weekends): f = forecast(w) slides.append(WeekSlide(kind="week", eyebrow=f"{label} · {day_range(w[0].day, w[-1].day)}", line=f.line, tip=f.tip, days=[ WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob) for d in w ])) first = forecast(weekends[0]) return PostData(**base, title="이번 주말 예보", icon="calendar", caption=first.caption, slides=slides, share_messages=["이번 주말 같이 놀자 🙌"]) if t is PostType.WEEKEND_PLAN and c.days: return self._weekend_plan(base, c, p.index_rank or 1) if t is PostType.QUOTE: return self._quote(base, c) if t is PostType.DAY_TRIP and c.trip is not None: return self._day_trip(base, *c.trip) if t is PostType.MOON: return self._moon(base, c) if t is PostType.UV: return self._uv_post(base, c) return None def _moon(self, base: dict, c: "_Ctx") -> PostData: """오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·밝기와 다음 보름. 피드 아래쪽에 둔다.""" tonight = _tonight(c.now) start = tonight.replace(hour=12) full, new = nearest(tonight, True).astimezone(KST), nearest(tonight, False).astimezone(KST) at, is_full = (full, True) if start <= full < start + timedelta(days=1) else (new, False) if start <= new < start + timedelta(days=1) else (None, False) row = next((h for h in c.hourly if h.forecast_at.astimezone(KST) == tonight), None) sky = Sky(row.sky) if row is not None else None rows = [Row(label="밤 하늘", value=_MOON_SKY[sky])] if sky is not None else [] eyebrow = f"오늘 밤 달 · {c.region.short_name}" if at is None: name, pct = phase_name(tonight), round(illumination(tonight) * 100) nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full nxt = nxt.astimezone(KST) waxing = name in ("초승달", "상현달", "차오르는 달") caption = ("구름이 많아 달은 숨바꼭질해요." if sky is Sky.CLOUDY else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨") return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption, slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n밝기 {pct}%", icon="moon", rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])], share_messages=[f"오늘 밤은 {name}이래 🌙"]) when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}" if is_full: line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요" caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY else "소원 빌기 딱 좋은 밤이에요 🌕" return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption, slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="달 밝기", value="100%"), *rows])], share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"]) stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None) if stars is not None: rows.append(Row(label="별보기각", value=f"{stars.score.score}점")) caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨" return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption, slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=[Row(label="달 밝기", value="0%"), *rows])], share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"]) def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData: """1~2시간 거리 후보 도시 중 이번 주말 나들이 점수 1위. 첫 장은 도시·날씨, 뒤로 그날 그곳 행사 최대 2장.""" b = pick.best when = f"{_WEEKDAY_KO[b.day.weekday()]}요일" rows = [Row(label="거리", value=f"여기서 약 {pick.distance_km}km"), Row(label="예상 날씨" if b.estimated else "날씨", value=b.reason)] if b.temp_min_c is not None and b.temp_max_c is not None: rows.append(Row(label="기온", value=f"{round(b.temp_min_c)}~{round(b.temp_max_c)}°")) if pick.note: rows.append(Row(label="볼거리", value=pick.note)) slides = [RowsSlide(kind="rows", eyebrow=f"당일치기 · {when} {short_day(b.day)}", line=f"{when}엔 {pick.label},\n나들이 {b.score}점", icon=b.icon, rows=rows)] for e in events: ev_rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))] slides.append(RowsSlide(kind="rows", eyebrow=f"{pick.label} 근처 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=ev_rows, image=e.event.image_url, image_credit=image_credit(e.event))) if pick.runner_up is not None: label, x = pick.runner_up caption = f"다음은 {label}, {_WEEKDAY_KO[x.day.weekday()]}요일 {x.score}점이에요." else: caption = "아침 일찍 출발하면 하루가 넉넉해요." return PostData(**base, title=f"{pick.label} 당일치기", icon=b.icon, caption=caption, slides=slides, share_messages=[f"{when} {pick.label} 당일치기 어때? 나들이 {b.score}점이래 🚗"]) def _weekend_plan(self, base: dict, c: "_Ctx", nth: int) -> Optional[PostData]: """이번 주말 nth 번째 날의 시간대별 동선.""" weekends = _weekends(c.days) if not weekends or len(weekends[0]) < nth: return None used: frozenset[int] = frozenset() for prev in weekends[0][:nth - 1]: used |= {e.event.event_id for e in pick_events(prev.day, c.events, used)} d = weekends[0][nth - 1] nxt = next((x for x in c.days if x.day == d.day + timedelta(days=1)), None) card = day_plan(d, c.sunsets.get(d.day), pick_events(d.day, c.events, used), nxt.temp_min_c if nxt else None) return PostData(**base, title=f"{d.weekday}요일 플랜", icon="calendar", caption=card.caption, slides=[PlanSlide(kind="plan", eyebrow=card.eyebrow, line=card.line, steps=[ PlanStep(time=x.time, icon=x.icon, title=x.title, sub=x.sub, image=x.image, image_credit=x.image_credit) for x in card.steps ])], share_messages=[f"{d.weekday}요일 이렇게 놀자! {card.line.splitlines()[0].rstrip(',')}"]) def _alert(self, base: dict, c: "_Ctx") -> Optional[PostData]: """오늘 남은 시간·내일 출퇴근에 비 확률 40% 이상이거나 특보가 있을 때만 켠다.""" tomorrow = c.now.date() + timedelta(days=1) later = [r for r in c.hourly if r.forecast_at > c.now and r.forecast_at.astimezone(KST).date() == c.now.date() and r.rain_prob >= _RAIN_PROB] commute = [(label, r) for r in c.hourly for label, h in _COMMUTE_HOURS if r.forecast_at.astimezone(KST).date() == tomorrow and r.forecast_at.astimezone(KST).hour == h and r.rain_prob >= _RAIN_PROB] warnings = (c.now_w.warnings or []) if c.now_w else [] if not (later or commute or warnings): return None rows = [Row(label="특보", value=w.text) for w in warnings] if later: rows.append(Row(label="오늘", value=f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}부터 비 {later[0].rain_prob}%")) rows += [Row(label=label, value=f"비 {r.rain_prob}%") for label, r in commute] probs = [r.rain_prob for r in later] + [r.rain_prob for _, r in commute] rain_tip = "큰 우산이 든든해요." if probs and max(probs) >= 60 else "접는 우산이면 충분해요." icon, tail, caption = _WARNING_LOOK[warnings[0].warning_type] if warnings else (*_RAIN_LOOK, rain_tip) if warnings: title, line = warnings[0].text, "바깥 활동 전에 꼭 확인하세요" elif later: title, line = "우산 챙겨요", f"{hour_label(later[0].forecast_at.astimezone(KST).hour)}쯤 비 소식이 있어요" else: title, line = "내일 우산 챙겨요", f"{commute[0][0]}에 비 소식이 있어요" return PostData(**base, title=title, icon=icon, caption=caption, slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon=icon, rows=rows)], share_messages=[f"{line} {tail}"]) def _uv_post(self, base: dict, c: "_Ctx") -> Optional[PostData]: """오늘 낮 자외선. 가장 셀 때가 '보통'(3) 아래면 챙길 게 없어 끈다.""" if not c.uv: return None peak = max(c.uv, key=lambda r: r.uv_index) top = float(peak.uv_index) if top < _UV_SHOW: return None label = uv_label(top) at = peak.forecast_at.astimezone(KST) rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv] high = top >= UV_HIGH if high: rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요")) line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림") return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}", slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)], share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"]) def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]: """가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다.""" air = c.now_w.air if c.now_w else None if air is None or c.now - air.measured_at > _AIR_STALE: return None values = [(name, v, g) for name, v, g in (("초미세먼지", air.pm25, pm25_grade(air.pm25)), ("미세먼지", air.pm10, pm10_grade(air.pm10))) if g] if not values: return None worst = max(g for _, _, g in values) label = AIR_GRADE_LABEL[worst] rows = [Row(label=name, value=f"{v}㎍/㎥ · {AIR_GRADE_LABEL[g]}") for name, v, g in values] if worst in _AIR_ADVICE: rows.append(Row(label="이렇게 해요", value=_AIR_ADVICE[worst])) line, tail = _AIR_LINE[worst] icon = "vent" if worst <= AirGrade.NORMAL else "cloud" return PostData(**base, title=f"미세먼지 {label}", icon=icon, caption=f"{air.station_name} 측정소 · {air.measured_at.astimezone(KST).hour}시 기준", slides=[RowsSlide(kind="rows", eyebrow=f"지금 공기 · {c.region.short_name}", line=line, icon=icon, rows=rows)], share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"]) def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]: """해 지기 전엔 오늘, 진 뒤엔 내일 노을. 하늘 상황으로 말하고, '쉬어요'면 한 줄 카드.""" after = c.now >= c.sunset_at target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset if target is None: return None when = "내일" if after else "오늘" sit = SkySituation(target.situation) if target.situation else None line = SITUATION_LINE[sit] if sit else GRADE_LABEL[SkyGrade(target.grade)] better = sky_outlook(target, c.sky.days, c.now.date()) sun = next((b for b in target.best_times if b["kind"] == "sun"), target.best_times[0]) sun_at = datetime.fromisoformat(sun["at"]).astimezone(KST) if day_verdict(target) == "rest": return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=f"{line}." + (f" {better}" if better else ""), slides=[], share_messages=[f"{when} 노을은 쉬어요, {line}"]) cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"] slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=line, score=target.score, grade_label=line, cuts=cuts, situation=sit)] if c.sky.spots: slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {compass(c.sky.sunset_azimuth)}쪽", icon="sunset", rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{compass(x.direction)} {x.distance_km}km", place=x.spot.name) for n, x in enumerate(c.sky.spots)])) caption = better or "보통 해 진 뒤 10~20분이 가장 붉어요." return PostData(**base, title=f"{when} 노을 · {line}", icon="sunset", caption=caption, slides=slides, share_messages=[f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요"]) def _tomorrow(self, base: dict, c: "_Ctx") -> PostData: tomorrow = c.now.date() + timedelta(days=1) rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute] best = None for i in c.board.items if c.board else []: s = next((x for x in i.trend if x.score_date == tomorrow), None) if s is not None and (best is None or s.score > best[1].score): best = (i, s) if best is not None: rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점")) caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요." icon = c.now_w.commute[0].icon if c.now_w.commute else "sun" return PostData(**base, title="내일 미리보기", icon=icon, caption=caption, slides=[RowsSlide(kind="rows", eyebrow=f"내일 · {c.region.short_name}", line=c.now_w.tomorrow_text, icon=icon, rows=rows)], share_messages=[c.now_w.tomorrow_text]) def _quote(self, base: dict, c: "_Ctx") -> Optional[PostData]: """오늘 날씨에 맞는 문장. 코드 앞머리(quote-rain-·quote-cloud-·quote-clear-·quote-night-·quote-any-)로 고른다.""" icons = [x.icon for x in c.today.slots] if c.today else [] weather = "rain" if any(i in ("rain", "snow") for i in icons) else "cloud" if icons.count("cloud") * 2 >= len(icons or [0]) else "clear" prefixes = [f"quote-{weather}-", "quote-any-"] + (["quote-night-"] if c.slot == "night" else []) pool = [a for a in c.quotes if a.code.startswith(tuple(prefixes))] a = _pick(pool, c.now.date()) if a is None: return None rows = [Row(label="출처", value=a.body[1])] if len(a.body) > 1 else [] mood = "잠들기 전" if a.code.startswith("quote-night-") else _QUOTE_MOOD[weather] return PostData(**base, title=a.title, icon=a.icon, caption=f"{mood}에 어울리는 한 문장이에요.", slides=[RowsSlide(kind="rows", eyebrow="오늘의 한 문장", line=a.body[0], icon=a.icon, rows=rows)], share_messages=[a.body[0]]) def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]: """seed 의 점수 구간 설명 {"0": …, "30": …, "60": …, "80": …} 중 점수가 들어가는 구간 문장.""" lo = next((x for x in sorted((int(k) for k in sentences or {}), reverse=True) if score >= x), None) return sentences[str(lo)] if lo is not None else None def _gak_caption(i: IndexItem) -> str: """점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간).""" band = _band_sentence(i.definition.sentences, i.score.score) nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None) if nxt is not None: diff = nxt.score - i.score.score how = "비슷해요" if abs(diff) < 5 else f"오늘보다 {abs(diff)}점 {'높아요' if diff > 0 else '낮아요'}" tail = f"내일은 {nxt.score}점, {how}." else: spans = [_span(w) for w in i.definition.windows or []] tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요." return f"{band} {tail}" if band else tail def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]: """내일 낮 최고기온을 오늘과 견준 한 줄.""" highs = [max((float(x.row.temp_c) for x in w.slots if x.row), default=None) if w else None for w in (today, tomorrow)] if None in highs: return None diff = round(highs[1] - highs[0]) if abs(diff) < 2: return f"내일 낮 최고 {round(highs[1])}°, 오늘이랑 비슷해요." return f"내일 낮 최고 {round(highs[1])}°, 오늘보다 {abs(diff)}° {'더워요' if diff > 0 else '쌀쌀해요'}." def _event_caption(e: EventItem) -> str: """진행 상태·거리·그날 날씨 중 있는 것. 다 없으면 일정 확정 여부.""" parts = ["지금 진행 중" if e.status == "live" else e.status_label] if e.distance_km is not None: parts.append(f"여기서 {round(e.distance_km)}km") if e.fit: parts.append(e.fit) if len(parts) > 1 or e.status == "live": return " · ".join(parts) return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요." _MOON_SKY = {Sky.CLEAR: "맑음, 잘 보여요", Sky.PARTLY: "구름 조금, 사이사이 보여요", Sky.CLOUDY: "흐림, 가려질 수 있어요"} def _tonight(now: datetime) -> datetime: """'오늘 밤' 22시. 피드 하루(03:00 시작)와 맞춰, 자정~03시는 전날 밤으로 본다.""" return datetime.combine(feed_day(now.astimezone(KST)), time(22), tzinfo=KST) @dataclass class _Ctx: region: Region now: datetime slot: str sunset_at: datetime today: Optional[TodayWeather] tomorrow: Optional[TodayWeather] now_w: Optional[NowWeather] sky: Optional[SkyView] board: Optional[IndexBoard] days: list[DayPlan] events: list[EventItem] sunsets: dict[date, datetime] hourly: list[WeatherHourly] articles: dict[int, Article] quotes: list[Article] trip: Optional[tuple[TripPick, list[EventItem]]] = None uv: list[OpenMeteoHourly] = field(default_factory=list) # 오늘 낮 3시간 칸 자외선