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:
commit
3f8f7daeb1
21 files changed
+1068
-111
No files matched your search
@@ -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()}
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user