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

+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),