Files
o2o-weather/backend/services/hero_stats.py
T

120 lines
5.5 KiB
Python

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
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
TEMP_SWING_C = 10.0
WIND_CHILL_C = 3.0
SHOWN = 1
@dataclass(frozen=True)
class HeroStatItem:
key: str
icon: str
label: str
value: str
tone: Tone = "normal"
detail: Optional[str] = None # 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥)
@dataclass(frozen=True)
class HeroInput:
now: datetime
night: bool
rain_at: Optional[datetime] = None # 앞으로 2시간 안에 비 오는 첫 시각 (초단기)
rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보)
today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지
air: Optional[AirGrade] = None
pm25: Optional[int] = None
pm10: Optional[int] = None
uv: Optional[float] = None
temp_min: Optional[float] = None
temp_max: Optional[float] = None
temp: Optional[float] = None
feels: Optional[float] = None
moon: Optional[str] = None
humidity: Optional[int] = None
discomfort: Optional[int] = None
after_dark: bool = False # 밤 구간(일몰 1시간 뒤~). night 는 저녁 구간까지 포함한다
_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험")
def uv_level(uv: float) -> int:
"""기상청 자외선 단계 1 낮음 ~ 5 위험."""
return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5
def uv_label(uv: float) -> str:
return _UV_LABELS[uv_level(uv) - 1]
def discomfort_label(v: int) -> str:
return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌"
def humidity_label(h: int) -> str:
return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함"
def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = []
if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity), detail=f"{x.humidity}%"))
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal", detail=str(x.discomfort)))
if not x.after_dark and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal", detail=f"{x.uv:g}"))
if x.air is not None:
pm = " · ".join(s for s in (f"초미세먼지 {x.pm25}㎍/㎥" if x.pm25 is not None else "", f"미세먼지 {x.pm10}㎍/㎥" if x.pm10 is not None else "") if s) or None
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal", detail=pm))
return out
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"))
elif x.rain_later_at is not None:
alerts.append(HeroStatItem("rain", "umbrella", "오늘 비", _rain_value(x.now, x.rain_later_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)}°", "바람 쌀쌀"))
# 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다
fills: list[HeroStatItem] = []
if x.today_known and x.rain_at is None and x.rain_later_at is None:
fills.append(HeroStatItem("rain", "moon" if x.night else "sun", "오늘 밤 비" if x.night else "오늘 비", "안 와요"))
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