feat: Open-Meteo 구름 20·100km 구 코드 저장, 보조값 수집, 활동 지수 10개에 자외선·햇빛·가시거리 반영

구름
- 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용
- cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장

보조값
- openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대)
- worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리
- 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE)

지수
- 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시)
- 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건
- 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결
- 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가

테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수).
This commit is contained in:
skkim committed 2026-10-06 17:21:59 +09:00
1 parent 7244449b7a
commit 7c12651068
19 files changed
+712 -82

No files matched your search

+42 -4
View File
@@ -6,7 +6,9 @@ from typing import Optional
from common.enums import RainType, Sky
from common.utils.text import hour_label
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
# 모든 지수의 상세에 늘 나오는 축. 나머지(자외선·햇빛·가시거리)는 비중이 있는 지수에만 나온다.
BASE_AXES = ("temp", "rain", "wind", "humidity", "air", "time")
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
_UNKNOWN = 70
@@ -23,6 +25,12 @@ class Hour:
wind_ms: Optional[float]
humidity: int
sky: Sky
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
uv: Optional[float] = None
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
visibility_km: Optional[float] = None
gust_ms: Optional[float] = None
ground_c: Optional[float] = None
@dataclass(frozen=True)
@@ -118,6 +126,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}{', ' + label if label else ''}"
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
if uv is None:
return _UNKNOWN, "자외선 정보 없음"
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
if ratio is None:
return _UNKNOWN, "햇빛 정보 없음"
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
if km is None:
return _UNKNOWN, "가시거리 정보 없음"
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
kind = rule["type"]
if kind == "weekday":
@@ -147,8 +173,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
return None, None
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%"}
_FIELD_TEXT = {
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
"gust_ms": "돌풍", "ground_c": "지표면 온도",
}
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
def zero_text(r: dict) -> str:
@@ -179,7 +208,7 @@ def _summary(hours: list[Hour]) -> str:
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
best: Optional[Result] = None
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
rules = definition.factor_rules
for hours in windows:
if not hours:
@@ -188,12 +217,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
raining = any(h.rain_type is not RainType.NONE for h in hours)
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
feels = mean(h.feels_c for h in hours)
uvs = [h.uv for h in hours if h.uv is not None]
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
views = [h.visibility_km for h in hours if h.visibility_km is not None]
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
grounds = [h.ground_c for h in hours if h.ground_c is not None]
scored = {
"temp": temp_score(rules["temp"], feels),
"rain": rain_score(rules["rain"], max_prob, raining),
"wind": wind_score(rules["wind"], max(winds) if winds else None),
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
"air": air_score(ctx.pm25, ctx.air_label),
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
"time": time_score(rules["time"], ctx),
}
factors = {a: v for a, (v, _) in scored.items()}
@@ -205,6 +242,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
"warning": "wind" if ctx.wind_warning else None,
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
+5 -5
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from common.enums import Confidence, SkyGrade, SkyType
DISTANCES_KM = (20, 50, 100)
DISTANCES_KM = (20, 100)
@dataclass(frozen=True)
@@ -14,11 +14,11 @@ class Layers:
high: float
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
def score(near20: Layers, far100: Layers) -> int:
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
canvas = max(near20.mid, near20.high)
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
f_near = 1 - 0.8 * near20.low / 100
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
+59 -3
View File
@@ -1,12 +1,12 @@
import asyncio
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
import httpx
from common.enums import CloudModel
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
@@ -15,6 +15,11 @@ class OpenMeteoRequestFailed(RuntimeError):
_CHUNK = 24
WEATHER_VARS = (
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
)
SLOT_HOURS = 3
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
@@ -31,6 +36,10 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
for attempt in range(_ATTEMPTS):
try:
res = await client.get(URL, params=params)
@@ -40,7 +49,23 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
except (httpx.HTTPError, ValueError) as e:
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
await asyncio.sleep(1.0 * (attempt + 1))
raise OpenMeteoRequestFailed(f"forecast {len(points)} points: {last}")
raise OpenMeteoRequestFailed(f"forecast {point_count} points: {last}")
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
}
return await _get_forecast(client, params, len(points))
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
@@ -55,3 +80,34 @@ def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
continue
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
return rows
def _round(v, digits: int = 0):
return None if v is None else (round(v, digits) if digits else int(round(v)))
def parse_weather(data: dict) -> list[dict]:
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀)."""
h = data["hourly"]
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
index = {t: i for i, t in enumerate(times)}
rows = []
for end, i in index.items():
if end.hour % SLOT_HOURS:
continue
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
if None in span:
continue
sun = [h["sunshine_duration"][j] for j in span]
rad = [h["shortwave_radiation"][j] for j in span]
rows.append({
"forecast_at": end,
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
"sunshine_s": None if None in sun else int(round(sum(sun))),
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
})
return rows
+45 -6
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, WeatherHourly
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherHourly
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.index_crud import IndexCRUD
@@ -58,8 +58,36 @@ def _hour(r: WeatherHourly) -> Hour:
)
def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly]) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다."""
def _slot_end_hour(h: int) -> int:
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
return (h + 3) // 3 * 3
def _nearest_slot_end_hour(h: int) -> int:
"""h시~h+1시의 한가운데에 가장 가까운 3시간 구간 끝 시각. 자외선·가시거리·돌풍·지표면 온도처럼 '끝 시각 순간값'에 쓴다 (9시→9시, 10시→12시)."""
return int((h + 0.5) / 3 + 0.5) * 3
def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict:
"""3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음')."""
fields = {}
if instant is not None:
fields |= {
"uv": float(instant.uv_index) if instant.uv_index is not None else None,
"visibility_km": instant.visibility_m / 1000 if instant.visibility_m is not None else None,
"gust_ms": float(instant.wind_gust_ms) if instant.wind_gust_ms is not None else None,
"ground_c": float(instant.soil_temp_c) if instant.soil_temp_c is not None else None,
}
if covering is not None and covering.sunshine_s is not None:
fields["sunshine_ratio"] = min(covering.sunshine_s / 10800, 1.0)
return fields
def windows_for(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
) -> list[list[Hour]]:
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
by_om = by_om or {}
start = kst_midnight(day)
out = []
for w in defn.windows:
@@ -69,7 +97,12 @@ def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHo
else:
hours = range(w["from"], w["to"])
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
out.append([replace(_hour(r), hour=h) for h, r in zip(hours, rows) if r is not None])
out.append([
replace(_hour(r), hour=h, **_om_fields(
by_om.get(start + timedelta(hours=_nearest_slot_end_hour(h))), by_om.get(start + timedelta(hours=_slot_end_hour(h)))
))
for h, r in zip(hours, rows) if r is not None
])
return out
@@ -140,6 +173,10 @@ class IndexService:
return err, None
if not rows:
return ErrorType.EXTERNAL_API_ERROR, None
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
)
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
air = await self.air_service.nearest(region)
by_at = {r.forecast_at: r for r in rows}
base_ctx = dict(
@@ -148,10 +185,12 @@ class IndexService:
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at), today_ctx)
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
issued = max(r.issued_at for r in rows)
inputs_at = max(issued, air.measured_at) if air else issued
if by_om:
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at:
return ErrorType.SUCCESS, weather_result.score if weather_result else None
@@ -171,7 +210,7 @@ class IndexService:
)
for d in defs:
day_ctx = replace(ctx, lookahead_rain_prob=lookahead_rain(d, day, by_at))
result = evaluate(d, windows_for(d, day, region, by_at), day_ctx)
result = evaluate(d, windows_for(d, day, region, by_at, by_om), day_ctx)
if result is None:
continue
out.append({
+23 -17
View File
@@ -66,10 +66,8 @@ def _nearest_hour(at: datetime) -> datetime:
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
first = sun_times(today, float(region.lat), float(region.lon))
rows = []
for kind, azimuth in ((SkyType.SUNSET, first.sunset_azimuth), (SkyType.SUNRISE, first.sunrise_azimuth)):
pts = _points(region, azimuth)
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
for i in range(DAYS):
d = today + timedelta(days=i)
st: SunTimes = sun_times(d, float(region.lat), float(region.lon))
@@ -77,12 +75,12 @@ def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> lis
hour = _nearest_hour(sun_at)
per_model = []
highs = []
for model in {k[2] for k in clouds}:
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
for model in {k[4] for k in clouds}:
layers = [clouds.get((region.code, kind.value, km, hour, model)) for km in DISTANCES_KM]
if None in layers:
continue
per_model.append(score(*layers))
highs.append((layers[0].high + layers[1].high) / 2)
highs.append(layers[0].high)
if not per_model:
continue
value = round(statistics.mean(per_model))
@@ -174,24 +172,32 @@ class SkyService:
plan = {}
for r in regions:
st = sun_times(today, float(r.lat), float(r.lon))
plan[r.code] = _points(r, st.sunset_azimuth) + _points(r, st.sunrise_azimuth)
points = sorted({p for pts in plan.values() for p in pts})
plan[r.code] = {SkyType.SUNSET: _points(r, st.sunset_azimuth), SkyType.SUNRISE: _points(r, st.sunrise_azimuth)}
points = sorted({p for kinds in plan.values() for pts in kinds.values() for p in pts})
try:
async with httpx.AsyncClient(timeout=30) as client:
data = await fetch_clouds(client, points, days=DAYS)
except OpenMeteoRequestFailed as e:
LOG.error(f"[sky] {len(regions)} regions: {e}")
return
needed_hours = {
_nearest_hour(at)
for r in regions
for i in range(DAYS)
for st in [sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))]
for at in (st.sunset_at, st.sunrise_at)
}
cloud_rows = [row for p, d in zip(points, data) for row in parse_clouds(p, d) if row["forecast_at"] in needed_hours]
by_point: dict[tuple[float, float], dict[datetime, list[dict]]] = {}
for p, d in zip(points, data):
for row in parse_clouds(p, d):
by_point.setdefault(p, {}).setdefault(row["forecast_at"], []).append(row)
cloud_rows = []
for r in regions:
for kind, pts in plan[r.code].items():
for i in range(DAYS):
st = sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))
hour = _nearest_hour(st.sunset_at if kind is SkyType.SUNSET else st.sunrise_at)
for km, p in zip(DISTANCES_KM, pts):
cloud_rows += [
{"region_code": r.code, "kind": kind.value, "distance_km": km, "forecast_at": hour, "model": row["model"],
"cloud_low": row["cloud_low"], "cloud_mid": row["cloud_mid"], "cloud_high": row["cloud_high"]}
for row in by_point.get(p, {}).get(hour, [])
]
clouds = {
(float(r["lat"]), float(r["lon"]), r["model"], r["forecast_at"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
(r["region_code"], r["kind"], r["distance_km"], r["forecast_at"], r["model"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
for r in cloud_rows
}
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now)]