feat: 피드에 자외선 포스트 (아침·낮, 오늘 가장 셀 때 '보통' 이상인 날만)
- 오늘 9·12·15·18시 자외선(Open-Meteo)과 가장 셀 때 시각, '높음' 이상이면 할 일 한 줄 - '낮음'인 날은 챙길 게 없어 띄우지 않음
This commit is contained in:
1 parent
c67121351b
commit
35b3e0df43
6 files changed
+90
-10
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -10,7 +10,7 @@ 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.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
@@ -28,7 +28,7 @@ from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
from services.hero_stats import HeroInput, hero_stats
|
||||
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
@@ -60,11 +60,12 @@ LINEUP = [
|
||||
(17, PostType.AIR, RefType.NONE, None),
|
||||
(18, PostType.DAY_TRIP, RefType.NONE, None),
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
]
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.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.MOON, 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.MOON, PostType.QUOTE],
|
||||
}
|
||||
@@ -74,6 +75,7 @@ _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 에 그날 카드가 바뀐다
|
||||
@@ -334,7 +336,8 @@ class FeedService:
|
||||
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)
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
@@ -382,6 +385,14 @@ class FeedService:
|
||||
return (pick, []), True
|
||||
return (pick, pick_events(pick.best.day, items)), False
|
||||
|
||||
async def _uv_today(self, region_code: str, now: datetime) -> list[OpenMeteoHourly]:
|
||||
"""오늘 09~18시 3시간 칸 끝 시각의 자외선 (Open-Meteo)."""
|
||||
day = kst_midnight(now.date())
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.openmeteo_between(s, region_code, day + timedelta(hours=9), day + timedelta(hours=18))
|
||||
)
|
||||
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
|
||||
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
|
||||
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
|
||||
@@ -471,6 +482,8 @@ class FeedService:
|
||||
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:
|
||||
@@ -573,6 +586,25 @@ class FeedService:
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{line} {tail}"])
|
||||
|
||||
def _uv_post(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""오늘 낮 자외선. 가장 셀 때가 '보통'(3) 아래면 챙길 게 없어 끈다."""
|
||||
if not c.uv:
|
||||
return None
|
||||
peak = max(c.uv, key=lambda r: r.uv_index)
|
||||
top = float(peak.uv_index)
|
||||
if top < _UV_SHOW:
|
||||
return None
|
||||
label = uv_label(top)
|
||||
at = peak.forecast_at.astimezone(KST)
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
|
||||
high = top >= UV_HIGH
|
||||
if high:
|
||||
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
|
||||
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
|
||||
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
air = c.now_w.air if c.now_w else None
|
||||
@@ -717,3 +749,4 @@ class _Ctx:
|
||||
articles: dict[int, Article]
|
||||
quotes: list[Article]
|
||||
trip: Optional[tuple[TripPick, list[EventItem]]] = None
|
||||
uv: list[OpenMeteoHourly] = field(default_factory=list) # 오늘 낮 3시간 칸 자외선
|
||||
Reference in new issue
Block a user