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

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

No files matched your search

+26 -2
View File
@@ -101,8 +101,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)
@@ -110,6 +111,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"
@@ -156,6 +174,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)
@@ -177,6 +198,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)
+5 -5
View File
@@ -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:
+23 -1
View File
@@ -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))
+1
View File
@@ -3,6 +3,7 @@
| 문서 | 내용 | 아티팩트 |
|---|---|---|
| `../../docs/데이터_흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
| `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 |
+272
View File
@@ -0,0 +1,272 @@
# 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의 순간값이다.
- **밤 구간(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 하루의 일조 합**은 끝 시각 09·12·15·18·21시 구간 5개를 더한다 (밤 구간은 NULL).
- 일사 평균은 맑은 날에도 피크를 깎는다 (시간별 최대 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이면 나오지 않는다.
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
- 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`).
+32 -6
View File
@@ -39,16 +39,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번 갱신).
@@ -116,6 +136,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° 안", ...}
@@ -237,11 +260,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}]. 화면 문장은 여기서 만든다
+32
View File
@@ -11,12 +11,15 @@ 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.week_crud import WeekCRUD
from crud.weather_crud import WeatherCRUD
from services.external.airkorea import fetch_stations, parse_stations
from services.external import popga, teams_webhook
from services.external.culture_api import SIDO_NAME
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
from services.week_service import collect_events
from services.weekend_rank import WeekendRank
@@ -36,7 +39,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:
@@ -65,6 +70,33 @@ async def refresh_weekend_rank(only_if_missing: bool = False) -> ErrorType:
return err
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())
+150 -18
View File
@@ -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": {
@@ -84,11 +87,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": {
@@ -116,6 +122,10 @@
"sun": 100,
"holiday": 100,
"default": 60
},
"uv": {
"zero": 8,
"full": 2
}
},
"zero_rules": [
@@ -154,6 +164,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": {
@@ -223,6 +236,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": {
@@ -302,6 +318,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": {
@@ -357,11 +376,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": {
@@ -390,6 +412,14 @@
"sun": 100,
"holiday": 100,
"default": 50
},
"uv": {
"zero": 8,
"full": 2
},
"view": {
"zero": 5,
"full": 20
}
},
"zero_rules": [
@@ -434,6 +464,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": {
@@ -494,6 +527,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": {
@@ -529,6 +565,11 @@
"field": "wind_ms",
"op": ">=",
"value": 14
},
{
"field": "gust_ms",
"op": ">=",
"value": 15
}
],
"limit_description": "캠핑장 예약 상황은 반영하지 못해요",
@@ -562,8 +603,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": {
@@ -585,6 +629,10 @@
"time": {
"type": "fixed",
"value": 100
},
"uv": {
"zero": 8,
"full": 2
}
},
"zero_rules": [
@@ -624,10 +672,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": {
@@ -648,6 +699,10 @@
},
"time": {
"type": "moon"
},
"view": {
"zero": 5,
"full": 20
}
},
"zero_rules": [
@@ -690,6 +745,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": {
@@ -741,6 +799,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": {
@@ -794,6 +855,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": {
@@ -840,11 +904,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": {
@@ -864,6 +931,10 @@
"time": {
"type": "fixed",
"value": 100
},
"sun": {
"zero": 0.2,
"full": 0.8
}
},
"zero_rules": [
@@ -873,7 +944,7 @@
"value": 60
}
],
"limit_description": "집 일조량은 반영하지 못해요",
"limit_description": "집 방향·그늘 일조량은 반영하지 못해요",
"sentences": {
"0": "비 소식이 있어요. 오늘 빨래는 실내 건조로!",
"30": "눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.",
@@ -902,6 +973,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": {
@@ -941,6 +1015,11 @@
"field": "wind_ms",
"op": ">=",
"value": 10
},
{
"field": "gust_ms",
"op": ">=",
"value": 15
}
],
"limit_description": "자전거 도로 공사는 반영하지 못해요",
@@ -971,11 +1050,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": {
@@ -1000,6 +1082,10 @@
"time": {
"type": "fixed",
"value": 100
},
"uv": {
"zero": 8,
"full": 2
}
},
"zero_rules": [
@@ -1012,9 +1098,14 @@
"field": "pm25",
"op": ">=",
"value": 75
},
{
"field": "ground_c",
"op": ">=",
"value": 45
}
],
"limit_description": "노면 온도는 실측하지 못해요",
"limit_description": "지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요",
"sentences": {
"0": "체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!",
"30": "덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.",
@@ -1043,6 +1134,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": {
@@ -1094,6 +1188,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": {
@@ -1145,6 +1242,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": {
@@ -1198,6 +1298,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": {
@@ -1251,6 +1354,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": {
@@ -1300,11 +1406,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": {
@@ -1329,6 +1438,10 @@
"time": {
"type": "fixed",
"value": 100
},
"uv": {
"zero": 8,
"full": 2
}
},
"zero_rules": [
@@ -1362,11 +1475,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": {
@@ -1390,6 +1506,10 @@
},
"time": {
"type": "sunset_score"
},
"view": {
"zero": 5,
"full": 20
}
},
"zero_rules": [
@@ -1428,6 +1548,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": {
@@ -1491,6 +1614,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": {
@@ -1545,6 +1671,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": {
@@ -1598,6 +1727,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": {
+47 -6
View File
@@ -8,7 +8,7 @@ from typing import Optional
from common.enums import RainType, Sky
from common.utils.text import hour_label
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
_UNKNOWN = 70
@@ -25,6 +25,12 @@ class Hour:
wind_ms: Optional[float]
humidity: int
sky: Sky
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
uv: Optional[float] = None
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
visibility_km: Optional[float] = None
gust_ms: Optional[float] = None
ground_c: Optional[float] = None
@dataclass(frozen=True)
@@ -134,6 +140,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
if uv is None:
return _UNKNOWN, "자외선 정보 없음"
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
if ratio is None:
return _UNKNOWN, "햇빛 정보 없음"
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
if km is None:
return _UNKNOWN, "가시거리 정보 없음"
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
kind = rule["type"]
if kind == "weekday":
@@ -153,10 +177,14 @@ _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower":
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
def axis_label(axis: str, rules: dict) -> str:
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
if axis in _OM_LABEL:
return _OM_LABEL[axis]
if axis == "rain":
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
if axis == "air":
@@ -180,8 +208,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
return None, None
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%"}
_FIELD_TEXT = {
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
"gust_ms": "돌풍", "ground_c": "지표면 온도",
}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
def _cond(r: dict) -> tuple[str, str, str]:
@@ -232,7 +263,7 @@ def _until(definition) -> str:
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
best: Optional[Result] = None
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
rules = definition.factor_rules
until = _until(definition)
for hours in windows:
@@ -243,12 +274,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
raining = any(h.rain_type is not RainType.NONE for h in hours)
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
feels = mean(h.feels_c for h in hours)
uvs = [h.uv for h in hours if h.uv is not None]
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
views = [h.visibility_km for h in hours if h.visibility_km is not None]
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
grounds = [h.ground_c for h in hours if h.ground_c is not None]
scored = {
"temp": temp_score(rules["temp"], feels),
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
"wind": wind_score(rules["wind"], max(winds) if winds else None),
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
"air": air_score(ctx.pm25, ctx.air_label),
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
"time": time_score(rules["time"], ctx),
}
factors = {a: v for a, (v, _) in scored.items()}
@@ -259,6 +298,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
"warning": "wind" if ctx.wind_warning else None,
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
@@ -277,11 +317,11 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
if fc.temp_min_c is None or fc.temp_max_c is None:
return None
best: Optional[Result] = None
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
rules = definition.factor_rules
until = _until(definition)
after = next_fc or fc
@@ -301,6 +341,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
"wind": wind_score(rules["wind"], None),
"humidity": humidity,
"air": air_score(None, None),
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
"time": time_score(rules["time"], ctx),
}
factors = {a: v for a, (v, _) in scored.items()}
+11 -11
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
DISTANCES_KM = (20, 50, 100)
DISTANCES_KM = (20, 100)
@dataclass(frozen=True)
@@ -14,11 +14,11 @@ class Layers:
high: float
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
def score(near20: Layers, far100: Layers) -> int:
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = max(near20.mid, near20.high)
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
f_near = 1 - 0.8 * near20.low / 100
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
@@ -73,13 +73,13 @@ def mean_layers(rows: list[Layers]) -> Layers:
return Layers(*(statistics.mean(getattr(r, k) for r in rows) for k in ("low", "mid", "high")))
def situation(near20: Layers, near50: Layers, far100: Layers) -> SkySituation:
def situation(near20: Layers, far100: Layers) -> SkySituation:
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
return SkySituation.COVERED
if (near20.low + near50.low) / 2 >= 60:
if near20.low >= 60:
return SkySituation.LOW_CLOUD
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
canvas = max(near20.mid, near20.high)
if canvas < 25:
return SkySituation.FEW
if canvas > 75:
@@ -100,13 +100,13 @@ SITUATION_VERDICT = {
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
def reason(near20: Layers, near50: Layers, far100: Layers) -> str:
def reason(near20: Layers, far100: Layers) -> str:
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
if (near20.low + near50.low) / 2 >= 60:
if near20.low >= 60:
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
canvas = round((max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2)
canvas = round(max(near20.mid, near20.high))
if canvas < 10:
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
if canvas > 85:
+75 -4
View File
@@ -1,5 +1,5 @@
import asyncio
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
import httpx
@@ -7,7 +7,7 @@ from common.enums import CloudModel
from services.external.guard import Unreachable, guarded
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
@@ -17,10 +17,23 @@ class OpenMeteoRequestFailed(RuntimeError):
_CHUNK = 24
WEATHER_VARS = (
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
)
SLOT_HOURS = 3
# 해가 없는 밤 구간(21~06시 = 끝 시각 KST 0·3·6시)은 햇빛 값(일조·일사·자외선)을 저장하지 않는다.
DARK_SLOT_END_KST = (0, 3, 6)
_SUN_FIELDS = ("uv_index", "uv_index_clear_sky", "sunshine_s", "shortwave_avg_wm2", "shortwave_max_wm2")
_KST_OFFSET = timedelta(hours=9)
def is_dark_slot(end: datetime) -> bool:
return (end.astimezone(timezone.utc) + _KST_OFFSET).hour in DARK_SLOT_END_KST
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
"""좌표마다 시간별 층별 구름을 모델별로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
async def all_chunks() -> list[dict]:
@@ -37,6 +50,10 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
for attempt in range(_ATTEMPTS):
try:
res = await client.get(URL, params=params)
@@ -47,7 +64,27 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(1.0 * (attempt + 1))
raise Unreachable(f"forecast {len(points)} points: {last}")
raise Unreachable(f"forecast {point_count} points: {last}")
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
async def all_chunks() -> list[dict]:
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
return await guarded("openmeteo:weather", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
@@ -62,3 +99,37 @@ def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
continue
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
return rows
def _round(v, digits: int = 0):
return None if v is None else (round(v, digits) if digits else int(round(v)))
def parse_weather(data: dict) -> list[dict]:
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀). 밤 구간은 햇빛 값을 비운다."""
h = data["hourly"]
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
index = {t: i for i, t in enumerate(times)}
rows = []
for end, i in index.items():
if end.hour % SLOT_HOURS:
continue
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
if None in span:
continue
sun = [h["sunshine_duration"][j] for j in span]
rad = [h["shortwave_radiation"][j] for j in span]
row = {
"forecast_at": end,
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
"sunshine_s": None if None in sun else int(round(sum(sun))),
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
}
if is_dark_slot(end):
row |= dict.fromkeys(_SUN_FIELDS)
rows.append(row)
return rows
+51 -8
View File
@@ -7,7 +7,7 @@ from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import IndexDefinition, IndexScore, Region, WeatherDaily, WeatherHourly
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.index_crud import IndexCRUD
@@ -19,6 +19,7 @@ from services.air_service import GRADE_LABEL, AirService
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
from services.calc.moon import illumination
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
from services.warning_service import WarningService
from services.weather_service import WeatherService
@@ -89,13 +90,48 @@ def window_hours(defn, day: date, region: Region) -> list[list[int]]:
return out
def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly]) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다."""
def _slot_end_hour(h: int) -> int:
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
return (h + 3) // 3 * 3
def _nearest_slot_end_hour(h: int) -> int:
"""h시~h+1시의 한가운데에 가장 가까운 3시간 구간 끝 시각. 자외선·가시거리·돌풍·지표면 온도처럼 '끝 시각 순간값'에 쓴다 (9시→9시, 10시→12시)."""
return int((h + 0.5) / 3 + 0.5) * 3
def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict:
"""3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음'). 밤 구간은 햇빛 값을 받지 않으므로 0으로 본다."""
fields = {}
if instant is not None:
fields |= {
"uv": 0.0 if is_dark_slot(instant.forecast_at) else float(instant.uv_index) if instant.uv_index is not None else None,
"visibility_km": instant.visibility_m / 1000 if instant.visibility_m is not None else None,
"gust_ms": float(instant.wind_gust_ms) if instant.wind_gust_ms is not None else None,
"ground_c": float(instant.soil_temp_c) if instant.soil_temp_c is not None else None,
}
if covering is not None and is_dark_slot(covering.forecast_at):
fields["sunshine_ratio"] = 0.0
elif covering is not None and covering.sunshine_s is not None:
fields["sunshine_ratio"] = min(covering.sunshine_s / 10800, 1.0)
return fields
def windows_for(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
by_om = by_om or {}
start = kst_midnight(day)
out = []
for hours in window_hours(defn, day, region):
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
out.append([replace(_hour(r), hour=h) for h, r in zip(hours, rows) if r is not None])
out.append([
replace(_hour(r), hour=h, **_om_fields(
by_om.get(start + timedelta(hours=_nearest_slot_end_hour(h))), by_om.get(start + timedelta(hours=_slot_end_hour(h)))
))
for h, r in zip(hours, rows) if r is not None
])
return out
@@ -114,10 +150,11 @@ def _lookahead_days(defn) -> int:
def day_result(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool,
by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
) -> Optional[Result]:
"""short(오늘~모레)이거나 시간대가 시간별 예보로 다 채워지면 그대로 계산, 아니면 중기예보로 예상 점수."""
windows = windows_for(defn, day, region, by_at)
windows = windows_for(defn, day, region, by_at, by_om)
if short or all(len(w) == len(h) for w, h in zip(windows, window_hours(defn, day, region))):
return evaluate(defn, windows, replace(ctx, lookahead_rain_prob=lookahead_rain(defn, day, by_at)))
fc = daily.get(day)
@@ -201,6 +238,10 @@ class IndexService:
return ErrorType.EXTERNAL_API_ERROR, None
_, daily_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, today, days[-1] + timedelta(days=2)))
daily = {d.forecast_date: day_forecast(d) for d in daily_rows or []}
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
)
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
air = await self.air_service.nearest(region)
by_at = {r.forecast_at: r for r in rows}
base_ctx = dict(
@@ -209,10 +250,12 @@ class IndexService:
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at), today_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
inputs_at = max(issued, air.measured_at) if air else issued
if by_om:
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
@@ -232,7 +275,7 @@ class IndexService:
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
)
for d in defs:
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS))
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
if result is None:
continue
out.append({
+32 -26
View File
@@ -150,27 +150,25 @@ def _nearest_hour(at: datetime) -> datetime:
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
first = sun_times(today, float(region.lat), float(region.lon))
rows = []
for kind, azimuth in ((SkyType.SUNSET, first.sunset_azimuth), (SkyType.SUNRISE, first.sunrise_azimuth)):
pts = _points(region, azimuth)
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
for i in range(DAYS):
d = today + timedelta(days=i)
st: SunTimes = sun_times(d, float(region.lat), float(region.lon))
sun_at, twilight_at = (st.sunset_at, st.dusk_end_at) if kind is SkyType.SUNSET else (st.sunrise_at, st.dawn_start_at)
hour = _nearest_hour(sun_at)
per_model, highs, model_layers = [], [], []
for model in {k[2] for k in clouds}:
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
for model in {k[4] for k in clouds}:
layers = [clouds.get((region.code, kind.value, km, hour, model)) for km in DISTANCES_KM]
if None in layers:
continue
per_model.append(score(*layers))
highs.append((layers[0].high + layers[1].high) / 2)
highs.append(layers[0].high)
model_layers.append(layers)
if not per_model:
continue
value = round(statistics.mean(per_model))
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(3)))
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
rows.append({
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
"confidence": confidence(per_model).value,
@@ -222,7 +220,7 @@ class SkyService:
LOG.error(f"[sky] spots {region.code}: {err.name}")
near = nearest_spots(lat, lon, spots or [])
first = sun_times(now.date(), lat, lon)
plan = await self._plan(region, first.sunset_azimuth, sunsets, near, now)
plan = await self._plan(region, sunsets, near, now)
return ErrorType.SUCCESS, SkyView(
region=region,
sunset_azimuth=first.sunset_azimuth,
@@ -233,7 +231,7 @@ class SkyService:
plan=plan,
)
async def _plan(self, region: Region, azimuth: int, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
lat, lon = float(region.lat), float(region.lon)
target, st = None, None
@@ -244,15 +242,15 @@ class SkyService:
break
if target is None or st is None:
return None
pts = _points(region, azimuth)
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, pts, _nearest_hour(st.sunset_at)))
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
if err is not ErrorType.SUCCESS:
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
by_point: dict[tuple[float, float], list[Layers]] = {}
by_km: dict[int, list[Layers]] = {}
for r in rows or []:
by_point.setdefault((float(r.lat), float(r.lon)), []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
layers = [mean_layers(by_point[p]) for p in pts if p in by_point]
return build_plan(target, st, layers if len(layers) == len(pts) else None, spots, sunsets, now.date())
if r.kind == SkyType.SUNSET.value:
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
@@ -300,24 +298,32 @@ class SkyService:
plan = {}
for r in regions:
st = sun_times(today, float(r.lat), float(r.lon))
plan[r.code] = _points(r, st.sunset_azimuth) + _points(r, st.sunrise_azimuth)
points = sorted({p for pts in plan.values() for p in pts})
plan[r.code] = {SkyType.SUNSET: _points(r, st.sunset_azimuth), SkyType.SUNRISE: _points(r, st.sunrise_azimuth)}
points = sorted({p for kinds in plan.values() for pts in kinds.values() for p in pts})
try:
async with httpx.AsyncClient(timeout=30) as client:
data = await fetch_clouds(client, points, days=DAYS)
except OpenMeteoRequestFailed as e:
LOG.error(f"[sky] {len(regions)} regions: {e}")
return
needed_hours = {
_nearest_hour(at)
for r in regions
for i in range(DAYS)
for st in [sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))]
for at in (st.sunset_at, st.sunrise_at)
}
cloud_rows = [row for p, d in zip(points, data) for row in parse_clouds(p, d) if row["forecast_at"] in needed_hours]
by_point: dict[tuple[float, float], dict[datetime, list[dict]]] = {}
for p, d in zip(points, data):
for row in parse_clouds(p, d):
by_point.setdefault(p, {}).setdefault(row["forecast_at"], []).append(row)
cloud_rows = []
for r in regions:
for kind, pts in plan[r.code].items():
for i in range(DAYS):
st = sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))
hour = _nearest_hour(st.sunset_at if kind is SkyType.SUNSET else st.sunrise_at)
for km, p in zip(DISTANCES_KM, pts):
cloud_rows += [
{"region_code": r.code, "kind": kind.value, "distance_km": km, "forecast_at": hour, "model": row["model"],
"cloud_low": row["cloud_low"], "cloud_mid": row["cloud_mid"], "cloud_high": row["cloud_high"]}
for row in by_point.get(p, {}).get(hour, [])
]
clouds = {
(float(r["lat"]), float(r["lon"]), r["model"], r["forecast_at"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
(r["region_code"], r["kind"], r["distance_km"], r["forecast_at"], r["model"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
for r in cloud_rows
}
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now)]
+15 -2
View File
@@ -42,7 +42,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",
)
@@ -68,8 +68,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
@@ -96,6 +97,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")])))
@@ -106,6 +118,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(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
+95 -1
View File
@@ -1,4 +1,5 @@
from datetime import date, timedelta
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
@@ -6,9 +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 slot_days, slot_label
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
REGION = "1141000000"
@@ -96,3 +100,93 @@ def test_every_index_has_four_band_sentences():
import os
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
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)
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:
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%"
+50 -4
View File
@@ -4,8 +4,8 @@ from types import SimpleNamespace
from common.enums import RainType, Sky
from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, temp_score,
zero_rules_text,
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
uv_score, view_score, zero_rules_text,
)
from services.calc.moon import illumination
@@ -24,8 +24,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():
@@ -111,6 +111,52 @@ def test_moon_full_and_new():
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점"
def test_estimate_and_labels_cover_openmeteo_axes():
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
+113
View File
@@ -0,0 +1,113 @@
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
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
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"]
+20 -1
View File
@@ -55,7 +55,7 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
assert "알맞게" in plan["reason"]
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 4
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
assert plan["outlook"] == ""
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
@@ -122,3 +122,22 @@ def test_outlook_only_when_a_later_day_has_a_better_verdict():
few, glow = SkySituation.FEW, SkySituation.GLOW
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
@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
+13 -13
View File
@@ -10,21 +10,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():
@@ -48,10 +48,10 @@ def test_sunset_best_times_order():
def test_reason_names_what_decided_the_score():
canvas = Layers(low=0, mid=20, high=50)
assert "알맞게" in reason(canvas, canvas, CLEAR)
assert "먼 하늘" in reason(canvas, canvas, Layers(low=90, mid=50, high=0))
assert "낮은 구름" in reason(Layers(100, 0, 0), Layers(80, 0, 0), CLEAR)
assert "거의 없어" in reason(CLEAR, CLEAR, CLEAR)
assert "알맞게" in reason(canvas, CLEAR)
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
assert "거의 없어" in reason(CLEAR, CLEAR)
def test_verdict_bands_and_gray_label_is_not_weather_word():
@@ -70,11 +70,11 @@ def test_sunset_timeline_runs_golden_to_blue():
def test_situation_follows_reason_order():
from common.enums import SkySituation
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
assert situation(clear, clear, clear) is SkySituation.FEW
assert situation(glow, glow, clear) is SkySituation.GLOW
assert situation(Layers(0, 90, 95), Layers(0, 90, 95), clear) is SkySituation.THICK
assert situation(Layers(80, 0, 0), Layers(70, 0, 0), clear) is SkySituation.LOW_CLOUD
assert situation(glow, glow, Layers(70, 0, 0)) is SkySituation.COVERED
assert situation(clear, clear) is SkySituation.FEW
assert situation(glow, clear) is SkySituation.GLOW
assert situation(Layers(0, 90, 95), clear) is SkySituation.THICK
assert situation(Layers(80, 0, 0), clear) is SkySituation.LOW_CLOUD
assert situation(glow, Layers(70, 0, 0)) is SkySituation.COVERED
def test_ranking_summary_only_when_most_spots_share_a_situation():
+3 -2
View File
@@ -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, refresh_events, refresh_weekend_rank
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_weekend_rank
async def daily() -> None:
@@ -23,8 +23,9 @@ async def main() -> None:
# 행사(축제·전시·콘서트·팝업): 7일에 한 번, 끝나면 Teams 알림. 켤 때 7일 안에 받은 기록이 없으면 한 번.
scheduler.add_job(refresh_events, "cron", day_of_week="mon", hour=4, minute=0, max_instances=1, coalesce=True)
scheduler.add_job(refresh_events, kwargs={"only_if_missing": True}, max_instances=1)
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, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST")
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST")
stop = asyncio.Event()
loop = asyncio.get_running_loop()
+2 -1
View File
@@ -146,7 +146,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
<div style="--c:var(--kma)"><dt>중기예보</dt><dd>4~10일 뒤 오전·오후 날씨(맑음·구름·흐림·비)와 최저·최고기온</dd></div>
<div style="--c:var(--kma)"><dt>기상특보</dt><dd>최근 7일 구역별 특보 종류(강풍·호우 등)와 단계</dd></div>
<div style="--c:var(--air)"><dt>미세먼지</dt><dd>전국 측정소별 PM10·PM2.5 농도와 등급</dd></div>
<div style="--c:var(--om)"><dt>층별 구름</dt><dd>3일치 낮은·중간·높은 구름 양(%), 예보 모델 4개(ECMWF·GFS·JMA·ICON)</dd></div>
<div style="--c:var(--om)"><dt>층별 구름</dt><dd>3일치 낮은·중간·높은 구름 양(%), 해 지는·뜨는 쪽 20·100km 지점, 예보 모델 2개(일본 JMA·독일 ICON)</dd></div>
<div style="--c:var(--tour)"><dt>축제·행사</dt><dd>행사 이름·장소·시작일·종료일</dd></div>
<div style="--c:var(--kasi)"><dt>공휴일·절기</dt><dd>그해 공휴일과 24절기의 날짜·이름</dd></div>
</dl>
@@ -174,6 +174,7 @@ code{font-family:var(--mono);font-size:12.5px;background:var(--soft-db);padding:
<tr><td>미세먼지</td><td><span class="chip" style="--c:var(--air)">에어코리아 실시간</span></td><td>전국</td><td>매시 <span class="mono">:20</span></td><td><code>air_quality</code></td><td><code>air:tried</code> 10분</td></tr>
<tr><td>측정소 위치</td><td><span class="chip" style="--c:var(--air)">에어코리아 측정소</span></td><td>전국</td><td>처음 + 매일 03:00</td><td><code>air_station</code></td><td>—</td></tr>
<tr><td>층별 구름 (노을·일출)</td><td><span class="chip" style="--c:var(--om)">Open-Meteo</span></td><td>좌표 24개씩</td><td>오전 · 13시 · 21시 시간대마다 1번</td><td><code>cloud_hourly</code></td><td><code>sky:</code> 표시 24시간</td></tr>
<tr><td>자외선·가시거리·일조 등</td><td><span class="chip" style="--c:var(--om)">Open-Meteo</span></td><td>전국 256곳</td><td>6시간마다 03·09·15·21시 10분 (worker)</td><td><code>openmeteo_hourly</code></td><td>—</td></tr>
<tr><td>축제·행사</td><td><span class="chip" style="--c:var(--tour)">TourAPI</span></td><td>시도 1곳</td><td>그 시도 하루 1번</td><td><code>event</code></td><td><code>event:</code> 표시 24시간</td></tr>
<tr><td>공휴일 · 24절기</td><td><span class="chip" style="--c:var(--kasi)">천문연</span></td><td>1년치</td><td>그해 값이 없을 때</td><td><code>holiday</code> <code>solar_term</code></td><td>표시 30일</td></tr>
<tr><td>해 뜨고 지는 시각</td><td><span class="chip" style="--c:var(--kasi)">서버 계산</span></td><td>구 1곳</td><td>그날 값이 없을 때</td><td><code>sun_time</code></td><td>—</td></tr>