feat: 오늘 히어로 D4-2 — 해 안 점수, 상태 한 줄(습도·불쾌지수·자외선·미세먼지 단계), 하루 흐름 칸이 미리보기 탭, 구름·비·눈 연출 / 각 시간대별 점수·순위 미리보기 / 자외선 시간표 단계 색 칩 / 밤 화면 어두운 아이콘 빛
This commit is contained in:
1 parent
4cdc8b274f
commit
aa774c2a44
13 files changed
+367
-155
No files matched your search
@@ -30,7 +30,7 @@ from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import MoonNight, nearest, night, view_line
|
||||
from services.calc.sky_score import GRADE_LABEL, sky_title
|
||||
from services.calc.sun import sun_times
|
||||
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
|
||||
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
@@ -130,10 +130,6 @@ 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 _hero_input(
|
||||
now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str],
|
||||
) -> HeroInput:
|
||||
@@ -147,7 +143,7 @@ def _hero_input(
|
||||
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,
|
||||
moon=moon,
|
||||
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -238,7 +234,8 @@ def _by_position(posts: list[Post]) -> list[Post]:
|
||||
|
||||
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, active=i.active)
|
||||
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, active=i.active,
|
||||
slots=i.slots, slot_ranks=i.slot_ranks)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
@@ -418,10 +415,10 @@ class FeedService:
|
||||
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:
|
||||
return None
|
||||
return float(rows[0].uv_index)
|
||||
"""지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour))
|
||||
rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None
|
||||
|
||||
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, moon: Optional[tuple[MoonNight, str]] = None) -> Hero:
|
||||
@@ -429,16 +426,18 @@ class FeedService:
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
||||
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,
|
||||
humidity=cur.humidity if cur else None,
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) 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,
|
||||
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
|
||||
top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
|
||||
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, f"{moon[0].name}, {moon[1]}" if moon else None))],
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
|
||||
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -627,14 +626,13 @@ class FeedService:
|
||||
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)}",
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv]
|
||||
when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵"
|
||||
todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요"
|
||||
line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}"
|
||||
return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
||||
share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
|
||||
@@ -10,6 +10,8 @@ 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
|
||||
@@ -38,10 +40,42 @@ class HeroInput:
|
||||
temp: Optional[float] = None
|
||||
feels: Optional[float] = None
|
||||
moon: Optional[str] = None
|
||||
humidity: Optional[int] = None
|
||||
discomfort: Optional[int] = None
|
||||
|
||||
|
||||
_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 "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
||||
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)))
|
||||
if x.discomfort is not None:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||
if not x.night and x.uv is not None:
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||
if x.air is not None:
|
||||
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
|
||||
return out
|
||||
|
||||
|
||||
def _rain_value(now: datetime, at: datetime) -> str:
|
||||
|
||||
@@ -50,6 +50,7 @@ class IndexItem:
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
|
||||
|
||||
@@ -59,6 +60,7 @@ class IndexBoard:
|
||||
day: date
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
weather_slots: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
@@ -161,6 +163,12 @@ def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
|
||||
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
return {k: shown[k] for k in SLOTS if k in shown}
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
) -> dict[str, Result]:
|
||||
@@ -253,7 +261,7 @@ class IndexService:
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
err, weather_score = await self.ensure(region, now)
|
||||
err, weather_parts = await self.ensure(region, now)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
@@ -278,11 +286,11 @@ class IndexService:
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
|
||||
slot=shown_slot(cur), slots=parts,
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
@@ -293,12 +301,18 @@ class IndexService:
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
for k in SLOTS:
|
||||
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||
for n, i in enumerate(in_slot):
|
||||
i.slot_ranks[k] = n + 1
|
||||
return ErrorType.SUCCESS, IndexBoard(
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||
self.warning_service.for_region(region, now),
|
||||
@@ -328,7 +342,7 @@ class IndexService:
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
|
||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()}
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
@@ -339,7 +353,7 @@ class IndexService:
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
return ErrorType.SUCCESS, weather_parts
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||
@@ -366,4 +380,4 @@ class IndexService:
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
return err, weather_parts
|
||||
Reference in new issue
Block a user