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:
commit
3f8f7daeb1
21 files changed
+1068
-111
No files matched your search
+75
-4
@@ -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
|
||||
Reference in new issue
Block a user