feat: 지금 날씨를 초단기실황 관측값으로, 각 점수에서 시간대 알맞음 제거·우산각 계산식 변경

- 초단기실황(getUltraSrtNcst)을 받아 지금 정시 한 시각의 비·기온·습도·바람을 예보 대신 관측값으로 덮어씀 (체감·불쾌지수는 다시 계산). 지역별 1시간 캐시, 실패하면 초단기예보·단기예보로 되돌아감, 새 시각 실황이 나오면 각 점수를 다시 계산. 가이드대로 ±900 이상은 결측 처리. 테스트가 실제 기상청을 부르지 않게 실황 호출을 기본으로 막음
- 시간대 알맞음 요소를 31개 각에서 빼고 비중을 5% 단위로 나눔. 요소가 3개 미만이 된 뜨아각·파전각·감성노래각·감사각·선크림각에 요소를 더함. 러닝각의 활동 시간대 밖 점수 상한도 없앰. 요소가 하나뿐인 각은 가장 낮은 요소로 깎지 않음
- 우산각은 비 한 가지: 남은 하루(지금~자정) 비 확률 평균이 점수, 지금 비가 오면 70점에서 시작해 평균 × 30점을 더함. 내일·토·일 칸은 그날 6~24시 평균 × 100. 우산분실각도 비 한 가지
- 각 계산 기준 문서는 생성기를 새 규칙에 맞게 고쳐 다시 생성, 점수 계산식·서비스 동작 안내 문서 갱신
This commit is contained in:
skkim committed 2026-11-23 14:51:04 +09:00
1 parent 8ea9f8f04b
commit 5ab2381f79
19 files changed
+737 -243

No files matched your search

