From 9dacc86f47eac9fb824517c6455ba29cdf7496c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Wed, 7 Oct 2026 10:07:59 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=B0=A4=20=EA=B5=AC=EA=B0=84(21~06?= =?UTF-8?q?=EC=8B=9C)=20Open-Meteo=20=ED=96=87=EB=B9=9B=20=EA=B0=92(?= =?UTF-8?q?=EC=9D=BC=EC=A1=B0=C2=B7=EC=9D=BC=EC=82=AC=C2=B7=EC=9E=90?= =?UTF-8?q?=EC=99=B8=EC=84=A0)=20=EC=A0=80=EC=9E=A5=20=EC=A0=9C=EC=99=B8,?= =?UTF-8?q?=20=EC=A7=80=EC=88=98=20=EA=B3=84=EC=82=B0=EC=9D=80=200?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/docs/data-pipeline.md | 4 ++-- backend/docs/openmeteo-data.md | 3 ++- backend/services/external/open_meteo.py | 17 ++++++++++++++--- backend/services/index_service.py | 9 ++++++--- backend/tests/test_index_api.py | 14 ++++++++++++++ backend/tests/test_openmeteo_weather.py | 12 ++++++++++++ 6 files changed, 50 insertions(+), 9 deletions(-) diff --git a/backend/docs/data-pipeline.md b/backend/docs/data-pipeline.md index ff60ab6..ee963d0 100644 --- a/backend/docs/data-pipeline.md +++ b/backend/docs/data-pipeline.md @@ -174,10 +174,10 @@ Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸 | 칼럼 | 3시간 구간 값 | |---|---| | `uv_index`, `uv_index_clear_sky`, `visibility_m`, `wind_gust_ms`, `pressure_hpa`, `soil_temp_c` | 구간 끝 시각의 순간값 | -| `sunshine_s` | 직전 3시간 일조 합 (0~10800초). 하루 합이 시간별 합과 같다 | +| `sunshine_s` | 직전 3시간 일조 합 (0~10800초) | | `shortwave_avg_wm2`, `shortwave_max_wm2` | 직전 3시간 일사량 평균, 그중 가장 센 1시간 값 | -구간 끝 시각은 GMT 0·3·6…(= KST 0·3·6…)이다. 직전 3시간이 다 있는 구간만 저장해서 응답 맨 앞 구간은 빠진다. KST 하루의 일조 합은 끝 시각 03~24시 구간 8개이고, 24시 구간은 다음날 00시 행이다. +구간 끝 시각은 GMT 0·3·6…(= KST 0·3·6…)이다. 직전 3시간이 다 있는 구간만 저장해서 응답 맨 앞 구간은 빠진다. 밤 구간(21~06시 = 끝 시각 KST 00·03·06시)은 햇빛 값(`uv_index`, `uv_index_clear_sky`, `sunshine_s`, `shortwave_*`)을 NULL로 둔다. KST 하루의 일조 합은 끝 시각 09~21시 구간 5개다. ## 테스트 diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 3a28352..6d8fecc 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -86,8 +86,9 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100 - `forecast_at`은 3시간 구간의 **끝 시각**이다. GMT 0·3·6… 정시이고 KST로도 0·3·6… 정시라 단기예보 슬롯과 맞는다. - 일조·일사는 Open-Meteo가 "직전 1시간 값"으로 주므로, 끝 시각 t의 구간은 t-2·t-1·t 시 값 3개다. 3시간이 다 있는 구간만 저장한다. - 자외선·가시거리 등 나머지는 끝 시각 t의 순간값이다. +- **밤 구간(21~06시 = 끝 시각 KST 00·03·06시)은 햇빛 값을 저장하지 않는다**: `uv_index`, `uv_index_clear_sky`, `sunshine_s`, `shortwave_avg_wm2`, `shortwave_max_wm2`는 NULL. 가시거리·돌풍·기압·지면온도는 그대로 저장한다. 지수 계산에서는 이 구간을 '정보 없음'이 아니라 자외선 0·일조 0으로 본다 (`is_dark_slot`). - 요청이 UTC 오늘 00시(= KST 09시)부터 96시간이라 한 번에 구간 31개가 나온다 (구 256곳 × 31 = 7,936행). -- **KST 하루의 일조 합**은 끝 시각 03·06·…·24시 구간 8개를 더한다. 24시 구간은 DB에서 **다음날 00시** 행이다. 검증: 종로구 10/6 일조 합이 시간별 합(10.87h)과 같았다. +- **KST 하루의 일조 합**은 끝 시각 09·12·15·18·21시 구간 5개를 더한다 (밤 구간은 NULL). - 일사 평균은 맑은 날에도 피크를 깎는다 (시간별 최대 762 → 3시간 평균 최대 694). 시각별 임계(예: 500W/m²)로 쓸 때는 `shortwave_max_wm2`를 같이 본다. ### 저장·갱신 diff --git a/backend/services/external/open_meteo.py b/backend/services/external/open_meteo.py index da4dfcf..f957f68 100644 --- a/backend/services/external/open_meteo.py +++ b/backend/services/external/open_meteo.py @@ -20,6 +20,14 @@ WEATHER_VARS = ( "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]: @@ -88,7 +96,7 @@ def _round(v, digits: int = 0): def parse_weather(data: dict) -> list[dict]: """시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값. - 직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀).""" + 직전 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)} @@ -101,7 +109,7 @@ def parse_weather(data: dict) -> list[dict]: continue sun = [h["sunshine_duration"][j] for j in span] rad = [h["shortwave_radiation"][j] for j in span] - rows.append({ + 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), @@ -109,5 +117,8 @@ def parse_weather(data: dict) -> list[dict]: "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 diff --git a/backend/services/index_service.py b/backend/services/index_service.py index e9e969f..9a91823 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -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 @@ -100,16 +101,18 @@ def _nearest_slot_end_hour(h: int) -> int: def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict: - """3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음').""" + """3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음'). 밤 구간은 햇빛 값을 받지 않으므로 0으로 본다.""" fields = {} if instant is not None: fields |= { - "uv": float(instant.uv_index) if instant.uv_index is not None else None, + "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 covering.sunshine_s is not 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 diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index bc1a4b3..542d0d1 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -134,6 +134,20 @@ def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_cover assert all(h.uv is None and h.sunshine_ratio is None for h in no_om) +def test_dark_slots_count_as_no_sun_not_unknown(): + day = date(2026, 10, 6) + start = kst_midnight(day) + by_at = { + start + timedelta(hours=h): WeatherHourly( + forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1 + ) + for h in (22, 23) + } + by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)} + hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0] + assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2 + + @pytest.mark.anyio async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: diff --git a/backend/tests/test_openmeteo_weather.py b/backend/tests/test_openmeteo_weather.py index 91ccc0f..4217694 100644 --- a/backend/tests/test_openmeteo_weather.py +++ b/backend/tests/test_openmeteo_weather.py @@ -48,6 +48,18 @@ def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values(): assert rows[6]["sunshine_s"] == 9000 +def test_dark_slots_drop_sun_values_but_keep_others(): + times = [f"2026-10-06T{h:02d}:00" for h in range(24)] + full = {k: [1.0] * 24 for k in ("uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl", "soil_temperature_0cm")} + rows = {r["forecast_at"].hour: r for r in parse_weather({"hourly": {"time": times, "sunshine_duration": [600] * 24, "shortwave_radiation": [50] * 24} | full})} + dark = {15, 18, 21} # GMT 끝 시각 = KST 0·3·6시 (21~06시). KST 21시 구간(18~21시)은 남긴다 + assert sorted(rows) == [3, 6, 9, 12, 15, 18, 21] + for hour, row in rows.items(): + sun = (row["uv_index"], row["uv_index_clear_sky"], row["sunshine_s"], row["shortwave_avg_wm2"], row["shortwave_max_wm2"]) + assert (sun == (None,) * 5) is (hour in dark) + assert row["visibility_m"] == 1 and row["soil_temp_c"] == 1.0 + + @pytest.mark.anyio async def test_refresh_stores_every_region_and_is_repeatable(offline): assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS