feat: Open-Meteo 구름 20·100km 구 코드 저장, 보조값 수집, 활동 지수 10개에 자외선·햇빛·가시거리 반영
구름 - 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용 - cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장 보조값 - openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대) - worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리 - 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE) 지수 - 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시) - 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건 - 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결 - 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가 테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수).
This commit is contained in:
1 parent
7244449b7a
commit
7c12651068
19 files changed
+712
-82
No files matched your search
@@ -6,7 +6,9 @@ from typing import Optional
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.text import hour_label
|
||||
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
||||
# 모든 지수의 상세에 늘 나오는 축. 나머지(자외선·햇빛·가시거리)는 비중이 있는 지수에만 나온다.
|
||||
BASE_AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
@@ -23,6 +25,12 @@ class Hour:
|
||||
wind_ms: Optional[float]
|
||||
humidity: int
|
||||
sky: Sky
|
||||
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
|
||||
uv: Optional[float] = None
|
||||
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
|
||||
visibility_km: Optional[float] = None
|
||||
gust_ms: Optional[float] = None
|
||||
ground_c: Optional[float] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -118,6 +126,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
if uv is None:
|
||||
return _UNKNOWN, "자외선 정보 없음"
|
||||
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
|
||||
|
||||
|
||||
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
|
||||
if ratio is None:
|
||||
return _UNKNOWN, "햇빛 정보 없음"
|
||||
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
|
||||
|
||||
|
||||
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
|
||||
if km is None:
|
||||
return _UNKNOWN, "가시거리 정보 없음"
|
||||
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
|
||||
|
||||
|
||||
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
kind = rule["type"]
|
||||
if kind == "weekday":
|
||||
@@ -147,8 +173,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
return None, None
|
||||
|
||||
|
||||
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%"}
|
||||
_FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
|
||||
|
||||
def zero_text(r: dict) -> str:
|
||||
@@ -179,7 +208,7 @@ def _summary(hours: list[Hour]) -> str:
|
||||
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
||||
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
for hours in windows:
|
||||
if not hours:
|
||||
@@ -188,12 +217,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
uvs = [h.uv for h in hours if h.uv is not None]
|
||||
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
|
||||
views = [h.visibility_km for h in hours if h.visibility_km is not None]
|
||||
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
|
||||
grounds = [h.ground_c for h in hours if h.ground_c is not None]
|
||||
scored = {
|
||||
"temp": temp_score(rules["temp"], feels),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
@@ -205,6 +242,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
|
||||
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 50, 100)
|
||||
DISTANCES_KM = (20, 100)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,11 +14,11 @@ class Layers:
|
||||
high: float
|
||||
|
||||
|
||||
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
def score(near20: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = max(near20.mid, near20.high)
|
||||
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
|
||||
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
|
||||
f_near = 1 - 0.8 * near20.low / 100
|
||||
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
|
||||
Reference in new issue
Block a user