From 7c126510682737e189b67aa6830b610813e5555d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Tue, 6 Oct 2026 17:21:59 +0900 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20Open-Meteo=20=EA=B5=AC=EB=A6=84=202?= =?UTF-8?q?0=C2=B7100km=20=EA=B5=AC=20=EC=BD=94=EB=93=9C=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5,=20=EB=B3=B4=EC=A1=B0=EA=B0=92=20=EC=88=98=EC=A7=91,?= =?UTF-8?q?=20=ED=99=9C=EB=8F=99=20=EC=A7=80=EC=88=98=2010=EA=B0=9C?= =?UTF-8?q?=EC=97=90=20=EC=9E=90=EC=99=B8=EC=84=A0=C2=B7=ED=96=87=EB=B9=9B?= =?UTF-8?q?=C2=B7=EA=B0=80=EC=8B=9C=EA=B1=B0=EB=A6=AC=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 구름 - 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용 - cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장 보조값 - openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대) - worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리 - 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE) 지수 - 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시) - 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건 - 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결 - 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가 테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수). --- backend/common/database/model/models.py | 28 +++- backend/crud/sky_crud.py | 10 +- backend/crud/weather_crud.py | 24 +++- backend/postgres-init/init.sql | 38 +++++- backend/router/v1/index/index.py | 6 +- backend/scheduler/jobs.py | 32 +++++ backend/seed/index_definition.json | 168 +++++++++++++++++++++--- backend/services/calc/index_calc.py | 46 ++++++- backend/services/calc/sky_score.py | 10 +- backend/services/external/open_meteo.py | 62 ++++++++- backend/services/index_service.py | 51 ++++++- backend/services/sky_service.py | 40 +++--- backend/tests/conftest.py | 17 ++- backend/tests/test_index_api.py | 83 +++++++++++- backend/tests/test_index_calc.py | 46 ++++++- backend/tests/test_openmeteo_weather.py | 101 ++++++++++++++ backend/tests/test_sky_api.py | 19 +++ backend/tests/test_sky_score.py | 8 +- backend/worker_main.py | 5 +- 19 files changed, 712 insertions(+), 82 deletions(-) create mode 100644 backend/tests/test_openmeteo_weather.py diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index e5ade8e..d4318a9 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -99,8 +99,9 @@ class WeatherWarning(Base): class CloudHourly(Base): __tablename__ = "cloud_hourly" - lat: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True) - lon: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True) + region_code: Mapped[str] = mapped_column(String(10), primary_key=True) + kind: Mapped[int] = mapped_column(SmallInteger, primary_key=True) + distance_km: Mapped[int] = mapped_column(SmallInteger, primary_key=True) forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True) model: Mapped[int] = mapped_column(SmallInteger, primary_key=True) cloud_low: Mapped[int] = mapped_column(SmallInteger) @@ -108,6 +109,23 @@ class CloudHourly(Base): cloud_high: Mapped[int] = mapped_column(SmallInteger) +class OpenMeteoHourly(Base): + __tablename__ = "openmeteo_hourly" + + region_code: Mapped[str] = mapped_column(String(10), primary_key=True) + forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True) + uv_index: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True) + uv_index_clear_sky: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True) + visibility_m: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + wind_gust_ms: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True) + pressure_hpa: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 1), nullable=True) + soil_temp_c: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True) + sunshine_s: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True) + shortwave_avg_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True) + shortwave_max_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True) + fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + + class SkyScore(Base): __tablename__ = "sky_score" @@ -151,6 +169,9 @@ class IndexDefinition(Base): weight_wind: Mapped[int] = mapped_column(SmallInteger) weight_humidity: Mapped[int] = mapped_column(SmallInteger) weight_air: Mapped[int] = mapped_column(SmallInteger) + weight_uv: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") + weight_sun: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") + weight_view: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") weight_time: Mapped[int] = mapped_column(SmallInteger) factor_rules: Mapped[dict] = mapped_column(JSONB) zero_rules: Mapped[list] = mapped_column(JSONB) @@ -172,6 +193,9 @@ class IndexScore(Base): wind_score: Mapped[int] = mapped_column(SmallInteger) humidity_score: Mapped[int] = mapped_column(SmallInteger) air_score: Mapped[int] = mapped_column(SmallInteger) + uv_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") + sun_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") + view_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0") time_score: Mapped[int] = mapped_column(SmallInteger) zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) notes: Mapped[dict] = mapped_column(JSONB) diff --git a/backend/crud/sky_crud.py b/backend/crud/sky_crud.py index 495f96e..8d6b8df 100644 --- a/backend/crud/sky_crud.py +++ b/backend/crud/sky_crud.py @@ -1,6 +1,6 @@ from datetime import date, datetime -from sqlalchemy import and_, delete, or_, select +from sqlalchemy import delete, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession @@ -14,13 +14,13 @@ class SkyCRUD: for i in range(0, len(rows), _CHUNK): stmt = insert(CloudHourly).values(rows[i:i + _CHUNK]) await s.execute(stmt.on_conflict_do_update( - index_elements=["lat", "lon", "forecast_at", "model"], + index_elements=["region_code", "kind", "distance_km", "forecast_at", "model"], set_={k: stmt.excluded[k] for k in ("cloud_low", "cloud_mid", "cloud_high")}, )) - async def clouds_at(self, s: AsyncSession, points: list[tuple[float, float]], at: datetime) -> list[CloudHourly]: - cond = or_(*[and_(CloudHourly.lat == round(lat, 2), CloudHourly.lon == round(lon, 2)) for lat, lon in points]) - return list((await s.scalars(select(CloudHourly).where(cond, CloudHourly.forecast_at == at))).all()) + async def clouds_at(self, s: AsyncSession, region_code: str, at: datetime) -> list[CloudHourly]: + stmt = select(CloudHourly).where(CloudHourly.region_code == region_code, CloudHourly.forecast_at == at) + return list((await s.scalars(stmt)).all()) async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None: if not rows: diff --git a/backend/crud/weather_crud.py b/backend/crud/weather_crud.py index 12322d5..541e6f0 100644 --- a/backend/crud/weather_crud.py +++ b/backend/crud/weather_crud.py @@ -5,7 +5,9 @@ from sqlalchemy import func, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession -from common.database.model.models import SunTime, WeatherDaily, WeatherHourly +from common.database.model.models import OpenMeteoHourly, SunTime, WeatherDaily, WeatherHourly + +_CHUNK = 1000 def _upsert_newer(model, rows: list[dict], keys: list[str]): @@ -27,6 +29,26 @@ class WeatherCRUD: if rows: await s.execute(_upsert_newer(WeatherDaily, rows, ["region_code", "forecast_date"])) + async def upsert_openmeteo(self, s: AsyncSession, rows: list[dict]) -> None: + """같은 (구, 시각)이면 덮어쓰되, 새 응답에서 값이 비어 오면(NULL) 그 칼럼은 이전 값을 지키고 받은 시각만 갱신한다.""" + keys = ["region_code", "forecast_at"] + table = OpenMeteoHourly.__table__ + for i in range(0, len(rows), _CHUNK): + stmt = insert(OpenMeteoHourly).values(rows[i:i + _CHUNK]) + set_ = { + c.name: stmt.excluded[c.name] if c.name == "fetched_at" else func.coalesce(stmt.excluded[c.name], table.c[c.name]) + for c in table.columns if c.name not in keys + } + await s.execute(stmt.on_conflict_do_update(index_elements=keys, set_=set_)) + + async def openmeteo_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[OpenMeteoHourly]: + stmt = ( + select(OpenMeteoHourly) + .where(OpenMeteoHourly.region_code == region_code, OpenMeteoHourly.forecast_at >= start, OpenMeteoHourly.forecast_at <= end) + .order_by(OpenMeteoHourly.forecast_at) + ) + return list((await s.scalars(stmt)).all()) + async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]: return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code)) diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index b7ba1dc..3121ca3 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -37,16 +37,36 @@ CREATE TABLE IF NOT EXISTS public.weather_daily ( PRIMARY KEY (region_code, forecast_date) ); --- 지점별 층별 구름. 노을·일출 점수용 (구마다 해 지는 쪽·뜨는 쪽 20·50·100km 지점). +-- 구별 층별 구름. 출처: Open-Meteo. 노을·일출 점수용 (구 중심에서 해 지는 쪽·뜨는 쪽 20·100km 지점). +-- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 넣는다. CREATE TABLE IF NOT EXISTS public.cloud_hourly ( - lat NUMERIC(5,2) NOT NULL, -- 소수 둘째 자리 반올림 값 - lon NUMERIC(5,2) NOT NULL, - forecast_at TIMESTAMPTZ NOT NULL, + region_code VARCHAR(10) NOT NULL, -- region.code + kind SMALLINT NOT NULL, -- SkyType: 1=일몰 방향 2=일출 방향 + distance_km SMALLINT NOT NULL, -- 구 중심에서 떨어진 거리: 20(머리 위) 또는 100(해 쪽 지평선) + forecast_at TIMESTAMPTZ NOT NULL, -- 일몰·일출에 가장 가까운 정시 model SMALLINT NOT NULL, -- CloudModel: 1=ECMWF 2=GFS 3=JMA 4=ICON (모델끼리 비교해 노을 확신을 낸다) cloud_low SMALLINT NOT NULL, -- 낮은 구름 % (약 2km 아래) cloud_mid SMALLINT NOT NULL, -- 중간 구름 % cloud_high SMALLINT NOT NULL, -- 높은 구름 % (약 6km 위) - PRIMARY KEY (lat, lon, forecast_at, model) + PRIMARY KEY (region_code, kind, distance_km, forecast_at, model) +); + +-- 구별 3시간 간격 날씨 보조값. 출처: Open-Meteo (구 중심 좌표, 모델 지정 없음). 6시간마다 새로 받아 같은 (구, 시각) 줄을 덮어쓴다. +-- forecast_at 은 3시간 구간의 끝 시각(GMT 0·3·6… = KST 0·3·6…). 일조·일사는 그 직전 3시간 값이고 나머지는 끝 시각 순간값이다. +CREATE TABLE IF NOT EXISTS public.openmeteo_hourly ( + region_code VARCHAR(10) NOT NULL, -- region.code + forecast_at TIMESTAMPTZ NOT NULL, -- 3시간 구간의 끝 시각 + uv_index NUMERIC(4,2) NULL, -- 자외선지수 (순간값) + uv_index_clear_sky NUMERIC(4,2) NULL, -- 구름이 없다고 볼 때의 자외선지수 (순간값). uv_index / 이 값 = 구름이 가린 정도 + visibility_m INTEGER NULL, -- 가시거리 m (순간값) + wind_gust_ms NUMERIC(4,1) NULL, -- 돌풍 m/s + pressure_hpa NUMERIC(5,1) NULL, -- 해면기압 hPa (순간값) + soil_temp_c NUMERIC(4,1) NULL, -- 지표면 온도 ℃ (순간값) + sunshine_s SMALLINT NULL, -- 직전 3시간 일조 합 초 (0~10800) + shortwave_avg_wm2 SMALLINT NULL, -- 직전 3시간 전천일사량 평균 W/m² + shortwave_max_wm2 SMALLINT NULL, -- 직전 3시간 중 가장 센 1시간 값 W/m² + fetched_at TIMESTAMPTZ NOT NULL, -- 받은 시각 + PRIMARY KEY (region_code, forecast_at) ); -- 미세먼지 측정소. 출처: 에어코리아 측정소 정보 (하루 1번 갱신). @@ -111,6 +131,9 @@ CREATE TABLE IF NOT EXISTS public.index_score ( wind_score SMALLINT NOT NULL, humidity_score SMALLINT NOT NULL, air_score SMALLINT NOT NULL, + uv_score SMALLINT NOT NULL DEFAULT 0, -- 자외선·햇빛·가시거리은 비중이 있는 지수만 값이 있다 (없으면 0) + sun_score SMALLINT NOT NULL DEFAULT 0, + view_score SMALLINT NOT NULL DEFAULT 0, time_score SMALLINT NOT NULL, zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL) notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...} @@ -231,11 +254,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition ( has_detail BOOLEAN NOT NULL DEFAULT TRUE, -- 계산 근거 화면이 있는지 description VARCHAR(100) NOT NULL, -- 무엇을 재는지 windows JSONB NOT NULL, -- 계산 시간대 [{"from": 18, "to": 24}] 여러 개면 가장 좋은 쪽, {"around": "sunset"} 은 일몰 ±1시간 - weight_temp SMALLINT NOT NULL, -- 6요소 비중 (합 100) + weight_temp SMALLINT NOT NULL, -- 요소 비중 (합 100) weight_rain SMALLINT NOT NULL, weight_wind SMALLINT NOT NULL, weight_humidity SMALLINT NOT NULL, weight_air SMALLINT NOT NULL, + weight_uv SMALLINT NOT NULL DEFAULT 0, -- 자외선 (Open-Meteo). 해당 지수만 0 이 아니다 + weight_sun SMALLINT NOT NULL DEFAULT 0, -- 햇빛 = 해 난 비율 (Open-Meteo 일조) + weight_view SMALLINT NOT NULL DEFAULT 0, -- 가시거리 (Open-Meteo) weight_time SMALLINT NOT NULL, factor_rules JSONB NOT NULL, -- 요소별 점수 규칙 {"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {...}, ...} zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다 diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py index 61ffccb..7c23db9 100644 --- a/backend/router/v1/index/index.py +++ b/backend/router/v1/index/index.py @@ -5,12 +5,12 @@ from fastapi import APIRouter, Depends, Path, Query from common.enums import ErrorType, IndexCategory from common.models.errors import error_info from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, TrendPoint -from services.calc.index_calc import AXES, zero_rules_text +from services.calc.index_calc import AXES, BASE_AXES, zero_rules_text from services.index_service import IndexItem, IndexService router = APIRouter(prefix="/v1/index", tags=["index"]) -_AXIS_LABEL = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "공기", "time": "시간대"} +_AXIS_LABEL = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "공기", "uv": "자외선", "sun": "햇빛", "view": "가시거리", "time": "시간대"} def _summary(i: IndexItem) -> IndexSummary: @@ -50,7 +50,7 @@ async def get_index(index_id: int = Path(...), region: str = Query(..., descript index=_summary(item), description=d.description, factors=[ Factor(axis=a, label=_AXIS_LABEL[a], value=getattr(s, f"{a}_score"), weight=getattr(d, f"weight_{a}"), note=s.notes.get(a, "")) - for a in AXES + for a in AXES if a in BASE_AXES or getattr(d, f"weight_{a}") > 0 ], zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description, ) diff --git a/backend/scheduler/jobs.py b/backend/scheduler/jobs.py index cb837a3..06afb5e 100644 --- a/backend/scheduler/jobs.py +++ b/backend/scheduler/jobs.py @@ -7,9 +7,12 @@ from common.logger import LOG from common.utils.kma_time import now_kst from crud.air_crud import AirCRUD from crud.feed_crud import FeedCRUD +from crud.region_crud import RegionCRUD from crud.season_crud import SeasonCRUD +from crud.weather_crud import WeatherCRUD from services.external.airkorea import fetch_stations, parse_stations from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed +from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather from services.feed_service import build_feed_day, clear_feed_cache _CLEANUP_SQL = [ @@ -20,7 +23,9 @@ _CLEANUP_SQL = [ "DELETE FROM public.sky_score WHERE score_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7", "DELETE FROM public.cloud_hourly WHERE forecast_at < now() - interval '2 days'", "DELETE FROM public.event WHERE end_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 30", + "DELETE FROM public.openmeteo_hourly WHERE forecast_at < now() - interval '7 days'", ] +_OPENMETEO_DAYS = 4 async def cleanup_old_rows() -> ErrorType: @@ -42,6 +47,33 @@ async def refresh_air_stations() -> ErrorType: +async def refresh_openmeteo_weather() -> ErrorType: + """전국 구 중심 좌표의 자외선·가시거리·돌풍·기압·일조·일사·지면온도를 3시간 구간으로 묶어 저장한다.""" + err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s)) + if err is not ErrorType.SUCCESS: + return err + by_point: dict[tuple[float, float], list[str]] = {} + for r in regions: + by_point.setdefault((round(float(r.lat), 2), round(float(r.lon), 2)), []).append(r.code) + points = sorted(by_point) + try: + async with httpx.AsyncClient(timeout=30) as client: + data = await fetch_weather(client, points, days=_OPENMETEO_DAYS) + except OpenMeteoRequestFailed as e: + LOG.error(f"[scheduler] refresh_openmeteo_weather: {e}") + return ErrorType.EXTERNAL_API_ERROR + fetched_at = now_kst() + rows = [ + {"region_code": code, "fetched_at": fetched_at, **slot} + for point, d in zip(points, data) + for slot in parse_weather(d) + for code in by_point[point] + ] + err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)]) + LOG.info(f"[scheduler] refresh_openmeteo_weather {len(points)} points rows {len(rows)}: {err.name}") + return err + + async def build_today_feed() -> ErrorType: """그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다.""" err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD()) diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index dda01fe..7e1cbb4 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -19,6 +19,9 @@ "weight_wind": 15, "weight_humidity": 10, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -79,11 +82,14 @@ "to": 16 } ], - "weight_temp": 30, + "weight_temp": 25, "weight_rain": 25, "weight_wind": 15, - "weight_humidity": 10, + "weight_humidity": 5, "weight_air": 10, + "weight_uv": 10, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -111,6 +117,10 @@ "sun": 100, "holiday": 100, "default": 60 + }, + "uv": { + "zero": 8, + "full": 2 } }, "zero_rules": [ @@ -144,6 +154,9 @@ "weight_wind": 15, "weight_humidity": 15, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -208,6 +221,9 @@ "weight_wind": 15, "weight_humidity": 10, "weight_air": 15, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -282,6 +298,9 @@ "weight_wind": 15, "weight_humidity": 10, "weight_air": 45, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -332,11 +351,14 @@ "to": 12 } ], - "weight_temp": 30, + "weight_temp": 25, "weight_rain": 25, "weight_wind": 20, - "weight_humidity": 10, + "weight_humidity": 5, "weight_air": 10, + "weight_uv": 5, + "weight_sun": 0, + "weight_view": 5, "weight_time": 5, "factor_rules": { "temp": { @@ -365,6 +387,14 @@ "sun": 100, "holiday": 100, "default": 50 + }, + "uv": { + "zero": 8, + "full": 2 + }, + "view": { + "zero": 5, + "full": 20 } }, "zero_rules": [ @@ -404,6 +434,9 @@ "weight_wind": 10, "weight_humidity": 10, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -459,6 +492,9 @@ "weight_wind": 15, "weight_humidity": 15, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -494,6 +530,11 @@ "field": "wind_ms", "op": ">=", "value": 14 + }, + { + "field": "gust_ms", + "op": ">=", + "value": 15 } ], "limit_description": "캠핑장 예약 상황은 반영하지 못해요", @@ -522,8 +563,11 @@ "weight_temp": 35, "weight_rain": 20, "weight_wind": 10, - "weight_humidity": 20, + "weight_humidity": 15, "weight_air": 10, + "weight_uv": 5, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -545,6 +589,10 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 } }, "zero_rules": [ @@ -579,10 +627,13 @@ } ], "weight_temp": 5, - "weight_rain": 15, + "weight_rain": 10, "weight_wind": 5, - "weight_humidity": 10, - "weight_air": 20, + "weight_humidity": 5, + "weight_air": 15, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 15, "weight_time": 45, "factor_rules": { "temp": { @@ -603,6 +654,10 @@ }, "time": { "type": "moon" + }, + "view": { + "zero": 5, + "full": 20 } }, "zero_rules": [ @@ -640,6 +695,9 @@ "weight_wind": 15, "weight_humidity": 10, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -686,6 +744,9 @@ "weight_wind": 10, "weight_humidity": 15, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -734,6 +795,9 @@ "weight_wind": 15, "weight_humidity": 10, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -775,11 +839,14 @@ "to": 16 } ], - "weight_temp": 20, - "weight_rain": 35, - "weight_wind": 20, - "weight_humidity": 20, + "weight_temp": 15, + "weight_rain": 30, + "weight_wind": 15, + "weight_humidity": 10, "weight_air": 0, + "weight_uv": 0, + "weight_sun": 25, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -799,6 +866,10 @@ "time": { "type": "fixed", "value": 100 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -808,7 +879,7 @@ "value": 60 } ], - "limit_description": "집 일조량은 반영하지 못해요", + "limit_description": "집 방향·그늘 일조량은 반영하지 못해요", "sentences": {}, "sort_order": 14 }, @@ -832,6 +903,9 @@ "weight_wind": 30, "weight_humidity": 5, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -871,6 +945,11 @@ "field": "wind_ms", "op": ">=", "value": 10 + }, + { + "field": "gust_ms", + "op": ">=", + "value": 15 } ], "limit_description": "자전거 도로 공사는 반영하지 못해요", @@ -896,11 +975,14 @@ "to": 20 } ], - "weight_temp": 40, + "weight_temp": 35, "weight_rain": 25, "weight_wind": 10, "weight_humidity": 5, "weight_air": 15, + "weight_uv": 5, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -925,6 +1007,10 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 } }, "zero_rules": [ @@ -937,9 +1023,14 @@ "field": "pm25", "op": ">=", "value": 75 + }, + { + "field": "ground_c", + "op": ">=", + "value": 45 } ], - "limit_description": "노면 온도는 실측하지 못해요", + "limit_description": "지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요", "sentences": {}, "sort_order": 16 }, @@ -963,6 +1054,9 @@ "weight_wind": 5, "weight_humidity": 30, "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -1009,6 +1103,9 @@ "weight_wind": 10, "weight_humidity": 35, "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -1055,6 +1152,9 @@ "weight_wind": 5, "weight_humidity": 15, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -1103,6 +1203,9 @@ "weight_wind": 10, "weight_humidity": 5, "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 15, "factor_rules": { "temp": { @@ -1151,6 +1254,9 @@ "weight_wind": 10, "weight_humidity": 5, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -1195,11 +1301,14 @@ "to": 10 } ], - "weight_temp": 30, + "weight_temp": 25, "weight_rain": 30, "weight_wind": 10, "weight_humidity": 15, "weight_air": 10, + "weight_uv": 5, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { @@ -1224,6 +1333,10 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 } }, "zero_rules": [ @@ -1252,11 +1365,14 @@ "hours": 1 } ], - "weight_temp": 15, + "weight_temp": 10, "weight_rain": 25, "weight_wind": 10, "weight_humidity": 5, - "weight_air": 15, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 10, "weight_time": 30, "factor_rules": { "temp": { @@ -1280,6 +1396,10 @@ }, "time": { "type": "sunset_score" + }, + "view": { + "zero": 5, + "full": 20 } }, "zero_rules": [ @@ -1313,6 +1433,9 @@ "weight_wind": 10, "weight_humidity": 5, "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -1371,6 +1494,9 @@ "weight_wind": 10, "weight_humidity": 5, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { @@ -1420,6 +1546,9 @@ "weight_wind": 15, "weight_humidity": 5, "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 15, "factor_rules": { "temp": { @@ -1468,6 +1597,9 @@ "weight_wind": 10, "weight_humidity": 0, "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, "weight_time": 5, "factor_rules": { "temp": { diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 2d4f99f..a6968fe 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -6,7 +6,9 @@ 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") +# 모든 지수의 상세에 늘 나오는 축. 나머지(자외선·햇빛·가시거리)는 비중이 있는 지수에만 나온다. +BASE_AXES = ("temp", "rain", "wind", "humidity", "air", "time") _WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun") _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") _UNKNOWN = 70 @@ -23,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) @@ -118,6 +126,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": @@ -147,8 +173,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 zero_text(r: dict) -> str: @@ -179,7 +208,7 @@ def _summary(hours: list[Hour]) -> 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 for hours in windows: if not hours: @@ -188,12 +217,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), "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()} @@ -205,6 +242,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: diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index d3b4456..799a14b 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -4,7 +4,7 @@ from datetime import datetime, timedelta from common.enums import Confidence, SkyGrade, 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)) diff --git a/backend/services/external/open_meteo.py b/backend/services/external/open_meteo.py index 87e7adc..da4dfcf 100644 --- a/backend/services/external/open_meteo.py +++ b/backend/services/external/open_meteo.py @@ -1,12 +1,12 @@ import asyncio -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import httpx from common.enums import CloudModel 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 @@ -15,6 +15,11 @@ 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 async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]: @@ -31,6 +36,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) @@ -40,7 +49,23 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa except (httpx.HTTPError, ValueError) as e: last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip() await asyncio.sleep(1.0 * (attempt + 1)) - raise OpenMeteoRequestFailed(f"forecast {len(points)} points: {last}") + raise OpenMeteoRequestFailed(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)] + results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks]) + return [d for r in results for d in r] + + +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]: @@ -55,3 +80,34 @@ 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] + rows.append({ + "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))), + }) + return rows diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 24c0951..0bb3177 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -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, WeatherHourly +from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, 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 @@ -58,8 +58,36 @@ def _hour(r: WeatherHourly) -> Hour: ) -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시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음').""" + fields = {} + if instant is not None: + fields |= { + "uv": 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: + 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 w in defn.windows: @@ -69,7 +97,12 @@ def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHo else: hours = range(w["from"], w["to"]) 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 @@ -140,6 +173,10 @@ class IndexService: return err, None if not rows: return ErrorType.EXTERNAL_API_ERROR, None + 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( @@ -148,10 +185,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) 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)) if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at: return ErrorType.SUCCESS, weather_result.score if weather_result else None @@ -171,7 +210,7 @@ class IndexService: ) for d in defs: day_ctx = replace(ctx, lookahead_rain_prob=lookahead_rain(d, day, by_at)) - result = evaluate(d, windows_for(d, day, region, by_at), day_ctx) + result = evaluate(d, windows_for(d, day, region, by_at, by_om), day_ctx) if result is None: continue out.append({ diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py index a817432..4ccdf84 100644 --- a/backend/services/sky_service.py +++ b/backend/services/sky_service.py @@ -66,10 +66,8 @@ 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)) @@ -77,12 +75,12 @@ def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> lis hour = _nearest_hour(sun_at) per_model = [] highs = [] - 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) if not per_model: continue value = round(statistics.mean(per_model)) @@ -174,24 +172,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)] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index f35ce35..2b95baf 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -41,7 +41,7 @@ def anyio_backend(): _VOLATILE = ( - "weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time", + "weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time", "sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users", ) @@ -67,8 +67,9 @@ async def _async(v): @pytest.fixture def offline(monkeypatch): """외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다.""" - from datetime import timedelta + from datetime import datetime, timedelta, timezone + 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 @@ -95,6 +96,17 @@ def offline(monkeypatch): h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)} return _async([{"hourly": h} for _ in points]) + def openmeteo_weather(client, points, days=4): + start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) + times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)] + n = len(times) + h = { + "time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n, + "wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n, + "shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n, + } + return _async([{"hourly": h} for _ in points]) + 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")]))) @@ -105,6 +117,7 @@ def offline(monkeypatch): }])) monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([])) monkeypatch.setattr(sky_service, "fetch_clouds", clouds) + monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather) monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {}))) monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([])) monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{ diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 36e9ee0..187d544 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -1,4 +1,5 @@ -from datetime import timedelta +from datetime import date, timedelta +from types import SimpleNamespace import pytest from httpx import ASGITransport, AsyncClient @@ -6,8 +7,12 @@ from httpx import ASGITransport, AsyncClient import services.air_service as air_service import services.warning_service as warning_service import services.weather_service as weather_service +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import OpenMeteoHourly, WeatherHourly from common.utils.kma_time import kst_midnight, now_kst +from crud.weather_crud import WeatherCRUD from router.router import app +from services.index_service import _nearest_slot_end_hour, _slot_end_hour, windows_for REGION = "1141000000" @@ -66,3 +71,79 @@ async def test_index_detail_has_six_factors_and_rules(fakes): assert sum(f["weight"] for f in body["factors"]) == 100 assert body["zero_rules"] == "비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점" assert body["limit"].startswith("모기") + + +def _om_row(at, **over): + row = { + "region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0, + "visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0, + "sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600, + } + return row | over + + +async def _put_om(rows): + await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)]) + + +async def _laundry_sun(client): + items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"] + index_id = next(i["index_id"] for i in items if i["code"] == "laundry") + body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json() + return {f["axis"]: f for f in body["factors"]} + + +def test_slot_end_hours_for_covering_and_nearest_slot(): + hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26) + assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27] + assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27] + + +def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot(): + 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 range(7, 16) + } + by_om = { + start + timedelta(hours=end): OpenMeteoHourly( + forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0 + ) + for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800)) + } + morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om) + assert [h.uv for h in morning] == [1.0, 1.0] + assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시) + assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합) + assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0 + no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0] + assert all(h.uv is None and h.sunshine_ratio is None for h in no_om) + + +@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: + laundry = await _laundry_sun(client) + yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"] + assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음" + assert sum(f["weight"] for f in laundry.values()) == 100 + assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"] + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"] + stars_id = next(i["index_id"] for i in items if i["code"] == "stars") + stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"] + assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리" + + +@pytest.mark.anyio +async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes): + today = kst_midnight(now_kst().date()) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + before = await _laundry_sun(client) + assert before["sun"]["value"] == 70 + await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)]) + after = await _laundry_sun(client) + assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%" diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 506efd4..791c451 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -2,7 +2,7 @@ from datetime import date, datetime, timezone from types import SimpleNamespace from common.enums import RainType, Sky -from services.calc.index_calc import Context, Hour, evaluate, rain_score, temp_score, zero_rules_text +from services.calc.index_calc import Context, Hour, evaluate, rain_score, sun_score, temp_score, uv_score, view_score, zero_rules_text from services.calc.moon import illumination CTX = Context(day=date(2026, 10, 2), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=80, wind_warning=False, lookahead_rain_prob=0) @@ -20,8 +20,8 @@ def _defn(**kw): return SimpleNamespace(**{**base, **kw}) -def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR): - return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky) +def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR, **extra): + return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky, **extra) def test_perfect_evening_scores_100(): @@ -80,3 +80,43 @@ def test_zero_rules_text(): def test_moon_full_and_new(): assert illumination(datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)) < 0.01 assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95 + + +def test_uv_sun_view_scores_are_linear_and_unknown_is_70(): + assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0 + assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100 + assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0 + assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70) + assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0" + assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음" + + +def _uv_defn(): + rules = _defn().factor_rules | {"uv": {"zero": 8, "full": 2}} + return _defn(weight_temp=25, weight_humidity=5, weight_uv=10, factor_rules=rules) + + +def test_weighted_uv_axis_lowers_score_when_uv_is_high_and_is_unknown_when_missing(): + low = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0)]], CTX) + high = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX) + missing = evaluate(_uv_defn(), [[_h(19, wind=1.0)]], CTX) + assert low.score == 100 and low.factors["uv"] == 100 + assert high.factors["uv"] == 0 and high.score < 80 + assert missing.factors["uv"] == 70 and missing.notes["uv"] == "자외선 정보 없음" + + +def test_unweighted_new_axes_do_not_affect_score_and_use_max_uv_in_window(): + plain = evaluate(_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX) + assert plain.score == 100 and plain.factors["uv"] == 0 + window = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0), _h(20, wind=1.0, uv=9.0)]], CTX) + assert window.factors["uv"] == 0 + + +def test_gust_and_ground_temperature_zero_rules(): + gust = _defn(zero_rules=[{"field": "gust_ms", "op": ">=", "value": 15}]) + assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=16.0)]], CTX).score == 0 + assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100 + assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다 + ground = [{"field": "ground_c", "op": ">=", "value": 45}] + assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 바로 0점" + assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이면" diff --git a/backend/tests/test_openmeteo_weather.py b/backend/tests/test_openmeteo_weather.py new file mode 100644 index 0000000..91ccc0f --- /dev/null +++ b/backend/tests/test_openmeteo_weather.py @@ -0,0 +1,101 @@ +import pytest +from sqlalchemy import text + +import scheduler.jobs as jobs +from common.database.db_session_manager import DB_SESSION_MNG +from common.enums import ErrorType +from services.external.open_meteo import OpenMeteoRequestFailed, parse_weather + +SLOTS_PER_REGION = 31 # 96시간 응답에서 직전 3시간이 다 있는 3시간 구간 (끝 시각 03시 ~ 다음다음다음날 21시) + + +def _hourly(**over): + times = [f"2026-10-06T{h:02d}:00" for h in range(9)] + base = { + "time": times, + "uv_index": [round(0.1 * h, 1) for h in range(9)], + "uv_index_clear_sky": [round(0.2 * h, 1) for h in range(9)], + "visibility": [10000.0 + h for h in range(9)], + "wind_gusts_10m": [1.0 + h for h in range(9)], + "pressure_msl": [1000.0 + h for h in range(9)], + "sunshine_duration": [0, 600, 1200, 1800, 2400, 3000, 3600, 3600, 3600], + "shortwave_radiation": [0, 10, 20, 30, 40, 60, 100, 200, 300], + "soil_temperature_0cm": [10.0 + h for h in range(9)], + } + return {"hourly": base | over} + + +def test_three_hour_slots_sum_sunshine_and_average_radiation(): + rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly())} + assert sorted(rows) == [3, 6] # 00시 구간은 앞 두 시간이 없어 만들지 않는다 + assert rows[3]["sunshine_s"] == 600 + 1200 + 1800 + assert rows[3]["shortwave_avg_wm2"] == 20 and rows[3]["shortwave_max_wm2"] == 30 + assert rows[6]["sunshine_s"] == 2400 + 3000 + 3600 + assert rows[6]["shortwave_avg_wm2"] == 67 and rows[6]["shortwave_max_wm2"] == 100 + + +def test_other_values_are_taken_at_slot_end(): + row = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}[6] + assert row["uv_index"] == 0.6 and row["uv_index_clear_sky"] == 1.2 + assert row["visibility_m"] == 10006 and row["wind_gust_ms"] == 7.0 + assert row["pressure_hpa"] == 1006.0 and row["soil_temp_c"] == 16.0 + + +def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values(): + sun = [0, 600, None, 1800, 2400, 3000, 3600, 3600, 3600] + rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly(sunshine_duration=sun))} + assert rows[3]["sunshine_s"] is None and rows[3]["uv_index"] == 0.3 + assert rows[6]["sunshine_s"] == 9000 + + +@pytest.mark.anyio +async def test_refresh_stores_every_region_and_is_repeatable(offline): + assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS + first = await _counts() + assert first["regions"] == 256 and first["rows"] == 256 * SLOTS_PER_REGION and first["slots"] == SLOTS_PER_REGION + + assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS + assert (await _counts())["rows"] == first["rows"] + + +@pytest.mark.anyio +async def test_refresh_failure_returns_error_and_stores_nothing(offline, monkeypatch): + async def fail(client, points, days=4): + raise OpenMeteoRequestFailed("boom") + + monkeypatch.setattr(jobs, "fetch_weather", fail) + assert await jobs.refresh_openmeteo_weather() is ErrorType.EXTERNAL_API_ERROR + assert (await _counts())["rows"] == 0 + + +async def _counts() -> dict: + err, res = await DB_SESSION_MNG.execute_lambda( + lambda s: s.execute(text("SELECT count(*) AS rows, count(DISTINCT region_code) AS regions, count(DISTINCT forecast_at) AS slots FROM openmeteo_hourly")) + ) + return dict(res.one()._mapping) + + +@pytest.mark.anyio +async def test_upsert_keeps_previous_value_when_new_value_is_missing(): + from datetime import datetime, timedelta, timezone + + from crud.weather_crud import WeatherCRUD + + at = datetime(2026, 10, 6, 3, tzinfo=timezone.utc) + first = { + "region_code": "1144000000", "forecast_at": at, "fetched_at": at, "uv_index": 3.0, "uv_index_clear_sky": 3.5, + "visibility_m": 20000, "wind_gust_ms": 4.0, "pressure_hpa": 1015.0, "soil_temp_c": 18.0, + "sunshine_s": 3600, "shortwave_avg_wm2": 300, "shortwave_max_wm2": 400, + } + second = first | {"fetched_at": at + timedelta(hours=6), "uv_index": None, "sunshine_s": None, "visibility_m": 15000} + + for row in (first, second): + await DB_SESSION_MNG.execute_lambda_run([lambda s, r=row: WeatherCRUD().upsert_openmeteo(s, [r])]) + + err, res = await DB_SESSION_MNG.execute_lambda( + lambda s: s.execute(text("SELECT uv_index, sunshine_s, visibility_m, fetched_at FROM openmeteo_hourly WHERE region_code = '1144000000'")) + ) + row = res.one() + assert float(row.uv_index) == 3.0 and row.sunshine_s == 3600 # 비어 온 값은 이전 값 유지 + assert row.visibility_m == 15000 # 값이 있으면 덮어씀 + assert row.fetched_at == second["fetched_at"] diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py index 68c7300..8f260e6 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -63,3 +63,22 @@ async def test_sky_ranking_has_30_spots_sorted(monkeypatch, clean): scores = [i["score"] for i in body["items"]] assert len(scores) == 30 and scores == sorted(scores, reverse=True) assert body["items"][0]["rank"] == 1 and body["items"][0]["note"] + + +@pytest.mark.anyio +async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean): + async def fake_fetch(client, points, days=3): + return _fake_response(points, days) + + monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + await client.get("/v1/sky", params={"region": "1144000000"}) + + err, rows = await DB_SESSION_MNG.execute_lambda( + lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'")) + ) + rows = rows.all() + assert len(rows) == 2 * 2 * 3 * 2 + assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)} + assert {r.model for r in rows} == {3, 4} + assert len({r.forecast_at for r in rows}) == 6 diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index fc1f66c..8a64a26 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -9,21 +9,21 @@ CLEAR = Layers(0, 0, 0) def test_high_clouds_overhead_and_clear_horizon_is_best(): canvas = Layers(low=0, mid=20, high=50) - assert score(canvas, canvas, CLEAR) == 100 + assert score(canvas, CLEAR) == 100 def test_clear_sky_is_only_soft(): - assert grade(score(CLEAR, CLEAR, CLEAR)) is SkyGrade.SOFT + assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT def test_low_clouds_toward_sun_block_the_light(): canvas = Layers(low=0, mid=20, high=50) - assert grade(score(canvas, canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY + assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY def test_overcast_low_clouds_is_gray(): gray = Layers(low=100, mid=100, high=100) - assert grade(score(gray, gray, gray)) is SkyGrade.GRAY + assert grade(score(gray, gray)) is SkyGrade.GRAY def test_confidence_from_model_spread(): diff --git a/backend/worker_main.py b/backend/worker_main.py index 5ce4acd..d62f730 100644 --- a/backend/worker_main.py +++ b/backend/worker_main.py @@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler from common.database.db_session_manager import DB_SESSION_MNG from common.logger import LOG -from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations +from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_openmeteo_weather async def daily() -> None: @@ -17,8 +17,9 @@ async def daily() -> None: async def main() -> None: scheduler = AsyncIOScheduler(timezone="Asia/Seoul") scheduler.add_job(daily, "cron", hour=3, minute=0, max_instances=1, coalesce=True) + scheduler.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True) scheduler.start() - LOG.info("[worker] started, daily job at 03:00 KST") + LOG.info("[worker] started, daily job at 03:00 KST, openmeteo job at 03·09·15·21:10 KST") stop = asyncio.Event() loop = asyncio.get_running_loop() From 4caee53d6d6607e2364dfe6b88ed3f96b0da46ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Tue, 6 Oct 2026 17:22:05 +0900 Subject: [PATCH 2/3] =?UTF-8?q?docs:=20Open-Meteo=20=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=84=B0=20=EB=AC=B8=EC=84=9C=20=EC=B6=94=EA=B0=80,=20?= =?UTF-8?q?=EB=8D=B0=EC=9D=B4=ED=84=B0=20=ED=9D=90=EB=A6=84=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EC=97=90=20=EB=B3=B4=EC=A1=B0=EA=B0=92=C2=B7=EC=8A=A4?= =?UTF-8?q?=EC=BC=80=EC=A4=84=20=EC=98=88=EC=99=B8=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - openmeteo-data.md 신규: 구름(JMA·ICON, 20·100km)과 보조값 변수·3시간 집계·저장·갱신·호출량, 활동 지수 적용 방식과 적용 전후, 알려진 한계, DB 적용 SQL - data-pipeline.md: Open-Meteo 보조값 행, 6시간마다 수집 예외 원칙, 7일 정리 규칙 - README.md 문서 목차에 openmeteo-data.md 추가 --- backend/docs/README.md | 1 + backend/docs/data-pipeline.md | 21 ++- backend/docs/openmeteo-data.md | 270 +++++++++++++++++++++++++++++++++ 3 files changed, 288 insertions(+), 4 deletions(-) create mode 100644 backend/docs/openmeteo-data.md diff --git a/backend/docs/README.md b/backend/docs/README.md index e447b52..6d223b0 100644 --- a/backend/docs/README.md +++ b/backend/docs/README.md @@ -4,6 +4,7 @@ |---|---|---| | `../../docs/데이터지도.html` | 데이터 지도: 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ | | `data-pipeline.md` (`.html` 은 같은 내용) | 외부 API를 언제 받아 어디에 저장·캐시하는지, 피드 칸, 하루 1번 스케줄, 테스트 DB | https://claude.ai/artifact/A4cE22L5aPnMfU53mKCSps | +| `openmeteo-data.md` | Open-Meteo로 받는 구름(JMA·ICON, 20·100km)과 보조값(자외선·가시거리·돌풍·기압·일조·일사·지면온도)의 변수, 3시간 집계, 저장·갱신, 호출량, 지수 활용 후보, DB 적용 SQL | - | | `api.html` | API 목록, 응답 예시, 프론트 연결(Hey API) | https://claude.ai/artifact/LjVYpLzomBTrkMxjDvAoDD | | `index-draft.html` | 활동 지수 기준 초안 (실제 값은 `seed/index_definition.json`) | https://claude.ai/artifact/RrgaKozLCycwduymWPXz4s | | `api-codegen.html` | 프론트 코드 생성 도구 비교 (Hey API 로 결정) | https://claude.ai/artifact/FPuknSnajrmxTM7hEpPKek | diff --git a/backend/docs/data-pipeline.md b/backend/docs/data-pipeline.md index 75ec129..ff60ab6 100644 --- a/backend/docs/data-pipeline.md +++ b/backend/docs/data-pipeline.md @@ -9,7 +9,7 @@ 3. 계산(체감기온, 지수, 노을 점수)은 **데이터가 들어올 때 한 번** 하고 저장한다. 4. **그날 카드는 처음부터 다 보인다.** 매일 03:00 스케줄러가 그날 카드(`post`)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다. 5. **Redis**는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다. -6. 스케줄은 **하루 1번**(매일 03:00, worker)만 돈다. +6. 스케줄은 **하루 1번**(매일 03:00, worker)이 기본이다. 예외로 Open-Meteo 보조값(`openmeteo_hourly`)만 **6시간마다**(03·09·15·21시 10분) 구 전체를 한꺼번에 받는다. ## 한눈에 @@ -18,7 +18,8 @@ | 시간별·하루 날씨 | 기상청 단기예보 | 새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때 | `weather_hourly` `weather_daily` | 피드 완성본에 포함 | | 앞으로 2시간 비 | 기상청 초단기예보 | 매시 45분 이후 그 구를 처음 볼 때 | 저장 안 함 | `ultra:{구}` | | 4~7일 뒤 날씨 | 기상청 중기예보 | 새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때 | `weather_daily` (단기예보가 8시간 미만인 날은 중기 값 유지) | — | -| 층별 구름 | Open-Meteo (ECMWF·GFS·JMA·ICON) | 오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청 | `cloud_hourly` (일출·일몰 시각 값만) | — | +| 층별 구름 | Open-Meteo (JMA·ICON) | 오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 구마다 해 지는 쪽·뜨는 쪽 20·100km 지점 4곳, 좌표 24개씩 나눠 동시에 요청 | `cloud_hourly` (구 코드 키, 일출·일몰 시각 값만, 모델별) | — | +| 자외선·가시거리·돌풍·기압·일조·일사·지면온도 | Open-Meteo (구 중심 좌표, 모델 지정 없음) | **6시간마다 worker가 전국 256곳 일괄** (03·09·15·21시 10분). 좌표 24개씩 요청 11번, 하루 44번 | `openmeteo_hourly` (3시간 구간 끝 시각 키. 일조는 3시간 합, 일사는 평균·최대, 나머지는 끝 시각 값) | — | | 미세먼지 | 에어코리아 실시간 | 매시 20분 이후 처음 볼 때, 전국 1번 | `air_quality` | — | | 기상특보 | 기상청 기상특보 | 매시 정각 이후 처음 볼 때, 전국 1번 | `weather_warning` | — | | 축제·행사 | TourAPI (`lDongRegnCd` = 구 코드 앞 2자리) | 그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌 | `event` | — | @@ -96,7 +97,7 @@ Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸 | 에어코리아 측정소 | `https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList` | 전국 측정소 | | TourAPI 축제 | `https://apis.data.go.kr/B551011/KorService2/searchFestival2` (지역은 `lDongRegnCd`, `areaCode` 아님) | 시도 1곳 | | 천문연 특일정보 | `https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo` | 1개월 | -| Open-Meteo | `https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high` | 좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음) | +| Open-Meteo | `https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high` | 좌표 여러 개, 3일. JMA·ICON 모델 사용 (ECMWF·GFS는 쓰지 않음, KMA 모델은 값이 비어 있음) | ## 계산 (데이터가 들어올 때 한 번) @@ -163,9 +164,21 @@ Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸 | 하는 일 | 이유 | |---|---| | 그날 피드 카드를 `post`에 넣고 Redis `feed:*` 비우기 | 하루 카드 목록 | -| 7일 지난 날씨·해 시각·각 점수·노을 점수, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기 | 테이블이 계속 커지지 않게 | +| 7일 지난 날씨·해 시각·각 점수·노을 점수·Open-Meteo 보조값, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기 | 테이블이 계속 커지지 않게 | | 에어코리아 측정소 목록 갱신 (전국 1번) | 측정소가 새로 생기거나 없어질 때 반영 | +## Open-Meteo 보조값 (6시간마다, worker) + +구름 외에 노을 점수에 쓰지 않는 값을 구 중심 좌표로 받아 둔다. 아직 지수 계산이나 API는 이 값을 쓰지 않는다. + +| 칼럼 | 3시간 구간 값 | +|---|---| +| `uv_index`, `uv_index_clear_sky`, `visibility_m`, `wind_gust_ms`, `pressure_hpa`, `soil_temp_c` | 구간 끝 시각의 순간값 | +| `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시 행이다. + ## 테스트 `pytest`는 개발 DB를 건드리지 않는다. 실행할 때마다 `nalssigak_test` DB를 `init.sql`로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (`tests/conftest.py`의 `offline`). diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md new file mode 100644 index 0000000..802ae1f --- /dev/null +++ b/backend/docs/openmeteo-data.md @@ -0,0 +1,270 @@ +# Open-Meteo 데이터 + +Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장 방식. 인증키는 쓰지 않는다. 전체 데이터 흐름은 `data-pipeline.md`, 이 문서는 Open-Meteo 쪽만 자세히 적는다. + +> 수치(소요 시간, 값 분포 등)는 2026-10-06 로컬에서 실제 호출해 잰 값이다. 운영에서 달라질 수 있다. + +## 한눈에 + +| 구분 | 테이블 | 담는 것 | 좌표 | 모델 | 언제 받나 | +|---|---|---|---|---|---| +| 층별 구름 | `cloud_hourly` | 저·중·상층 구름 %. 노을·일출 점수용 | 구마다 해 지는 쪽·뜨는 쪽 **20·100km 지점 4곳** | **JMA·ICON** 각각 | 사용자가 볼 때. 오전·13시 이후·21시 이후 구별 하루 3번 | +| 보조값 | `openmeteo_hourly` | 자외선·가시거리·돌풍·기압·일조·일사·지면온도 | **구 중심 1곳** (256곳) | 지정 안 함 (Open-Meteo 기본) | worker가 03·09·15·21시 10분(KST)에 전국 일괄 | + +두 테이블은 서로 다른 출처·좌표·주기로 쌓이고 합쳐지지 않는다. 보조값은 활동 지수 10개의 점수에 쓰인다 (3절). + +## 1. 층별 구름 (`cloud_hourly`) + +### 저장 구조 + +| 칼럼 | 설명 | +|---|---| +| `region_code`, `kind`, `distance_km`, `forecast_at`, `model` | 키. `kind` 1=일몰 방향 2=일출 방향, `distance_km` 20 또는 100, `model` 3=JMA 4=ICON | +| `cloud_low`, `cloud_mid`, `cloud_high` | 낮은(약 2km 아래)·중간·높은(약 6km 위) 구름 % | + +- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 저장한다. 구마다 2종류 × 2거리 × 3일 × 2모델 = **24행**. +- 정리: 예보 시각이 **2일** 지난 행을 매일 03:00에 지운다. + +### 좌표와 시각 + +1. 그날 일몰·일출 방위각을 계산한다 (`services/calc/sun.py`). 오늘 값 하나를 3일치에 같이 쓴다. +2. 구 중심에서 그 방향으로 20km, 100km 떨어진 점을 구한다 (`common/utils/geo.py`의 `destination`, 소수 둘째 자리 반올림). +3. 일몰(일출) 시각에서 가장 가까운 정시(30분을 더해 정시로 내림, GMT)의 값을 쓴다. + +### 점수에 쓰는 방식 (`services/calc/sky_score.py`) + +| 거리 | 쓰는 값 | 역할 | +|---|---|---| +| 20km | 저·중·상층 | 머리 위 하늘. 중·상층 구름이 50% 안팎이면 물들고, 저층이 많으면 가려져 감점 | +| 100km | 저층 + 중층(절반) | 해 쪽 지평선. 막히면 햇빛이 못 들어와 전체를 최대 75% 깎음 | + +``` +canvas = max(mid20, high20) +f_canvas = 0.3 (canvas < 10) / max(0, 1 - |canvas-50|/50) +f_near = 1 - 0.8 × low20 / 100 +light = 1 - min(low100 + 0.5×mid100, 100) / 100 +점수 = round(100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)) +``` + +- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. +- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림. + +### 이렇게 정한 이유 (검증 기록) + +- **20·100km 두 지점**: 기존 6점(20·50·100km)과 같은 구름 데이터로 비교하면 점수 차이 평균 0.4점, 최대 7점, 상관 0.97, 등급 일치 185/186 (구 31곳 × 3일 × 일몰/일출). 20km 한 점만 쓰면 상관이 0.18~0.28로 떨어져 구 순위가 맞지 않는다. 50km는 20km와 역할이 겹친다. +- **JMA·ICON 두 모델**: 4모델(ECMWF·GFS·JMA·ICON) 평균과 비교하면 점수 차이 평균 1.9점, 최대 12점, 상관 0.91, 등급 일치 166/186. 모델 2개라 신뢰도 "낮음"이 186개 중 3개 나온다 (4모델은 0개). 구름이 거의 없는 날 데이터라 흐린 날에는 다를 수 있다. +- 모델 성격(로컬 데이터 기준): ICON이 구름을 가장 많이 보고하고(저층 평균 10.4%), JMA는 중층을 상대적으로 많이 본다(평균 3.7%). 같은 지점·시각에서 한 층이라도 30%p 이상 갈리는 비율이 23%였다. 어느 모델이 한국 실제 구름과 맞는지는 관측으로 검증하지 않았다. + +### 호출량 + +- 구마다 좌표 4개. 좌표 24개씩 나눠 동시에 요청하므로 요청 수는 `ceil(좌표 수 / 24)`. +- 한 시간대에 전국 256곳을 한꺼번에 갱신하면 좌표 1,024개, 요청 43번. 구별로 따로 갱신하면 구마다 1번. +- 구별 하루 최대 3번 갱신 (Redis 마커 `sky:{구}:{날짜}:{시간대}`, 24시간). + +## 2. 보조값 (`openmeteo_hourly`) + +### 받는 변수 + +요청: `hourly=<아래 8개>`, `wind_speed_unit=ms`, `forecast_days=4`, `timezone=GMT`, 모델 미지정. 좌표 24개씩 묶어 11번을 동시에 보낸다. + +| Open-Meteo 변수 | 단위 | 칼럼 | 3시간 구간 값 | +|---|---|---|---| +| `uv_index` | 지수 | `uv_index` | 구간 끝 시각 값 | +| `uv_index_clear_sky` | 지수 | `uv_index_clear_sky` | 구간 끝 시각 값. `uv_index ÷ 이 값` = 구름이 해를 가린 정도 | +| `visibility` | m | `visibility_m` | 구간 끝 시각 값 | +| `wind_gusts_10m` | m/s | `wind_gust_ms` | 구간 끝 시각 값 | +| `pressure_msl` | hPa | `pressure_hpa` | 구간 끝 시각 값 | +| `soil_temperature_0cm` | ℃ | `soil_temp_c` | 구간 끝 시각 값 | +| `sunshine_duration` | 초 | `sunshine_s` | **직전 3시간 합** (0~10,800) | +| `shortwave_radiation` | W/m² | `shortwave_avg_wm2`, `shortwave_max_wm2` | 직전 3시간 **평균**, 그중 가장 센 1시간 값 **최대** | + +- 모델을 지정하지 않는 이유: `models`를 지정하면 자외선이 GFS에서만 값이 오고 ECMWF·JMA·ICON은 전부 null이었다. 지정하지 않으면 Open-Meteo가 고른 값 하나가 오는데 어느 모델인지는 응답에 없다. 그래서 이 테이블은 모델별 비교(신뢰도)를 할 수 없다. +- 구 중심 256곳 전부, 4일(96시간) 동안 8개 변수 모두 값이 왔고 null은 없었다. + +### 시각 규칙 + +- `forecast_at`은 3시간 구간의 **끝 시각**이다. GMT 0·3·6… 정시이고 KST로도 0·3·6… 정시라 단기예보 슬롯과 맞는다. +- 일조·일사는 Open-Meteo가 "직전 1시간 값"으로 주므로, 끝 시각 t의 구간은 t-2·t-1·t 시 값 3개다. 3시간이 다 있는 구간만 저장한다. +- 자외선·가시거리 등 나머지는 끝 시각 t의 순간값이다. +- 요청이 UTC 오늘 00시(= KST 09시)부터 96시간이라 한 번에 구간 31개가 나온다 (구 256곳 × 31 = 7,936행). +- **KST 하루의 일조 합**은 끝 시각 03·06·…·24시 구간 8개를 더한다. 24시 구간은 DB에서 **다음날 00시** 행이다. 검증: 종로구 10/6 일조 합이 시간별 합(10.87h)과 같았다. +- 일사 평균은 맑은 날에도 피크를 깎는다 (시간별 최대 762 → 3시간 평균 최대 694). 시각별 임계(예: 500W/m²)로 쓸 때는 `shortwave_max_wm2`를 같이 본다. + +### 저장·갱신 + +| 항목 | 규칙 | +|---|---| +| 수집 | worker가 03·09·15·21시 10분(KST). 정각이 아닌 이유는 03:00 일일 작업과 겹치지 않게 하려는 것 | +| 소요 시간 | 요청 11번 동시 호출 약 2.6~4.6초, 파싱 0.08초, 전체 약 5초 (DB 저장 7,936행 포함) | +| 덮어쓰기 | `ON CONFLICT (region_code, forecast_at)`로 같은 (구, 시각)을 새 값으로 바꾼다. 이력은 남지 않는다 | +| 값이 비어 올 때 | 새 값이 NULL이면 그 칼럼은 **이전 값을 유지**(`COALESCE`)하고 `fetched_at`만 갱신한다 | +| 응답 범위 밖 지난 구간 | 새 응답에 없어서 덮이지 않고 마지막으로 받은 예보 값이 남는다 (실측값이 아님) | +| 보관 | 예보 시각이 **7일** 지난 행을 매일 03:00에 지운다 | + +- `fetched_at`은 "마지막 응답을 받은 시각"이다. 일부 칼럼이 계속 비어 오면 그 칼럼은 오래된 값이 남을 수 있다. +- 오늘 KST 아침 구간(03·06·09시)은 03:10 수집이 채운다. 워커가 그 시각에 꺼져 있으면 그날 일조 합이 빈다 (요청에 `past_days=1`을 넣으면 해결, 아직 안 함). + +### 호출량 + +- 한 번 11번 × 하루 4번 = **하루 44번**, 좌표로는 하루 1,024개. +- 구름과 합치면 구름이 전국 일괄일 때 하루 약 4,100좌표 (구름 1,024좌표 × 3시간대 + 보조값 1,024). + +## 3. 활동 지수에 쓰는 방식 + +활동 지수 27개 중 10개에 보조값을 적용했다 (`services/calc/index_calc.py`, `services/index_service.py`, `seed/index_definition.json`). + +### 새 축 3개 + +| 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 | +|---|---|---|---| +| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` | +| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` | +| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` | + +- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**. +- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다 (기존 6개 축은 항상 나옴). +- 0점 조건에 쓰는 필드 2개가 늘었다: `gust_ms`(돌풍 최대), `ground_c`(지표면 온도 최대). + +### 지수별 적용 + +| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 | +|---|---|---|---| +| 빨래각 | 햇빛 25 | 15·30·15·10·0 | | +| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 | +| 피크닉각 | 자외선 10 | 25·25·15·5·10 | | +| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | | +| 러닝각 | 자외선 5 | 35·20·10·15·10 | | +| 가드닝각 | 자외선 5 | 25·30·10·15·10 | | +| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | | +| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | | +| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 | +| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 | + +- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인). +- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다. + +### 3시간 구간을 계산 창에 연결하는 규칙 + +지수 계산 창(예: 7~10시)의 시각 h마다 아래 구간을 붙인다. + +| 값 | 쓰는 구간 | 이유 | +|---|---|---| +| 자외선·가시거리·돌풍·지표면 온도 (순간값) | h시~h+1시 한가운데에 **가장 가까운** 구간 끝 시각 (9시→9시, 10시→12시) | 순간값이라 가까운 구간이 맞다. 덮는 구간을 쓰면 아침 창(7~10시)에 정오 자외선이 들어간다 | +| 일조 (직전 3시간 합) | h시~h+1시를 **덮는** 구간 (7시→9시, 12시→15시) | 구간 값이 직전 3시간이다 | + +- 처음에는 모두 덮는 구간으로 연결했다가, 가드닝각(7~10시)이 정오 자외선 때문에 86 → 79로 크게 떨어지는 것을 비교에서 발견해 순간값을 가장 가까운 구간으로 바꿨다. +- 창과 구간이 어긋나는 곳(11~16시, 7~12시 등)은 근사다. + +### 재계산 + +`IndexService.ensure`가 점수를 다시 계산하는 기준에 `openmeteo_hourly.fetched_at`을 추가했다. 보조값이 새로 와야 지수가 새로 계산된다 (6시간마다). + +### 적용 전후 (성남시 분당구 4113500000, 2026-10-06 로컬) + +| 지수 | 10/6 | 10/7 | 10/8 | 비고 | +|---|---|---|---|---| +| 빨래각 | 84→86 | 81→84 | 81→84 | 해 난 비율 100% | +| 멍뭉산책각 | 93→94 | 93→93 | 91→92 | | +| 피크닉각 | 81→75 | 85→78 | 85→78 | 낮 자외선 5.0 → 자외선 점수 49 | +| 등산각 | 77→76 | 78→77 | 79→78 | | +| 러닝각 | 76→78 | 80→82 | 74→77 | | +| 가드닝각 | 86→84 | 83→83 | 86→86 | | +| 별보기각 | 72→75 | 78→81 | 77→80 | | +| 사진산책각 | 73→73 | 73→73 | 72→73 | | +| 자전거각, 캠핑각 | 변화 없음 | | | 돌풍 15m/s 미만 | + +- 자외선 5(보통 수준)에 49점은 가혹할 수 있다. 여름 한낮 자외선(8 이상)은 0점이 되어 피크닉각이 크게 내려간다. 필요하면 시드 JSON의 `uv` 규칙(`zero`, `full`)을 조정한다. +- 이 비교는 한 지역, 3일, 맑은 날 기준이다. + +### 아직 안 쓴 것 + +- 기압(`pressure_hpa`): 등산·캠핑의 "기압 하락" 규칙은 6시간 변화 계산이 필요해 이번에 넣지 않았다. +- 일사(`shortwave_*`): 쓰는 지수가 없다. +- 문서 `날씨 데이터 및 지수 산출.html`의 새 지수(드라이브·도파민·뽀송·감정기복·센치·안개감성)는 아직 만들지 않았다. +- 시간대 해상도가 3시간이라 1~2시간짜리 계산 창에서는 정확도가 떨어진다. + +## 4. 알려진 한계와 주의 + +- **429**: 짧은 시간에 좌표를 몰아서 보내면 Open-Meteo가 429를 준다. 로컬에서 좌표 256개 × 3번을 연달아 보냈더니 3번째에 났고, 75초 쉰 뒤 정상이었다. 현재 재시도는 1초·2초 간격 3번이라 분당 한도에 걸리면 그 회차는 11개 요청 중 하나만 실패해도 전체가 저장되지 않는다. 다음 수집(6시간 뒤)까지 옛 값이 남는다. +- **한도**: 문서(`날씨 데이터 및 지수 산출.html`)는 하루 1만 건, 시간당 5천 건, 분당 600건이라고 적는다. 좌표 수 기준인지 요청 수 기준인지 확정하지 못했다. 로컬 429는 좌표 수 기준을 시사한다. +- **상업 이용**: Open-Meteo 무료 API는 비상업용이다. 서비스에 붙이려면 유료 플랜(API 키)이 필요하다. +- **관측값이 아니다**: 전부 예보 모델 값이다. 가시거리·일조·기압은 기상청 관측과 대조하지 않았다. 기상청 ASOS·생활기상지수는 이 키로 호출이 막혔다 (403, 400). +- **보조값이 비어 있으면 해당 축은 70점(정보 없음)**으로 계산되어 지수가 평범하게 보일 수 있다. 수집 실패가 길어지면 알아채기 어렵다. +- 자외선 등 임계값은 한국 기준으로 검증되지 않은 초안이다. + +## 5. 코드 위치 + +| 파일 | 역할 | +|---|---| +| `services/external/open_meteo.py` | `fetch_clouds`·`parse_clouds`(구름), `fetch_weather`·`parse_weather`(보조값, 3시간 집계), `MODELS` | +| `services/sky_service.py` | 구름 갱신(`_refresh`), 구 코드 키 저장, 점수 계산 | +| `services/calc/sky_score.py` | 점수·등급·신뢰도·추천 시각 | +| `scheduler/jobs.py`, `worker_main.py` | 보조값 수집 job(`refresh_openmeteo_weather`)과 스케줄, 7일 정리 | +| `crud/sky_crud.py`, `crud/weather_crud.py` | `cloud_hourly` 저장, `openmeteo_hourly` 저장(`upsert_openmeteo`, NULL 유지) | +| `services/calc/index_calc.py` | 새 축 `uv_score`·`sun_score`·`view_score`, 0점 필드 `gust_ms`·`ground_c`, `evaluate` 반영 | +| `services/index_service.py` | 3시간 구간 연결(`windows_for`, `_nearest_slot_end_hour`, `_slot_end_hour`), 재계산 기준에 `fetched_at` 추가 | +| `router/v1/index/index.py` | 새 축 이름표, 비중 있는 새 축만 상세에 노출 | +| `seed/index_definition.json` | 10개 지수의 새 비중·규칙·0점 조건 | +| `common/database/model/models.py`, `postgres-init/init.sql` | `CloudHourly`, `OpenMeteoHourly`, 지수 새 축 칼럼 모델과 DDL | +| `tests/test_openmeteo_weather.py`, `tests/test_sky_api.py`, `tests/test_sky_score.py`, `tests/test_index_calc.py`, `tests/test_index_api.py` | 집계·저장·덮어쓰기·점수·새 축·구간 연결·재계산 테스트 | + +## 6. 이미 만들어진 DB에 적용할 SQL + +`init.sql`은 DB를 처음 만들 때만 실행된다. 이미 있는 DB에는 아래를 직접 적용한다 (운영 DB는 코드 배포와 순서를 맞춘다). + +```sql +BEGIN; + +-- cloud_hourly 구조 변경 (좌표 키 → 구 코드 키). 기존 행은 삭제된다 (외부 API 캐시). +DROP TABLE IF EXISTS public.cloud_hourly; +CREATE TABLE public.cloud_hourly ( + region_code VARCHAR(10) NOT NULL, + kind SMALLINT NOT NULL, -- 1=일몰 방향 2=일출 방향 + distance_km SMALLINT NOT NULL, -- 20 또는 100 + forecast_at TIMESTAMPTZ NOT NULL, + model SMALLINT NOT NULL, -- 3=JMA 4=ICON + cloud_low SMALLINT NOT NULL, + cloud_mid SMALLINT NOT NULL, + cloud_high SMALLINT NOT NULL, + PRIMARY KEY (region_code, kind, distance_km, forecast_at, model) +); +DELETE FROM public.sky_score; -- 옛 방식 점수를 비워 새 방식으로 다시 계산 + +-- openmeteo_hourly 신규 (추가만 함) +CREATE TABLE IF NOT EXISTS public.openmeteo_hourly ( + region_code VARCHAR(10) NOT NULL, + forecast_at TIMESTAMPTZ NOT NULL, + uv_index NUMERIC(4,2) NULL, + uv_index_clear_sky NUMERIC(4,2) NULL, + visibility_m INTEGER NULL, + wind_gust_ms NUMERIC(4,1) NULL, + pressure_hpa NUMERIC(5,1) NULL, + soil_temp_c NUMERIC(4,1) NULL, + sunshine_s SMALLINT NULL, + shortwave_avg_wm2 SMALLINT NULL, + shortwave_max_wm2 SMALLINT NULL, + fetched_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (region_code, forecast_at) +); + +COMMIT; +``` + +지수 테이블에 새 축 칼럼을 추가한다 (삭제 없음). 이어서 `seed/index_definition.json`을 `load_seed.py`로 다시 넣어야 새 비중이 반영된다. + +```sql +BEGIN; +ALTER TABLE public.index_definition + ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE public.index_score + ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0; +COMMIT; +``` + +옛 정의로 계산된 `index_score`는 새 비중과 다르다. 지수를 새로 계산하려면 해당 지역의 `index_score` 행을 지우거나 `openmeteo_hourly`가 새로 갱신될 때까지 기다린다. + +점수를 새 방식으로 다시 계산하려면 Redis의 `sky:*` 마커도 지운다 (`redis-cli --scan --pattern "sky:*" | xargs -r redis-cli del`). 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 3/3] =?UTF-8?q?feat:=20=EB=B0=A4=20=EA=B5=AC=EA=B0=84(21~0?= =?UTF-8?q?6=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