feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?' - 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준 - 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수 - 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리 - 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정 - 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성 - 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시 - 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집 - 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
This commit is contained in:
1 parent
296a09d6db
commit
ddf05aeb5c
97 files changed
+5475
-720
No files matched your search
@@ -11,18 +11,20 @@ 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.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, SkyGrade, 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 hour_label, ieyo, month_day
|
||||
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, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
TopIndex, WeekDay, WeekSlide,
|
||||
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.sky_score import GRADE_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
@@ -30,7 +32,9 @@ 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
|
||||
from services.week_service import DayPlan, EventItem, WeekService, image_credit
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days
|
||||
|
||||
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드기획_v2.html).
|
||||
LINEUP = [
|
||||
@@ -48,13 +52,17 @@ LINEUP = [
|
||||
(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),
|
||||
]
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, 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.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: "한 문장"}
|
||||
@@ -65,6 +73,35 @@ _RAIN_PROB = 40
|
||||
_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]:
|
||||
@@ -169,9 +206,12 @@ def _top(i: IndexItem) -> TopIndex:
|
||||
|
||||
|
||||
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:
|
||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 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))
|
||||
@@ -179,7 +219,7 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||
end = start + timedelta(days=1)
|
||||
rows = []
|
||||
for position, post_type, ref_type, rank in LINEUP:
|
||||
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
|
||||
@@ -248,17 +288,23 @@ class FeedService:
|
||||
|
||||
async def _assemble(self, region: Region, now: datetime, day: date, slot: str, sunset_at: datetime) -> tuple[Res_Feed, bool]:
|
||||
"""피드와 '일부 재료를 못 가져왔는지'. 빠진 피드는 짧게만 캐시해 다음 요청이 다시 채우게 한다."""
|
||||
(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),
|
||||
(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_n, err_s, err_i, err_w, err_e))
|
||||
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)))
|
||||
@@ -267,8 +313,8 @@ class FeedService:
|
||||
_, 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)
|
||||
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)
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
@@ -288,7 +334,8 @@ class FeedService:
|
||||
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, 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) for e in events[:4]],
|
||||
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 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)
|
||||
@@ -298,6 +345,23 @@ class FeedService:
|
||||
)
|
||||
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
|
||||
|
||||
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
|
||||
@@ -318,28 +382,26 @@ class FeedService:
|
||||
|
||||
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)}.",
|
||||
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}이래"])
|
||||
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,
|
||||
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:
|
||||
@@ -354,26 +416,70 @@ class FeedService:
|
||||
if len(soon) < rank:
|
||||
return None
|
||||
e = soon[rank - 1]
|
||||
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 "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
rows = ([Row(label="장소", value=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"{c.region.name.split()[0]} 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows)],
|
||||
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
|
||||
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=["이번 주말 같이 놀자 🙌"])
|
||||
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)
|
||||
return None
|
||||
|
||||
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)] 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)
|
||||
@@ -387,15 +493,37 @@ class FeedService:
|
||||
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="umbrella", caption=line,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon="umbrella", rows=rows)],
|
||||
share_messages=[f"{line} ☔ 우산 챙겨!"])
|
||||
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 _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]:
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
|
||||
@@ -412,12 +540,15 @@ class FeedService:
|
||||
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,
|
||||
side = compass(c.sky.sunset_azimuth)
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, {side}쪽이 가장 붉어요", 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",
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {side}쪽이 트인 곳", 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}쯤이 가장 예뻐요.",
|
||||
nxt = next((x for x in c.sky.days if x.score_date > target.score_date), None)
|
||||
caption = f"{'모레' if after else '내일'} 노을은 {nxt.score}점이에요." if nxt is not None else "가장 붉은 때 앞뒤 20분이 골든타임이에요."
|
||||
return PostData(**base, title=f"{when} 노을 {target.score}점", icon="sunset", caption=caption,
|
||||
slides=slides, share_messages=[f"{when} 노을 {target.score}점이래 🌇 {peak_at:%H:%M}에 같이 볼래?"])
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
@@ -428,10 +559,9 @@ class FeedService:
|
||||
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)}."
|
||||
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)],
|
||||
@@ -447,10 +577,45 @@ class FeedService:
|
||||
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],
|
||||
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 _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 '낮아요'}"
|
||||
return f"내일은 {nxt.score}점, {how}."
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
return f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
|
||||
|
||||
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 "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Ctx:
|
||||
region: Region
|
||||
@@ -458,11 +623,14 @@ class _Ctx:
|
||||
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
|
||||
Reference in new issue
Block a user