import asyncio import random import re 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, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType from common.logger import LOG from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, 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, HeroTomorrow, HourCell, HoursSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide, PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide, ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import pm10_grade, pm25_grade from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of from services.calc.index_calc import rank_score from services.calc.moon import MoonNight, nearest, night, view_line from services.calc.sky_score import GRADE_LABEL, sky_title from services.calc.sun import sun_times from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level 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.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), (21, PostType.HERO, RefType.NONE, None), (22, PostType.TODAY_GAK, RefType.NONE, None), ] # 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리 _PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"} # 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다. NATIONAL_SCOPE = "00" NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON}) def sido_of(region_code: str) -> str: """구 행정코드의 시도 부분(앞 2자리).""" return region_code[:2] def post_scope(post_type: PostType, region_code: str) -> str: return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code) # 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위. # 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로. ORDER = { "morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE], "day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE], "evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE], "night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, 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 # 노을 시간대 각의 대략적인 순서용 _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_RAIN_LINE = ("공기는 맑은데 비가 와요,\n창문은 닫아 둬요", "☔ 창문은 닫아 둬!") # 맑음·보통인데 지금~2시간 안에 비 _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 _hero_input( now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str], ) -> 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"), after_dark=slot == "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, pm25=now_w.air.pm25 if now_w and now_w.air else None, pm10=now_w.air.pm10 if now_w and now_w.air else None, 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, moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None, ) def feed_day(now: datetime) -> date: return (now - timedelta(hours=_FEED_DAY_START)).date() 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), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY, now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)] 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, []) front = range(1, max(1, len(rest) // 2 + 1)) gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True) for gap, e in zip(gaps, reversed(events[:len(gaps)])): rest.insert(gap, e) return head + rest def _by_position(posts: list[Post]) -> list[Post]: """번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다).""" out: dict[int, Post] = {} for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)): out.setdefault(p.position, p) return list(out.values()) def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]: """내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순).""" best = None for i in board.items: s = next((x for x in i.trend if x.score_date == day), None) if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)): best = (i, s) return best def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow: best = _tomorrow_best(board, day) top1 = None if best is not None: d, s = best[0].definition, best[1] top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary) return HeroTomorrow( day=day, weather_slots=board.tomorrow_slots, top1=top1, weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()}, ) 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, active=i.active, slots=i.slots, slot_ranks=i.slot_ranks) async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType: """그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다. 전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 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 err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s)) if err is not ErrorType.SUCCESS: return err sidos = sorted({sido_of(r.code) for r in all_regions}) lineup = [ (scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos) if (scope, x[0]) not in made and (NATIONAL_SCOPE, 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 scope, 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, "scope": scope, "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}:priority-score-v4:{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, self.regions) res, partial = await self._assemble(region, now, day, slot, sunset_at) # 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다 if not res.bands.top5: return ErrorType.SUCCESS, res 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, [NATIONAL_SCOPE, sido_of(region.code)])) posts = _by_position(posts or []) _, 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.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else [] cards = [] pinned = {_PINNED[PostType(p.post_type)]: PostReaction(post_id=p.post_id, like_count=p.like_count, comment_count=p.comment_count) for p in posts or [] if PostType(p.post_type) in _PINNED} for p in posts or []: if PostType(p.post_type) is PostType.GAK or PostType(p.post_type) in _PINNED: 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 = [i for i in board.items if i.in_season] 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), _moon_view(region, now, hourly or [])), stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned, 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 board.ranked[:5]] if board else [], season=[ BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon, image=a.image_url, image_credit=a.image_credit) 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]: """지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다.""" err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour)) rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else [] return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None 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, moon: Optional[tuple[MoonNight, str]] = None) -> Hero: top = board.ranked[0] if board and board.ranked else None bubble = None if top is not None: bubble = f"지금은 {top.definition.name}!" if top.score.score >= 70 else "지금은 쉬어 가요" x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None) 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, humidity=cur.humidity 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, weather_slots=board.weather_slots if board else {}, weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.weather_why.items()} if board else {}, top1=_top(top) if top else None, bubble=bubble, moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None, stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)], status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone, detail=x.detail) for x in hero_status(x_in)], tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None, ) @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, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))], 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, image=a.image_url, image_credit=a.image_credit)], 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, gaks=_day_gaks(c.board, d.day)) 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) m, view = _moon_view(c.region, c.now, c.hourly) 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=label, value=_clock_word(t)) for label, t in (("달 뜸", m.rise_at), ("달 짐", m.set_at)) if t is not None] eyebrow = f"오늘 밤 달 · {c.region.short_name}" if at is None: name = m.name nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full nxt = nxt.astimezone(KST) waxing = name in ("초승달", "상현달", "차오르는 달") # 본문(잘 보이는지)과 어긋나지 않게: 안 보이는 밤·흐린 밤은 그 이유에 맞춰서 caption = ("달이 없는 만큼 별은 더 잘 보여요 ✨" if "안 보여요" in view else "구름 사이로 잠깐씩 보일 수도 있어요." if view.startswith("흐려서") else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨") return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption, slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", 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 view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕" return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption, slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="보이는지", value=view), *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=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=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv] when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵" todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요" line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}" return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}", 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=AIR_GRADE_LABEL[g]) for name, _, g in values] if worst in _AIR_ADVICE: rows.append(Row(label="이렇게 해요", value=_AIR_ADVICE[worst])) raining = worst <= AirGrade.NORMAL and c.now_w.will_rain_2h line, tail = _AIR_RAIN_LINE if raining else _AIR_LINE[worst] icon = "umbrella" if raining else "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]: """노을 탭 결론과 같은 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을. 노을 탭 히어로와 같은 문장, 안 볼 만한 날은 한 줄 카드.""" plan = c.sky.plan if plan is None: return None target, when, rise = plan.target, plan.when, plan.kind is SkyType.SUNRISE word, icon = ("일출", "sun") if rise else ("노을", "sunset") sit = SkySituation(target.situation) if target.situation else None line = plan.situation_label or "" # 보이는 날만 그날 하늘 한 줄 better = plan.outlook if day_verdict(target) == "rest" or SkyGrade(target.grade) is SkyGrade.GRAY: # 거의 안 보이는 날은 한 줄 카드 return PostData(**base, size="line", title=plan.title, icon=icon, caption=" ".join(filter(None, [line and f"{line}.", better])), slides=[], share_messages=[plan.title]) cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"] slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} {word} · {c.region.name}", line=line, score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)], cuts=cuts, situation=sit, headline=sky_title(SkyGrade(target.grade), plan.kind, None, plan.best_at), peak_at=plan.best_at)] if c.sky.spots and not rise: 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분 전이 가장 붉어요." if rise else "보통 해 진 뒤 10~20분이 가장 붉어요.") share = f"{plan.title} {'🌅' if rise else '🌇'}" return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share]) def _tomorrow(self, base: dict, c: "_Ctx") -> PostData: rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute] best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None 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 # 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다 _AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"} _NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "} def gak_rows(i: IndexItem, n: int = 4) -> list[Row]: """비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m).""" d, notes = i.definition, i.score.notes or {} weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}")) axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)] rows = [] for a in axes[:n]: head, _, tail = notes[a].partition(", ") prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None if prob: value = prob.group(0) elif a == "air" and tail: value = tail else: value = head.removeprefix(_NOTE_HEAD.get(a, "")) rows.append(Row(label=_AXIS_NAME[a], value=value)) return rows def _gak_caption(i: IndexItem) -> str: """슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다.""" 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 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 "올해 정확한 일정은 공식 안내로 확인해 주세요." _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0} def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]: """그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로.""" scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day] scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True) return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]] def _moon_view(region: Region, now: datetime, hourly: list[WeatherHourly]) -> tuple[MoonNight, str]: """오늘 밤 달과 잘 보이는지 한 마디. 구름은 달이 떠 있는 시각의 시간별 예보 하늘로 본다.""" day = feed_day(now.astimezone(KST)) m = night(day, float(region.lat), float(region.lon)) start = kst_midnight(day) by_at = {h.forecast_at: h for h in hourly} skies = [_CLOUDY[Sky(r.sky)] for h in m.up_hours if (r := by_at.get(start + timedelta(hours=h))) is not None] return m, view_line(m, sum(skies) / len(skies) if skies else None) def _clock_word(at: datetime) -> str: h = at.astimezone(KST).hour return f"{'새벽' if h < 6 else '밤' if h >= 21 or h == 0 else '저녁'} {h % 12 or 12}시 {at.astimezone(KST).minute:02d}분" 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시간 칸 자외선