feat: Open-Meteo 구름 20·100km 구 코드 저장, 보조값 수집, 활동 지수 10개에 자외선·햇빛·가시거리 반영
구름 - 노을·일출 점수를 구 중심 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는 테스트용 환경변수).
This commit is contained in:
1 parent
7244449b7a
commit
7c12651068
19 files changed
+712
-82
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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}]. 화면 문장은 여기서 만든다
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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())
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
+59
-3
@@ -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
|
||||
@@ -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({
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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([{
|
||||
|
||||
@@ -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%"
|
||||
@@ -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° 이상이면"
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
@@ -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():
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user