feat: 히어로 두 칸을 상황별로 고르고 아이콘·색을 상태에 맞춤
- 비 예보 → 미세먼지 나쁨 → 자외선 높음(낮) → 일교차 10° → 체감 쌀쌀 → 불쾌지수 75 순서, 모자라면 비 없음·미세먼지·자외선·달 - 조심(노랑)·비(파랑) 강조, 미세먼지 나쁨은 마스크 아이콘(Fluent Emoji) - Hero.stats 추가, 자외선은 openmeteo_hourly 지금 시각 값
This commit is contained in:
1 parent
5e2846ff72
commit
4096ce0441
13 files changed
+288
-21
No files matched your search
@@ -11,7 +11,7 @@ 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 AirGrade, ArticleCategory, ErrorType, PostType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
@@ -20,7 +20,7 @@ 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,
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide,
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
@@ -28,6 +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.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
@@ -116,6 +117,18 @@ def _discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float]) -> HeroInput:
|
||||
temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else []
|
||||
rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else []
|
||||
return HeroInput(
|
||||
now=now, night=slot in ("evening", "night"), rain_known=now_w is not None, rain_at=rainy[0].at if rainy else None,
|
||||
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
||||
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
moon=phase_name(_tonight(now)),
|
||||
)
|
||||
|
||||
|
||||
def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
@@ -334,7 +347,7 @@ class FeedService:
|
||||
items = board.items if board else []
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board),
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour)),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
@@ -365,7 +378,14 @@ class FeedService:
|
||||
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:
|
||||
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
|
||||
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
|
||||
return None
|
||||
return float(rows[0].uv_index)
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
@@ -377,6 +397,7 @@ class FeedService:
|
||||
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv))],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from common.enums import AirGrade
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.text import hour_label
|
||||
from services.air_service import GRADE_LABEL
|
||||
|
||||
Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
MUGGY = 75
|
||||
SHOWN = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HeroStatItem:
|
||||
key: str
|
||||
icon: str
|
||||
label: str
|
||||
value: str
|
||||
tone: Tone = "normal"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HeroInput:
|
||||
now: datetime
|
||||
night: bool
|
||||
rain_at: Optional[datetime] = None
|
||||
rain_known: bool = False
|
||||
air: Optional[AirGrade] = None
|
||||
uv: Optional[float] = None
|
||||
temp_min: Optional[float] = None
|
||||
temp_max: Optional[float] = None
|
||||
temp: Optional[float] = None
|
||||
feels: Optional[float] = None
|
||||
discomfort: Optional[int] = None
|
||||
moon: Optional[str] = None
|
||||
|
||||
|
||||
def uv_label(uv: float) -> str:
|
||||
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
||||
|
||||
|
||||
def _discomfort_label(v: int) -> str:
|
||||
return "보통" if v < 75 else "높음" if v < 80 else "매우 높음"
|
||||
|
||||
|
||||
def _rain_value(now: datetime, at: datetime) -> str:
|
||||
return "지금 와요" if at <= now else f"{hour_label(at.astimezone(KST).hour)}쯤 와요"
|
||||
|
||||
|
||||
def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 두 칸. 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
||||
alerts: list[HeroStatItem] = []
|
||||
if x.rain_at is not None:
|
||||
alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain"))
|
||||
if x.air in (AirGrade.BAD, AirGrade.VERY_BAD):
|
||||
alerts.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn"))
|
||||
if not x.night and x.uv is not None and x.uv >= UV_HIGH:
|
||||
alerts.append(HeroStatItem("uv", "glasses", "자외선", f"{round(x.uv)} · {uv_label(x.uv)}", "warn"))
|
||||
if x.temp_min is not None and x.temp_max is not None and x.temp_max - x.temp_min >= TEMP_SWING_C:
|
||||
alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷"))
|
||||
if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C:
|
||||
alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀"))
|
||||
if x.discomfort is not None and x.discomfort >= MUGGY:
|
||||
alerts.append(HeroStatItem("muggy", "muggy", "불쾌지수", f"{x.discomfort} · {_discomfort_label(x.discomfort)}", "warn"))
|
||||
|
||||
fills: list[HeroStatItem] = []
|
||||
if x.rain_known and x.rain_at is None:
|
||||
fills.append(HeroStatItem("rain", "moon" if x.night else "sun", "2시간 동안 비", "안 와요"))
|
||||
if x.air is not None:
|
||||
fills.append(HeroStatItem("air", "vent", "미세먼지", GRADE_LABEL[x.air]))
|
||||
if not x.night and x.uv is not None:
|
||||
fills.append(HeroStatItem("uv", "glasses", "자외선", f"{round(x.uv)} · {uv_label(x.uv)}"))
|
||||
if x.night and x.moon:
|
||||
fills.append(HeroStatItem("moon", "moon", "오늘 밤 달", x.moon))
|
||||
|
||||
picked: list[HeroStatItem] = []
|
||||
for item in alerts + fills:
|
||||
if item.key not in {p.key for p in picked} and not (item.icon == "coldwind" and any(p.icon == "coldwind" for p in picked)):
|
||||
picked.append(item)
|
||||
if len(picked) == SHOWN:
|
||||
break
|
||||
return picked
|
||||
Reference in new issue
Block a user