Files
o2o-weather/backend/services/feed_service.py
T
minaChoi 14ddebd040 feat: 10/6 회의 반영 — 각 점수 하향, 주말 카드 매일·다음 주말, 일반구를 시로 합침
- 각 점수: 편한 범위 안에서도 최적값에서만 100, 가장 나쁜 요인이 전체를 끌어내림
- 피드 노을 시간대 각 정렬 오류 수정
- 주말 카드 매일 노출, 예보가 닿으면 다음 주말 슬라이드 추가, 주말·행사 탭 열흘
- 지역 256→230 (일반구 39개를 시 13개로)
- 회의 기록과 TODO.md 추가
2026-10-06 09:57:25 +09:00

457 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import asyncio
from dataclasses import dataclass
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, Post, Region, WeatherHourly
from common.enums import ArticleCategory, ErrorType, PostType, RefType, SkyGrade
from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
from common.utils.text import hour_label, ieyo, month_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, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
TopIndex, WeekDay, WeekSlide,
)
from services.calc.sky_score import GRADE_LABEL
from services.calc.sun import sun_times
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
from services.weather_service import TodayWeather, WeatherService
from services.week_service import DayPlan, EventItem, WeekService
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드기획_v2.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, None),
(10, PostType.SEASON, RefType.ARTICLE, None),
(11, PostType.TIP, RefType.ARTICLE, None),
(12, PostType.QUOTE, RefType.NONE, None),
]
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다.
ORDER = {
"morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.EVENT, PostType.QUOTE],
"day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.EVENT, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.EVENT, 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
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
_RAIN_PROB = 40
_SUNSET_FULL = 60
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
_COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
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 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시간 전–21 · 밤 21–05."""
h = now.hour
if 5 <= h < 11:
return "morning"
if 11 <= h < 21:
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, at(day, 21),
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) -> list[PostData]:
"""켜진 카드만 그 시간대 순서로 놓는다."""
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]
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, exists = await DB_SESSION_MNG.execute_lambda(lambda s: crud.has_day(s, day))
if err is not ErrorType.SUCCESS or exists:
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 = await self._assemble(region, now, day, slot, sunset_at)
try:
await REDIS.conn.set(key, res.model_dump_json(), ex=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) -> Res_Feed:
(err_t, today), (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.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),
)
today = today if err_t 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 []
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, now_w=now_w, sky=sky, board=board,
days=days, events=events, hourly=hourly or [], articles=by_article, quotes=quotes)
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 []
return 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),
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning),
bands=Bands(
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon) for e in 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
],
),
)
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard]) -> 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,
)
@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=f"{i.score.summary}. 오늘의 각 {i.rank}위는 {ieyo(d.name)}.",
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:
slides = [HoursSlide(kind="hours", eyebrow="오늘 하루 · 3시간마다", line=c.today.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 c.today.slots
])]
if c.now_w is not None and c.now_w.air is not None and c.now_w.air_text:
slides.append(RowsSlide(kind="rows", eyebrow="미세먼지", line=c.now_w.air_text, icon="vent", rows=[
Row(label="초미세먼지", value=str(c.now_w.air.pm25) if c.now_w.air.pm25 is not None else "-"),
Row(label="미세먼지", value=str(c.now_w.air.pm10) if c.now_w.air.pm10 is not None else "-"),
Row(label="측정소", value=c.now_w.air.station_name),
]))
return PostData(**base, title="오늘 하루의 날씨", icon=c.today.slots[4].icon, caption=c.today.headline, 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.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 = [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()]
if not soon:
return None
e = soon[0]
rows = [Row(label="장소", value=e.event.place_name), Row(label="기간", value=f"{e.event.start_date:%m.%d}~{e.event.end_date:%m.%d}")]
if e.fit:
rows.append(Row(label="그날 날씨", value=e.fit))
caption = f"{month_day(e.event.start_date)}부터 {month_day(e.event.end_date)}까지예요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=f"{c.region.name.split()[0]} 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows)],
share_messages=[f"{e.event.name} 같이 갈래?"])
if t is PostType.WEEK and c.days:
weekends = _weekends(c.days)
if not weekends:
return None
first = weekends[0]
return PostData(**base, title="이번 주말 추천", icon="calendar", caption=" ".join(f"{d.weekday}요일은 {d.pick}." for d in first),
slides=[WeekSlide(kind="week", eyebrow=f"{label} · {c.region.short_name}", line=w[0].pick, days=[
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline) for d in w
]) for label, w in zip(("이번 주말", "다음 주말"), weekends)], share_messages=["이번 주말 같이 놀자 🙌"])
if t is PostType.QUOTE:
return self._quote(base, c)
return None
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]
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="umbrella", caption=line,
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon="umbrella", rows=rows)],
share_messages=[f"{line} ☔ 우산 챙겨!"])
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
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 "오늘"
grade = GRADE_LABEL[SkyGrade(target.grade)]
if target.score < _SUNSET_FULL:
nxt = None if after else next((x for x in c.sky.days if x.score_date > c.now.date()), None)
caption = "구름에 가려요." + (f" 내일 노을 {nxt.score}점이에요." if nxt is not None else "")
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=caption, slides=[],
share_messages=[f"{when} 노을은 구름에 가려요"])
peak = next((b for b in target.best_times if b["kind"] == "peak"), target.best_times[0])
peak_at = datetime.fromisoformat(peak["at"]).astimezone(KST)
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, 서쪽이 가장 붉어요", score=target.score,
grade_label=grade, cuts=[Cut(**b) for b in target.best_times])]
if c.sky.spots:
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 쪽 {c.sky.sunset_azimuth}°, 서쪽이 트인 곳", icon="sunset",
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{x.distance_km}km") for n, x in enumerate(c.sky.spots)]))
return PostData(**base, title=f"{when} 노을 {target.score}", icon="sunset", caption=f"{grade}. {peak_at:%H:%M}쯤이 가장 예뻐요.",
slides=slides, share_messages=[f"{when} 노을 {target.score}점이래 🌇 {peak_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)
caption = c.now_w.tomorrow_text + "."
if best is not None:
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}"))
caption += f" 내일 1위는 {ieyo(best[0].definition.name)}."
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 []
return PostData(**base, title=a.title, icon=a.icon, caption=a.body[0],
slides=[RowsSlide(kind="rows", eyebrow="오늘의 한 문장", line=a.body[0], icon=a.icon, rows=rows)], share_messages=[a.body[0]])
@dataclass
class _Ctx:
region: Region
now: datetime
slot: str
sunset_at: datetime
today: Optional[TodayWeather]
now_w: Optional[NowWeather]
sky: Optional[SkyView]
board: Optional[IndexBoard]
days: list[DayPlan]
events: list[EventItem]
hourly: list[WeatherHourly]
articles: dict[int, Article]
quotes: list[Article]