Merge origin/main into main-2: Open-Meteo 구름 20·100km·모델 2개 구조에 노을 하늘 상황 판정 맞춤

- 하늘 상황 판정·테스트를 구름 지점 2곳(20·100km), 모델 2개(JMA·ICON) 기준으로
- Open-Meteo 보조값 호출(fetch_weather)도 장애 대처(8초 끊기·2분 건너뛰기) 적용
- worker: 행사 수집 스케줄과 Open-Meteo 보조값 스케줄 둘 다 유지
- 지수 seed: main 의 한계 설명 + main-2 의 점수 구간 설명
- 옛 data-pipeline 문서는 삭제 유지, 내용은 openmeteo-data.md·데이터_흐름.html 에 반영
This commit is contained in:
minaChoi committed 2026-10-07 14:04:18 +09:00
commit 3f8f7daeb1
21 files changed
+1068 -111

No files matched your search

+47 -6
View File
@@ -8,7 +8,7 @@ from typing import Optional
from common.enums import RainType, Sky
from common.utils.text import hour_label
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
_UNKNOWN = 70
@@ -25,6 +25,12 @@ class Hour:
wind_ms: Optional[float]
humidity: int
sky: Sky
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
uv: Optional[float] = None
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
visibility_km: Optional[float] = None
gust_ms: Optional[float] = None
ground_c: Optional[float] = None
@dataclass(frozen=True)
@@ -134,6 +140,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
if uv is None:
return _UNKNOWN, "자외선 정보 없음"
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
if ratio is None:
return _UNKNOWN, "햇빛 정보 없음"
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
if km is None:
return _UNKNOWN, "가시거리 정보 없음"
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
kind = rule["type"]
if kind == "weekday":
@@ -153,10 +177,14 @@ _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower":
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
def axis_label(axis: str, rules: dict) -> str:
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
if axis in _OM_LABEL:
return _OM_LABEL[axis]
if axis == "rain":
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
if axis == "air":
@@ -180,8 +208,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
return None, None
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%"}
_FIELD_TEXT = {
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
"gust_ms": "돌풍", "ground_c": "지표면 온도",
}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
def _cond(r: dict) -> tuple[str, str, str]:
@@ -232,7 +263,7 @@ def _until(definition) -> str:
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
best: Optional[Result] = None
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
rules = definition.factor_rules
until = _until(definition)
for hours in windows:
@@ -243,12 +274,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
raining = any(h.rain_type is not RainType.NONE for h in hours)
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
feels = mean(h.feels_c for h in hours)
uvs = [h.uv for h in hours if h.uv is not None]
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
views = [h.visibility_km for h in hours if h.visibility_km is not None]
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
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 ""),
"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),
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
"time": time_score(rules["time"], ctx),
}
factors = {a: v for a, (v, _) in scored.items()}
@@ -259,6 +298,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
"warning": "wind" if ctx.wind_warning else None,
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
@@ -277,11 +317,11 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
if fc.temp_min_c is None or fc.temp_max_c is None:
return None
best: Optional[Result] = None
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
rules = definition.factor_rules
until = _until(definition)
after = next_fc or fc
@@ -301,6 +341,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
"wind": wind_score(rules["wind"], None),
"humidity": humidity,
"air": air_score(None, None),
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
"time": time_score(rules["time"], ctx),
}
factors = {a: v for a, (v, _) in scored.items()}
+11 -11
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
DISTANCES_KM = (20, 50, 100)
DISTANCES_KM = (20, 100)
@dataclass(frozen=True)
@@ -14,11 +14,11 @@ class Layers:
high: float
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
def score(near20: Layers, far100: Layers) -> int:
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = max(near20.mid, near20.high)
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
f_near = 1 - 0.8 * near20.low / 100
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
@@ -73,13 +73,13 @@ def mean_layers(rows: list[Layers]) -> Layers:
return Layers(*(statistics.mean(getattr(r, k) for r in rows) for k in ("low", "mid", "high")))
def situation(near20: Layers, near50: Layers, far100: Layers) -> SkySituation:
def situation(near20: Layers, far100: Layers) -> SkySituation:
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
return SkySituation.COVERED
if (near20.low + near50.low) / 2 >= 60:
if near20.low >= 60:
return SkySituation.LOW_CLOUD
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
canvas = max(near20.mid, near20.high)
if canvas < 25:
return SkySituation.FEW
if canvas > 75:
@@ -100,13 +100,13 @@ SITUATION_VERDICT = {
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
def reason(near20: Layers, near50: Layers, far100: Layers) -> str:
def reason(near20: Layers, far100: Layers) -> str:
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
if (near20.low + near50.low) / 2 >= 60:
if near20.low >= 60:
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
canvas = round((max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2)
canvas = round(max(near20.mid, near20.high))
if canvas < 10:
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
if canvas > 85:
+75 -4
View File
@@ -1,5 +1,5 @@
import asyncio
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
import httpx
@@ -7,7 +7,7 @@ from common.enums import CloudModel
from services.external.guard import Unreachable, guarded
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
@@ -17,10 +17,23 @@ class OpenMeteoRequestFailed(RuntimeError):
_CHUNK = 24
WEATHER_VARS = (
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
)
SLOT_HOURS = 3
# 해가 없는 밤 구간(21~06시 = 끝 시각 KST 0·3·6시)은 햇빛 값(일조·일사·자외선)을 저장하지 않는다.
DARK_SLOT_END_KST = (0, 3, 6)
_SUN_FIELDS = ("uv_index", "uv_index_clear_sky", "sunshine_s", "shortwave_avg_wm2", "shortwave_max_wm2")
_KST_OFFSET = timedelta(hours=9)
def is_dark_slot(end: datetime) -> bool:
return (end.astimezone(timezone.utc) + _KST_OFFSET).hour in DARK_SLOT_END_KST
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
"""좌표마다 시간별 층별 구름을 모델별로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
async def all_chunks() -> list[dict]:
@@ -37,6 +50,10 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
for attempt in range(_ATTEMPTS):
try:
res = await client.get(URL, params=params)
@@ -47,7 +64,27 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(1.0 * (attempt + 1))
raise Unreachable(f"forecast {len(points)} points: {last}")
raise Unreachable(f"forecast {point_count} points: {last}")
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
async def all_chunks() -> list[dict]:
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
return await guarded("openmeteo:weather", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
@@ -62,3 +99,37 @@ def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
continue
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
return rows
def _round(v, digits: int = 0):
return None if v is None else (round(v, digits) if digits else int(round(v)))
def parse_weather(data: dict) -> list[dict]:
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀). 밤 구간은 햇빛 값을 비운다."""
h = data["hourly"]
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
index = {t: i for i, t in enumerate(times)}
rows = []
for end, i in index.items():
if end.hour % SLOT_HOURS:
continue
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
if None in span:
continue
sun = [h["sunshine_duration"][j] for j in span]
rad = [h["shortwave_radiation"][j] for j in span]
row = {
"forecast_at": end,
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
"sunshine_s": None if None in sun else int(round(sum(sun))),
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
}
if is_dark_slot(end):
row |= dict.fromkeys(_SUN_FIELDS)
rows.append(row)
return rows
+51 -8
View File
@@ -7,7 +7,7 @@ from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import IndexDefinition, IndexScore, Region, WeatherDaily, WeatherHourly
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, kst_midnight, now_kst
from crud.index_crud import IndexCRUD
@@ -19,6 +19,7 @@ from services.air_service import GRADE_LABEL, AirService
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
from services.calc.moon import illumination
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
@@ -89,13 +90,48 @@ def window_hours(defn, day: date, region: Region) -> list[list[int]]:
return out
def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly]) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다."""
def _slot_end_hour(h: int) -> int:
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
return (h + 3) // 3 * 3
def _nearest_slot_end_hour(h: int) -> int:
"""h시~h+1시의 한가운데에 가장 가까운 3시간 구간 끝 시각. 자외선·가시거리·돌풍·지표면 온도처럼 '끝 시각 순간값'에 쓴다 (9시→9시, 10시→12시)."""
return int((h + 0.5) / 3 + 0.5) * 3
def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict:
"""3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음'). 밤 구간은 햇빛 값을 받지 않으므로 0으로 본다."""
fields = {}
if instant is not None:
fields |= {
"uv": 0.0 if is_dark_slot(instant.forecast_at) else float(instant.uv_index) if instant.uv_index is not None else None,
"visibility_km": instant.visibility_m / 1000 if instant.visibility_m is not None else None,
"gust_ms": float(instant.wind_gust_ms) if instant.wind_gust_ms is not None else None,
"ground_c": float(instant.soil_temp_c) if instant.soil_temp_c is not None else None,
}
if covering is not None and is_dark_slot(covering.forecast_at):
fields["sunshine_ratio"] = 0.0
elif covering is not None and covering.sunshine_s is not None:
fields["sunshine_ratio"] = min(covering.sunshine_s / 10800, 1.0)
return fields
def windows_for(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
by_om = by_om or {}
start = kst_midnight(day)
out = []
for hours in window_hours(defn, day, region):
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
out.append([replace(_hour(r), hour=h) for h, r in zip(hours, rows) if r is not None])
out.append([
replace(_hour(r), hour=h, **_om_fields(
by_om.get(start + timedelta(hours=_nearest_slot_end_hour(h))), by_om.get(start + timedelta(hours=_slot_end_hour(h)))
))
for h, r in zip(hours, rows) if r is not None
])
return out
@@ -114,10 +150,11 @@ def _lookahead_days(defn) -> int:
def day_result(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool,
by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
) -> Optional[Result]:
"""short(오늘~모레)이거나 시간대가 시간별 예보로 다 채워지면 그대로 계산, 아니면 중기예보로 예상 점수."""
windows = windows_for(defn, day, region, by_at)
windows = windows_for(defn, day, region, by_at, by_om)
if short or all(len(w) == len(h) for w, h in zip(windows, window_hours(defn, day, region))):
return evaluate(defn, windows, replace(ctx, lookahead_rain_prob=lookahead_rain(defn, day, by_at)))
fc = daily.get(day)
@@ -201,6 +238,10 @@ class IndexService:
return ErrorType.EXTERNAL_API_ERROR, None
_, daily_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, today, days[-1] + timedelta(days=2)))
daily = {d.forecast_date: day_forecast(d) for d in daily_rows or []}
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
)
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 = {r.forecast_at: r for r in rows}
base_ctx = dict(
@@ -209,10 +250,12 @@ class IndexService:
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at), today_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
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
if by_om:
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
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]))
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)}
@@ -232,7 +275,7 @@ class IndexService:
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
)
for d in defs:
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS))
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
out.append({
+32 -26
View File
@@ -150,27 +150,25 @@ def _nearest_hour(at: datetime) -> datetime:
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
first = sun_times(today, float(region.lat), float(region.lon))
rows = []
for kind, azimuth in ((SkyType.SUNSET, first.sunset_azimuth), (SkyType.SUNRISE, first.sunrise_azimuth)):
pts = _points(region, azimuth)
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
for i in range(DAYS):
d = today + timedelta(days=i)
st: SunTimes = sun_times(d, float(region.lat), float(region.lon))
sun_at, twilight_at = (st.sunset_at, st.dusk_end_at) if kind is SkyType.SUNSET else (st.sunrise_at, st.dawn_start_at)
hour = _nearest_hour(sun_at)
per_model, highs, model_layers = [], [], []
for model in {k[2] for k in clouds}:
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
for model in {k[4] for k in clouds}:
layers = [clouds.get((region.code, kind.value, km, hour, model)) for km in DISTANCES_KM]
if None in layers:
continue
per_model.append(score(*layers))
highs.append((layers[0].high + layers[1].high) / 2)
highs.append(layers[0].high)
model_layers.append(layers)
if not per_model:
continue
value = round(statistics.mean(per_model))
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(3)))
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
rows.append({
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
"confidence": confidence(per_model).value,
@@ -222,7 +220,7 @@ class SkyService:
LOG.error(f"[sky] spots {region.code}: {err.name}")
near = nearest_spots(lat, lon, spots or [])
first = sun_times(now.date(), lat, lon)
plan = await self._plan(region, first.sunset_azimuth, sunsets, near, now)
plan = await self._plan(region, sunsets, near, now)
return ErrorType.SUCCESS, SkyView(
region=region,
sunset_azimuth=first.sunset_azimuth,
@@ -233,7 +231,7 @@ class SkyService:
plan=plan,
)
async def _plan(self, region: Region, azimuth: int, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
lat, lon = float(region.lat), float(region.lon)
target, st = None, None
@@ -244,15 +242,15 @@ class SkyService:
break
if target is None or st is None:
return None
pts = _points(region, azimuth)
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, pts, _nearest_hour(st.sunset_at)))
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
if err is not ErrorType.SUCCESS:
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
by_point: dict[tuple[float, float], list[Layers]] = {}
by_km: dict[int, list[Layers]] = {}
for r in rows or []:
by_point.setdefault((float(r.lat), float(r.lon)), []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
layers = [mean_layers(by_point[p]) for p in pts if p in by_point]
return build_plan(target, st, layers if len(layers) == len(pts) else None, spots, sunsets, now.date())
if r.kind == SkyType.SUNSET.value:
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
@@ -300,24 +298,32 @@ class SkyService:
plan = {}
for r in regions:
st = sun_times(today, float(r.lat), float(r.lon))
plan[r.code] = _points(r, st.sunset_azimuth) + _points(r, st.sunrise_azimuth)
points = sorted({p for pts in plan.values() for p in pts})
plan[r.code] = {SkyType.SUNSET: _points(r, st.sunset_azimuth), SkyType.SUNRISE: _points(r, st.sunrise_azimuth)}
points = sorted({p for kinds in plan.values() for pts in kinds.values() for p in pts})
try:
async with httpx.AsyncClient(timeout=30) as client:
data = await fetch_clouds(client, points, days=DAYS)
except OpenMeteoRequestFailed as e:
LOG.error(f"[sky] {len(regions)} regions: {e}")
return
needed_hours = {
_nearest_hour(at)
for r in regions
for i in range(DAYS)
for st in [sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))]
for at in (st.sunset_at, st.sunrise_at)
}
cloud_rows = [row for p, d in zip(points, data) for row in parse_clouds(p, d) if row["forecast_at"] in needed_hours]
by_point: dict[tuple[float, float], dict[datetime, list[dict]]] = {}
for p, d in zip(points, data):
for row in parse_clouds(p, d):
by_point.setdefault(p, {}).setdefault(row["forecast_at"], []).append(row)
cloud_rows = []
for r in regions:
for kind, pts in plan[r.code].items():
for i in range(DAYS):
st = sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))
hour = _nearest_hour(st.sunset_at if kind is SkyType.SUNSET else st.sunrise_at)
for km, p in zip(DISTANCES_KM, pts):
cloud_rows += [
{"region_code": r.code, "kind": kind.value, "distance_km": km, "forecast_at": hour, "model": row["model"],
"cloud_low": row["cloud_low"], "cloud_mid": row["cloud_mid"], "cloud_high": row["cloud_high"]}
for row in by_point.get(p, {}).get(hour, [])
]
clouds = {
(float(r["lat"]), float(r["lon"]), r["model"], r["forecast_at"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
(r["region_code"], r["kind"], r["distance_km"], r["forecast_at"], r["model"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
for r in cloud_rows
}
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now)]