Merge branch 'feat/open-meteo'

This commit is contained in:
skkim committed 2026-10-07 16:55:26 +09:00
commit 0ad19e0f42
6 files changed
+144 -13

No files matched your search

+15 -1
View File
@@ -4,7 +4,7 @@ from sqlalchemy import delete, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import CloudHourly, Region, SkyScore, SunsetSpot
from common.database.model.models import CloudHourly, OpenMeteoHourly, Region, SkyScore, SunsetSpot, WeatherHourly
_CHUNK = 2000
@@ -44,5 +44,19 @@ class SkyCRUD:
if rows:
await s.execute(insert(SunsetSpot).values(rows))
async def hourly_for(self, s: AsyncSession, region_codes: list[str], start: datetime, end: datetime) -> list[WeatherHourly]:
"""노을 공기 보정용 습도·비 확률 (단기예보 시간별)."""
stmt = select(WeatherHourly).where(
WeatherHourly.region_code.in_(region_codes), WeatherHourly.forecast_at >= start, WeatherHourly.forecast_at < end
)
return list((await s.scalars(stmt)).all())
async def openmeteo_for(self, s: AsyncSession, region_codes: list[str], start: datetime, end: datetime) -> list[OpenMeteoHourly]:
"""노을 공기 보정용 가시거리 (Open-Meteo 3시간 구간)."""
stmt = select(OpenMeteoHourly).where(
OpenMeteoHourly.region_code.in_(region_codes), OpenMeteoHourly.forecast_at >= start, OpenMeteoHourly.forecast_at < end
)
return list((await s.scalars(stmt)).all())
async def ranking_regions(self, s: AsyncSession) -> list[Region]:
return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all())
+9 -3
View File
@@ -40,13 +40,19 @@ Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장
```
canvas = max(mid20, high20)
f_canvas = 0.3 (canvas < 10) / max(0, 1 - |canvas-50|/50)
f_canvas = 0.2 + 0.8 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 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))
구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)
점수 = min(100, round(모델 평균 구름 점수 × 공기 보정))
```
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음.
- 맑은 하늘(구름 0%)은 40점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0):
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 40km 이상 ×1.0 ~ 5km 이하 ×0.6. 뿌연 공기는 색을 흐린다.
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 50% 이하 ×1.0 ~ 90% 이상 ×0.75.
- 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15.
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다.
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
### 이렇게 정한 이유 (검증 기록)
+32 -1
View File
@@ -5,6 +5,10 @@ from datetime import datetime, timedelta
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
DISTANCES_KM = (20, 100)
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함).
_CLEAR_CANVAS = 0.2
# 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다.
RAIN_BEFORE_HOURS = (2, 6)
@dataclass(frozen=True)
@@ -14,15 +18,42 @@ class Layers:
high: float
@dataclass(frozen=True)
class Air:
"""구 중심의 해 질(뜰) 무렵 공기. 값이 없으면 보정하지 않는다."""
visibility_km: float | None = None
humidity: float | None = None
rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률
rain_now: int | None = None
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_canvas = _CLEAR_CANVAS + (1 - _CLEAR_CANVAS) * canvas / 50 if canvas <= 50 else max(0.0, 1 - (canvas - 50) / 50)
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))
def _ramp(v: float, bad: float, good: float, low: float) -> float:
"""good 쪽은 1.0, bad 쪽은 low, 사이는 직선."""
t = max(0.0, min(1.0, (v - bad) / (good - bad)))
return low + (1 - low) * t
def air_factor(air: Air) -> float:
"""공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다."""
f = 1.0
if air.visibility_km is not None:
f *= _ramp(air.visibility_km, 5, 40, 0.6)
if air.humidity is not None:
f *= _ramp(air.humidity, 90, 50, 0.75)
if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40:
f *= 1.15
return f
def grade(value: int) -> SkyGrade:
if value >= 80:
return SkyGrade.RED
+43 -7
View File
@@ -12,16 +12,16 @@ from redis.exceptions import RedisError
from common.cache.lock import redis_lock
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Region, SkyScore, SunsetSpot
from common.database.model.models import OpenMeteoHourly, Region, SkyScore, SunsetSpot, WeatherHourly
from common.enums import ErrorType, SkyGrade, SkySituation, SkyType
from common.logger import LOG
from common.utils.geo import bearing_deg, destination, haversine_km
from common.utils.kma_time import KST, now_kst
from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
from services.calc.sky_score import (
DISTANCES_KM, GRADE_LABEL, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Layers, best_times, confidence, grade, mean_layers,
reason, score, situation, sunset_timeline, verdict,
DISTANCES_KM, GRADE_LABEL, RAIN_BEFORE_HOURS, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Air, Layers, air_factor, best_times,
confidence, grade, mean_layers, reason, score, situation, sunset_timeline, verdict,
)
from services.calc.sun import SunTimes, sun_times
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
@@ -149,7 +149,33 @@ def _nearest_hour(at: datetime) -> datetime:
return (at + timedelta(minutes=30)).replace(minute=0, second=0, microsecond=0)
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
def _nearest_slot(at: datetime) -> datetime:
"""Open-Meteo 3시간 구간 끝 시각(GMT 0·3·6…) 중 at 에 가장 가까운 것."""
at = at.astimezone(timezone.utc)
midnight = at.replace(hour=0, minute=0, second=0, microsecond=0)
return midnight + timedelta(hours=3 * int((at - midnight).total_seconds() / 10800 + 0.5))
def _air(
code: str, sun_at: datetime, hourly: dict[tuple[str, datetime], WeatherHourly], om: dict[tuple[str, datetime], OpenMeteoHourly]
) -> Air:
"""해 질(뜰) 무렵 구 중심의 가시거리·습도와 그 전 몇 시간의 비 확률."""
hour = _nearest_hour(sun_at)
w, o = hourly.get((code, hour)), om.get((code, _nearest_slot(sun_at)))
before = [r.rain_prob for k in range(RAIN_BEFORE_HOURS[0], RAIN_BEFORE_HOURS[1] + 1) if (r := hourly.get((code, hour - timedelta(hours=k))))]
return Air(
visibility_km=o.visibility_m / 1000 if o is not None and o.visibility_m is not None else None,
humidity=w.humidity if w is not None else None,
rain_before=max(before, default=None),
rain_now=w.rain_prob if w is not None else None,
)
def _score_rows(
region: Region, today: date, clouds: dict, now: datetime,
hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None,
) -> list[dict]:
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로."""
rows = []
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
for i in range(DAYS):
@@ -167,7 +193,7 @@ def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> lis
model_layers.append(layers)
if not per_model:
continue
value = round(statistics.mean(per_model))
value = min(100, round(statistics.mean(per_model) * air_factor(_air(region.code, sun_at, hourly or {}, om or {}))))
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,
@@ -326,7 +352,17 @@ class SkyService:
(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)]
codes, start = [r.code for r in regions], kst_midnight(today)
end = start + timedelta(days=DAYS + 1)
err, hourly_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.hourly_for(s, codes, start, end))
if err is not ErrorType.SUCCESS:
LOG.error(f"[sky] air hourly: {err.name}")
err, om_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.openmeteo_for(s, codes, start, end))
if err is not ErrorType.SUCCESS:
LOG.error(f"[sky] air openmeteo: {err.name}")
hourly = {(w.region_code, w.forecast_at): w for w in hourly_rows or []}
om = {(o.region_code, o.forecast_at): o for o in om_rows or []}
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om)]
err = await DB_SESSION_MNG.execute_lambda_run([
lambda s: self.crud.upsert_clouds(s, cloud_rows),
lambda s: self.crud.upsert_scores(s, score_rows),
+28
View File
@@ -141,3 +141,31 @@ async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, c
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
def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air():
from datetime import date, datetime, timedelta, timezone
from types import SimpleNamespace
from common.enums import SkyType
from services.calc.sky_score import Layers
from services.calc.sun import sun_times
region = SimpleNamespace(code="R", lat=37.56, lon=126.91)
today = date(2026, 10, 7)
hour = sky_service._nearest_hour(sun_times(today, region.lat, region.lon).sunset_at)
clouds = {("R", SkyType.SUNSET.value, km, hour, 3): Layers(0, 20, 0) for km in (20, 100)}
now = datetime(2026, 10, 7, 3, tzinfo=timezone.utc)
plain = sky_service._score_rows(region, today, clouds, now)[0]["score"]
hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)}
om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)}
hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"]
assert hazy == round(plain * 0.6 * 0.75)
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)}
assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15))
def test_nearest_slot_is_closest_three_hour_end():
from datetime import datetime, timezone
at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731
assert [sky_service._nearest_slot(at(h, m)).hour for h, m in ((8, 0), (9, 0), (10, 29), (10, 31))] == [9, 9, 9, 12]
+17 -1
View File
@@ -2,7 +2,9 @@ from datetime import date, datetime, timedelta, timezone
from common.enums import Confidence, SkyGrade, SkyType
from common.utils.geo import destination, haversine_km
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict
from services.calc.sky_score import (
GRADE_LABEL, Air, Layers, air_factor, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict,
)
from services.calc.sun import sun_times
CLEAR = Layers(0, 0, 0)
@@ -17,6 +19,20 @@ def test_clear_sky_is_only_soft():
assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT
def test_score_rises_steadily_with_a_few_clouds():
scores = [score(Layers(0, c, 0), CLEAR) for c in (0, 5, 9, 10, 15, 20, 30, 50)]
assert scores == sorted(scores) and len(set(scores)) == len(scores) # 맑은 날도 구름 몇 %로 갈리고 10%에서 꺾이지 않는다
def test_air_factor_hazy_humid_lowers_and_clearing_rain_raises():
assert air_factor(Air()) == 1.0
assert air_factor(Air(visibility_km=40, humidity=50)) == 1.0
assert air_factor(Air(visibility_km=5)) == 0.6 and air_factor(Air(humidity=90)) == 0.75
assert 0.6 < air_factor(Air(visibility_km=30)) < 1.0
assert air_factor(Air(rain_before=70, rain_now=10)) == 1.15
assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음
def test_low_clouds_toward_sun_block_the_light():
canvas = Layers(low=0, mid=20, high=50)
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY