Merge remote-tracking branch 'origin/main' into feat/watch-summary
No files matched your search
@@ -2568,7 +2568,7 @@
|
||||
{
|
||||
"code": "flower",
|
||||
"name": "꽃구경각",
|
||||
"icon": "garden",
|
||||
"icon": "flower",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
@@ -2652,7 +2652,7 @@
|
||||
{
|
||||
"code": "blanket",
|
||||
"name": "이불빨래각",
|
||||
"icon": "laundry",
|
||||
"icon": "blanket",
|
||||
"category": 3,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
@@ -2731,7 +2731,7 @@
|
||||
{
|
||||
"code": "bingsu",
|
||||
"name": "빙수각",
|
||||
"icon": "iced_hot",
|
||||
"icon": "bingsu",
|
||||
"category": 2,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
@@ -2793,7 +2793,7 @@
|
||||
{
|
||||
"code": "indoordry",
|
||||
"name": "실내건조각",
|
||||
"icon": "laundry",
|
||||
"icon": "indoordry",
|
||||
"category": 3,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
@@ -2860,7 +2860,7 @@
|
||||
{
|
||||
"code": "riverwind",
|
||||
"name": "한강밤바람각",
|
||||
"icon": "yajang",
|
||||
"icon": "riverwind",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
@@ -3318,7 +3318,7 @@
|
||||
{
|
||||
"code": "bungeoppang",
|
||||
"name": "붕어빵각",
|
||||
"icon": "sweet_potato",
|
||||
"icon": "bungeoppang",
|
||||
"category": 2,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
@@ -3494,7 +3494,7 @@
|
||||
{
|
||||
"code": "pajeon",
|
||||
"name": "파전각",
|
||||
"icon": "makgeolli",
|
||||
"icon": "pajeon",
|
||||
"category": 2,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
@@ -3606,7 +3606,7 @@
|
||||
{
|
||||
"code": "trot",
|
||||
"name": "트로트각",
|
||||
"icon": "picnic",
|
||||
"icon": "trot",
|
||||
"category": 1,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
@@ -3676,7 +3676,7 @@
|
||||
{
|
||||
"code": "singing_rain",
|
||||
"name": "싱잉인더레인각",
|
||||
"icon": "umbrella",
|
||||
"icon": "singing_rain",
|
||||
"category": 1,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
|
||||
@@ -153,12 +153,13 @@ def feed_day(now: datetime) -> date:
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신·정각(지금 구간이 줄어듦) 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY]
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
|
||||
now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
nxt = min(c for c in changes if c > now)
|
||||
@@ -427,7 +428,7 @@ class FeedService:
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
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],
|
||||
|
||||
@@ -21,9 +21,8 @@ from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, e
|
||||
from services.calc.moon import night, up_ratio, view_line
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
from services.now_service import RainHour, ultra_hours
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
|
||||
|
||||
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
||||
DAYS = 3
|
||||
@@ -176,18 +175,6 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
|
||||
"""초단기예보가 비라고 한 시각은 그 비로 바꾼 사본. 단기예보는 3시간마다라 지금 내리는 비를 놓친다."""
|
||||
out = dict(by_at)
|
||||
for h in ultra or []:
|
||||
r = out.get(h.at)
|
||||
if r is None or h.rain_type is RainType.NONE or r.rain_type != RainType.NONE.value:
|
||||
continue
|
||||
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
||||
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": max(float(r.rain_mm), h.rain_mm)})
|
||||
return out
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
|
||||
|
||||
@@ -208,19 +195,32 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
now: Optional[datetime] = None,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다."""
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()}
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
|
||||
hours_by_slot = slot_hours(day, sunset_at)
|
||||
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
result = evaluate(defn, [w for w in windows if len(w) >= need], ctx)
|
||||
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
|
||||
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _trim_passed(hours_by_slot: dict[str, set[int]], day: date, sunset_at: datetime, now: datetime) -> Optional[str]:
|
||||
"""지금 구간에서 이미 지난 시각을 뺀다(지난 단기예보 비가 지금 점수에 남지 않게). 지금 구간 이름, 오늘이 아니면 None."""
|
||||
hour = int((now - kst_midnight(day)).total_seconds() // 3600)
|
||||
cur = next((k for k, hours in hours_by_slot.items() if hour in hours), None)
|
||||
if cur is not None:
|
||||
hours_by_slot[cur] = {h for h in hours_by_slot[cur] if h >= hour}
|
||||
return cur
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
@@ -390,7 +390,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_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()}
|
||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).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
|
||||
@@ -398,6 +398,8 @@ class IndexService:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
if ultra is not None:
|
||||
inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY)
|
||||
# 지금 구간은 지금 시각부터 보므로 정각마다 다시 계산
|
||||
inputs_at = max(inputs_at, now.replace(minute=0, second=0, microsecond=0))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
@@ -423,7 +425,7 @@ class IndexService:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at, now) if day == today else {}
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
|
||||
@@ -3,39 +3,23 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
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 AirQuality, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.text import hour_label
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import fetch_ultra, parse_ultra
|
||||
from services.warning_service import WarningItem, WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import RainHour, WeatherService, ultra_hours
|
||||
|
||||
_FETCH_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
lightning: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class CommuteRow:
|
||||
label: str
|
||||
@@ -146,45 +130,3 @@ class NowService:
|
||||
|
||||
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
|
||||
return await ultra_hours(region, now)
|
||||
|
||||
|
||||
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
|
||||
|
||||
|
||||
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if not cached:
|
||||
return None
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] != base.isoformat():
|
||||
return None
|
||||
return [
|
||||
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
||||
for h in data["hours"]
|
||||
]
|
||||
|
||||
|
||||
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
||||
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
||||
if attempt:
|
||||
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
||||
if (hours := await _cached_ultra(key, base)) is not None:
|
||||
return hours
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
continue
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
return None
|
||||
except _FETCH_ERRORS as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
@@ -5,6 +5,7 @@ from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
@@ -14,14 +15,14 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Region, SunTime, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, latest_vilage_base, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.calc.sun import sun_times
|
||||
from services.calc.weather_calc import discomfort_index, feels_like_c
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_vilage, latest_mid_base, parse_mid, parse_vilage
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
|
||||
|
||||
SLOT_HOURS = range(0, 24, 3)
|
||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
||||
@@ -31,6 +32,14 @@ MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
lightning: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slot:
|
||||
at: datetime
|
||||
@@ -49,6 +58,18 @@ class TodayWeather:
|
||||
slots: list[Slot]
|
||||
|
||||
|
||||
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
|
||||
"""초단기예보가 닿는 시각은 비·비 없음 모두 초단기예보로 바꾼 사본. 단기예보는 3시간마다라 그 사이 바뀐 비를 놓친다."""
|
||||
out = dict(by_at)
|
||||
for h in ultra or []:
|
||||
r = out.get(h.at)
|
||||
if r is None or (h.rain_type.value, h.rain_mm) == (r.rain_type, float(r.rain_mm)):
|
||||
continue
|
||||
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
||||
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": h.rain_mm})
|
||||
return out
|
||||
|
||||
|
||||
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
|
||||
rows = []
|
||||
for at, v in hourly.items():
|
||||
@@ -138,7 +159,7 @@ class WeatherService:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
|
||||
now = now_kst()
|
||||
await self.ensure_vilage(region, now)
|
||||
_, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
|
||||
day = day or now.date()
|
||||
sun = await self._ensure_sun(region, day)
|
||||
start = kst_midnight(day)
|
||||
@@ -154,11 +175,13 @@ class WeatherService:
|
||||
sunset_score = next(
|
||||
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
|
||||
)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
slots = []
|
||||
hour_now = now.replace(minute=0, second=0, microsecond=0)
|
||||
for h in SLOT_HOURS:
|
||||
at = start + timedelta(hours=h)
|
||||
row = by_at.get(at)
|
||||
# 지금이 든 칸은 칸 첫 시각 대신 지금 시각 예보 (이미 지난 시각의 비가 '지금'으로 보이지 않게)
|
||||
row = by_at.get(hour_now) if at <= now < at + timedelta(hours=3) and hour_now in by_at else by_at.get(at)
|
||||
icon, tone, note = _slot_view(at, row, sun)
|
||||
if note == "노을" and sunset_score is not None:
|
||||
note = f"노을 {sunset_score}"
|
||||
@@ -262,3 +285,45 @@ class WeatherService:
|
||||
}
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
|
||||
return SunTime(**row)
|
||||
|
||||
|
||||
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
|
||||
|
||||
|
||||
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if not cached:
|
||||
return None
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] != base.isoformat():
|
||||
return None
|
||||
return [
|
||||
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
||||
for h in data["hours"]
|
||||
]
|
||||
|
||||
|
||||
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
||||
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
||||
if attempt:
|
||||
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
||||
if (hours := await _cached_ultra(key, base)) is not None:
|
||||
return hours
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
continue
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
return None
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
@@ -80,7 +80,6 @@ def offline(monkeypatch):
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -118,7 +117,7 @@ def offline(monkeypatch):
|
||||
|
||||
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
|
||||
|
||||
@@ -6,8 +6,8 @@ from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results, with_ultra_rain
|
||||
from services.now_service import RainHour
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
|
||||
from services.weather_service import RainHour, with_ultra_rain
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
@@ -81,15 +81,17 @@ def _hourly(h: int, rain: RainType = RainType.NONE) -> WeatherHourly:
|
||||
)
|
||||
|
||||
|
||||
def test_ultra_rain_marks_dry_forecast_hours_as_rain():
|
||||
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER))}
|
||||
def test_ultra_overrides_vilage_rain_both_ways():
|
||||
"""초단기예보가 닿는 시각은 초단기예보가 이긴다: 단기예보가 맑아도 비로, 단기예보가 비여도 비 없음으로."""
|
||||
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER), _hourly(12, RainType.RAIN))}
|
||||
at = lambda h: kst_midnight(DAY) + timedelta(hours=h) # noqa: E731
|
||||
ultra = [RainHour(at=at(10), rain_type=RainType.RAIN, rain_mm=1.5), RainHour(at=at(9), rain_type=RainType.NONE, rain_mm=0),
|
||||
RainHour(at=at(11), rain_type=RainType.RAIN, rain_mm=3.0)]
|
||||
RainHour(at=at(11), rain_type=RainType.NONE, rain_mm=0)]
|
||||
out = with_ultra_rain(by_at, ultra)
|
||||
assert (out[at(10)].rain_type, float(out[at(10)].rain_mm)) == (RainType.RAIN.value, 1.5)
|
||||
assert out[at(9)] is by_at[at(9)] and out[at(11)] is by_at[at(11)]
|
||||
assert by_at[at(10)].rain_type == RainType.NONE.value
|
||||
assert (out[at(11)].rain_type, float(out[at(11)].rain_mm)) == (RainType.NONE.value, 0)
|
||||
assert out[at(9)] is by_at[at(9)] and out[at(12)] is by_at[at(12)]
|
||||
assert by_at[at(10)].rain_type == RainType.NONE.value and by_at[at(11)].rain_type == RainType.SHOWER.value
|
||||
|
||||
|
||||
def test_ultra_rain_lowers_slot_score():
|
||||
@@ -106,3 +108,20 @@ def test_slot_needs_two_overlapping_hours():
|
||||
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
|
||||
|
||||
def test_current_slot_skips_passed_hours():
|
||||
"""13:30이면 낮 구간(11~15시)은 13시부터 본다. 11~12시에만 온 비는 지금 점수를 깎지 않는다. 지난 아침 구간은 그대로."""
|
||||
defn = _defn([{"from": 5, "to": 24}])
|
||||
by_at = {r.forecast_at: r for r in (_hourly(h, RainType.RAIN if h in (11, 12) else RainType.NONE) for h in range(5, 30))}
|
||||
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
|
||||
with_now = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET, now)
|
||||
without = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert with_now["day"].score > without["day"].score
|
||||
assert with_now["morning"].score == without["morning"].score
|
||||
|
||||
|
||||
def test_current_slot_keeps_last_hour():
|
||||
"""구간 끝 한 시간만 남아도 지금 구간 점수를 낸다."""
|
||||
now = datetime(2026, 10, 8, 15, 10, tzinfo=KST)
|
||||
assert "day" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
|
||||
@@ -4,7 +4,6 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.now_service as now_service
|
||||
import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
@@ -52,7 +51,7 @@ def fakes(monkeypatch):
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -2,7 +2,6 @@ import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -16,7 +15,7 @@ REGION = "1114000000"
|
||||
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
|
||||
SOURCES = {
|
||||
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
|
||||
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"ultra": (weather_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
|
||||
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
|
||||
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
|
||||
|
||||
@@ -4,7 +4,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.now_service as now_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
@@ -94,7 +94,7 @@ async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
|
||||
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
|
||||
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
|
||||
]
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(items))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(items))
|
||||
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
|
||||
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
|
||||
@@ -5,7 +5,6 @@ from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
@@ -63,7 +62,7 @@ async def clean():
|
||||
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
|
||||
now = now_kst()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
|
||||
@@ -92,7 +91,7 @@ async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
|
||||
raise DataGoKrRequestFailed("HTTP 504")
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", fail)
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", fail)
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
|
||||
|
||||
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 49 KiB |
@@ -130,7 +130,9 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
const top1 = slotTop ?? hero?.top1
|
||||
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
||||
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
|
||||
const bubble = slotTop ? (slotTop.score >= 70 ? `오늘은 ${slotTop.name}!` : '오늘은 쉬어 가요') : hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
|
||||
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
|
||||
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
const status = hero?.status ?? []
|
||||
const rain = weather === 'rain' || weather === 'sleet'
|
||||
const snow = weather === 'snow' || weather === 'sleet'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay'])
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
|
||||