+25 -4
View File
@@ -62,6 +62,7 @@ class Context:
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
at_now: bool = False # 평가하는 첫 시각이 지금인지 (우산각의 '지금 비'). 다른 구간·내일 칸은 지금이 없다
@dataclass(frozen=True)
@@ -138,6 +139,18 @@ def rain_score(rule: dict, max_prob: int, raining: bool, until: str = "") -> tup
return (0 if raining else _linear(max_prob, 100, 0)), (f"비 소식, {prob}" if raining else prob)
def rain_rest_of_day_score(rule: dict, probs: list[int], raining_now: bool) -> tuple[int, str]:
"""남은 시각(시각마다 1시간)의 비 확률 평균. 지금 비가 오면 now_base 에서 시작해 나머지를 평균으로 채운다 (그 시각은 100% 로 침)."""
if raining_now:
probs = [100, *probs[1:]]
avg = sum(probs) / len(probs)
note = f"남은 시간 평균 비 확률 {round(avg)}%"
if raining_now:
base = rule["now_base"]
return _clamp(base + (100 - base) * avg / 100), f"지금 비가 와요, {note}"
return _clamp(avg), note
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
if wind is None:
return _UNKNOWN, f"바람 정보가 없어 {_UNKNOWN}점으로 둬요"
@@ -310,7 +323,8 @@ def summary_line(mid: Hour) -> str:
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int:
"""비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다)."""
mixed = sum(factors[a] * weights[a] for a in AXES) / 100
if not worst_pull:
# 요소가 하나면 그 요소가 곧 가장 낮은 요소라 깎으면 같은 점수를 두 번 깎게 된다
if not worst_pull or sum(1 for a in AXES if weights[a]) <= 1:
return round(mixed)
# 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다.
worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100)
@@ -343,7 +357,10 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
grounds = [h.ground_c for h in hours if h.ground_c is not None]
scored = {
"temp": temp_score(rules["temp"], feels),
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
"rain": (
rain_rest_of_day_score(rules["rain"], [h.rain_prob for h in hours], ctx.at_now and hours[0].rain_type is not RainType.NONE)
if rules["rain"].get("span") == "rest_of_day" else rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else "")
),
"wind": wind_score(rules["wind"], max(winds) if winds else None),
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
@@ -395,7 +412,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
if not hours:
continue
temps = [hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours]
own_prob = max(fc.rain_prob_am if h < 12 else fc.rain_prob_pm if h < 24 else after.rain_prob_am for h in hours)
hour_probs = [fc.rain_prob_am if h < 12 else fc.rain_prob_pm if h < 24 else after.rain_prob_am for h in hours]
own_prob = max(hour_probs)
max_prob = max(own_prob, ctx.lookahead_rain_prob)
humidity = (50, "습도 이 각엔 상관없어 50점으로 둬요") if rules["humidity"]["type"] == "ignore" else (
_UNKNOWN, f"습도 정보가 없어 {_UNKNOWN}점으로 둬요"
@@ -403,7 +421,10 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
temp, temp_note = temp_score(rules["temp"], mean(temps))
scored = {
"temp": (temp, f"{temp_note} (최저·최고 기온으로 어림)"),
"rain": rain_score(rules["rain"], max_prob, False, until if max_prob > own_prob else ""),
"rain": (
rain_rest_of_day_score(rules["rain"], hour_probs, False)
if rules["rain"].get("span") == "rest_of_day" else rain_score(rules["rain"], max_prob, False, until if max_prob > own_prob else "")
),
"wind": wind_score(rules["wind"], None),
"humidity": humidity,
"air": air_score(None, None),
+27
View File
@@ -1,5 +1,6 @@
import re
from datetime import date, datetime, timedelta
from typing import Optional
import httpx
@@ -9,6 +10,7 @@ from services.external.data_go_kr import get_all_items
VILAGE_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
ULTRA_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst"
NCST_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst"
WARNING_URL = "https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd"
_SKY = {"1": Sky.CLEAR, "3": Sky.PARTLY, "4": Sky.CLOUDY}
# 단기예보 0~4, 초단기예보는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림이 더 있다
@@ -40,6 +42,12 @@ async def fetch_ultra(client: httpx.AsyncClient, nx: int, ny: int, base: datetim
return await get_all_items(client, ULTRA_URL, params, page_size=100)
async def fetch_ncst(client: httpx.AsyncClient, nx: int, ny: int, base: datetime) -> list[dict]:
base = base.astimezone(KST)
params = {"dataType": "JSON", "base_date": base.strftime("%Y%m%d"), "base_time": base.strftime("%H%M"), "nx": nx, "ny": ny}
return await get_all_items(client, NCST_URL, params, page_size=100)
async def fetch_warning_events(client: httpx.AsyncClient, since: datetime, until: datetime) -> list[dict]:
params = {"dataType": "JSON", "fromTmFc": since.astimezone(KST).strftime("%Y%m%d"), "toTmFc": until.astimezone(KST).strftime("%Y%m%d")}
return await get_all_items(client, WARNING_URL, params)
@@ -91,6 +99,25 @@ def parse_ultra(items: list[dict]) -> list[dict]:
]
_NCST_FIELDS = ("PTY", "RN1", "T1H", "REH", "WSD")
_MISSING = 900 # 가이드: +900 이상, -900 이하 값은 결측
def parse_ncst(items: list[dict]) -> Optional[dict]:
"""초단기실황: 지금 관측한 비 형태·1시간 강수량·기온·습도·풍속. 하나라도 없거나 결측이면 None."""
v = {it["category"]: it["obsrValue"] for it in items}
if not all(k in v for k in _NCST_FIELDS):
return None
try:
nums = {k: float(v[k]) for k in ("RN1", "T1H", "REH", "WSD")}
rain_type = _PTY[v["PTY"]]
except (ValueError, KeyError):
return None
if any(abs(n) >= _MISSING for n in nums.values()):
return None
return {"rain_type": rain_type, "rain_mm": nums["RN1"], "temp_c": nums["T1H"], "humidity": round(nums["REH"]), "wind_ms": nums["WSD"]}
_ACTIVE_COMMANDS = {1, 3, 6, 7}
+18 -10
View File
@@ -11,7 +11,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, now_kst
from common.utils.kma_time import KST, NCST_DELAY, ULTRA_DELAY, kst_midnight, latest_ultra_base, now_kst
from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
@@ -24,7 +24,7 @@ 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.warning_service import WarningService
from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
from services.weather_service import WeatherService, observed_now, ultra_hours, with_observed, with_ultra_rain
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
DAYS = 3
@@ -248,9 +248,13 @@ def slot_results(
continue
matches = any(any(h % 24 in w for h in hours) for w in activity)
# 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다.
window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}])
windows = windows_for(window, day, region, by_at, by_om, only=hours)
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
# 우산각은 구간이 아니라 그 구간 시작(지금 구간은 지금)부터 자정까지의 비를 본다.
seen = set(range(min(hours), 24)) if defn.factor_rules["rain"].get("span") == "rest_of_day" else hours
window = SimpleNamespace(windows=[{"from": min(seen), "to": max(seen) + 1}])
windows = windows_for(window, day, region, by_at, by_om, only=seen)
# 지금 시각의 예보 행이 있을 때만 '지금'이다 (없으면 첫 행은 더 뒤 시각이다)
at_now = key == cur and bool(windows and windows[0]) and windows[0][0].hour == int((now - kst_midnight(day)).total_seconds() // 3600)
result = evaluate(defn, windows, replace(ctx, time_matches=matches, at_now=at_now))
if result is not None:
# 지금 구간 줄은 남은 시간의 가운데가 아니라 지금 시각 날씨로
if key == cur and windows and windows[0]:
@@ -413,7 +417,9 @@ class IndexService:
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
_, _, ultra, observed = await asyncio.gather(
self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now), observed_now(region, now),
)
today = now.date()
start = kst_midnight(today)
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
@@ -422,7 +428,7 @@ class IndexService:
if not rows:
return ErrorType.EXTERNAL_API_ERROR, None
air = await self.air_service.nearest(region)
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
by_at = with_observed(with_ultra_rain({r.forecast_at: r for r in rows}, ultra), observed)
ctx = Context(
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
@@ -437,9 +443,9 @@ class IndexService:
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[date, dict[str, Result]]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘·내일 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings, ultra = await asyncio.gather(
_, _, _, warnings, ultra, observed = 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), ultra_hours(region, now, wait=True),
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True), observed_now(region, now, wait=True),
)
today = now.date()
start = kst_midnight(today)
@@ -458,7 +464,7 @@ class IndexService:
)
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
air = await self.air_service.nearest(region)
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
by_at = with_observed(with_ultra_rain({r.forecast_at: r for r in rows}, ultra), observed)
base_ctx = dict(
pm25=air.pm25 if air else None,
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
@@ -480,6 +486,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)
if observed is not None:
inputs_at = max(inputs_at, observed.at + NCST_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))
+73 -4
View File
@@ -15,14 +15,16 @@ 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_ultra_base, latest_vilage_base, now_kst
from common.utils.kma_time import KST, NCST_DELAY, kst_midnight, latest_ncst_base, 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_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
from services.external.kma import (
day_start_base, fetch_mid, fetch_ncst, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ncst, parse_ultra, parse_vilage,
)
SLOT_HOURS = range(0, 24, 3)
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
@@ -40,6 +42,17 @@ class RainHour:
lightning: bool = False
@dataclass
class Observed:
"""초단기실황: 정시(at)에 관측한 지금 날씨."""
at: datetime
rain_type: RainType
rain_mm: float
temp_c: float
humidity: int
wind_ms: float
@dataclass
class Slot:
at: datetime
@@ -70,6 +83,19 @@ def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[R
return out
def with_observed(by_at: dict[datetime, WeatherHourly], obs: Optional[Observed]) -> dict[datetime, WeatherHourly]:
"""실황이 닿는 정시 한 시각은 비·기온·습도·바람을 관측값으로 바꾼 사본. 체감온도·불쾌지수는 관측값으로 다시 계산한다."""
r = by_at.get(obs.at) if obs else None
if r is None:
return by_at
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
row = WeatherHourly(**{
**cols, "rain_type": obs.rain_type.value, "rain_mm": obs.rain_mm, "temp_c": obs.temp_c, "humidity": obs.humidity, "wind_ms": obs.wind_ms,
"feels_c": feels_like_c(obs.temp_c, obs.humidity, obs.wind_ms, obs.at.month), "discomfort_index": discomfort_index(obs.temp_c, obs.humidity),
})
return {**by_at, obs.at: row}
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
rows = []
for at, v in hourly.items():
@@ -159,7 +185,7 @@ class WeatherService:
return ErrorType.NOT_FOUND, None
now = now_kst()
_, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
_, ultra, observed = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True), observed_now(region, now, wait=True))
day = day or now.date()
sun = await self._ensure_sun(region, day)
start = kst_midnight(day)
@@ -175,7 +201,7 @@ 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 = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
by_at = with_observed(with_ultra_rain({r.forecast_at: r for r in rows}, ultra), observed)
slots = []
hour_now = now.replace(minute=0, second=0, microsecond=0)
for h in SLOT_HOURS:
@@ -327,3 +353,46 @@ async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Opti
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
LOG.error(f"[now] ultra {region.code}: {e}")
return None
async def _cached_ncst(key: str, base: datetime) -> Optional[Observed]:
cached = await REDIS.conn.get(key)
if not cached:
return None
data = orjson.loads(cached)
if data["base"] != base.isoformat():
return None
return Observed(
at=base, rain_type=RainType(data["rain_type"]), rain_mm=data["rain_mm"], temp_c=data["temp_c"], humidity=data["humidity"], wind_ms=data["wind_ms"],
)
async def observed_now(region: Region, now: datetime, wait: bool = False) -> Optional[Observed]:
"""초단기실황(지금 관측). 정시마다 한 번 받아 그 시간 동안 쓴다. 실패하거나 값이 비면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다린다."""
key = f"ncst:{region.code}"
base = latest_ncst_base(now)
try:
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
if attempt:
await asyncio.sleep(_ULTRA_WAIT_SEC)
if (obs := await _cached_ncst(key, base)) is not None:
return obs
async with redis_lock(f"lock:ncst:{region.code}") as acquired:
if not acquired:
continue
async with httpx.AsyncClient(timeout=10) as client:
parsed = parse_ncst(await fetch_ncst(client, region.nx, region.ny, base))
if parsed is None:
return None
obs = Observed(at=base, **parsed)
payload = {
"base": base.isoformat(), "rain_type": obs.rain_type.value, "rain_mm": obs.rain_mm, "temp_c": obs.temp_c,
"humidity": obs.humidity, "wind_ms": obs.wind_ms,
}
ttl = int((base + timedelta(hours=1) + NCST_DELAY - now).total_seconds())
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
return obs
return None
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
LOG.error(f"[now] ncst {region.code}: {e}")
return None