from dataclasses import dataclass, field from datetime import date from statistics import mean from typing import Optional from common.enums import RainType, Sky from common.utils.text import hour_label 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 _EDGE = 85 _WORST_PULL = 0.25 @dataclass(frozen=True) class Hour: hour: int feels_c: float rain_type: RainType rain_prob: int 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) class Context: day: date is_holiday: bool pm25: Optional[int] air_label: Optional[str] moon: float sunset_score: Optional[int] wind_warning: bool lookahead_rain_prob: int @dataclass class Result: score: int factors: dict[str, int] notes: dict[str, str] zero_reason: Optional[str] summary: str window: tuple[int, int] = field(default=(0, 0)) def _clamp(v: float) -> int: return round(max(0.0, min(100.0, v))) def _linear(v: float, zero: float, full: float) -> int: return _clamp((v - zero) / (full - zero) * 100) def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float) -> int: """최적값에서만 100. 편한 범위 끝은 _EDGE, 범위 밖은 한 단위마다 per_out 씩 깎는다.""" best = (lo + hi) / 2 if best is None else best if v < lo or v > hi: return _clamp(_EDGE - per_out * min(abs(v - lo), abs(v - hi))) side = (best - lo) if v < best else (hi - best) return _clamp(100 - (100 - _EDGE) * (abs(v - best) / side if side else 0)) def temp_score(rule: dict, feels: float) -> tuple[int, str]: t = feels + rule.get("offset", 0) shown = f"정상 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°" if rule["type"] == "range": lo, hi = rule["lo"], rule["hi"] return _peak(t, lo, hi, rule.get("best"), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}" if rule["type"] == "away": lo, hi = rule["lo"], rule["hi"] dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi)) return _clamp(30 + 7 * dist), f"{shown}, 편한 범위 {lo}~{hi}°에서 멀수록 올라가요" return _linear(t, rule["zero"], rule["full"]), shown def rain_score(rule: dict, max_prob: int, raining: bool) -> tuple[int, str]: if rule["dir"] == "wet": return (100 if raining else _clamp(max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%, 비 오면 올라가요") return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, 확률 {max_prob}%" if raining else f"비 확률 {max_prob}%") def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]: if wind is None or rule["type"] == "ignore": return (_UNKNOWN if wind is None else 50), ("바람 정보 없음" if wind is None else f"바람 초속 {wind:g}m") note = f"바람 초속 {wind:g}m" if rule["type"] == "calm": ok = rule["ok"] if wind <= ok / 2: return 100, note if wind <= ok: return _clamp(100 - (100 - _EDGE) * (wind - ok / 2) / (ok / 2)), note return _clamp(_EDGE * (rule["limit"] - wind) / (rule["limit"] - ok)), note if rule["type"] == "moderate": if 2 <= wind <= 5: return 100, note return (_clamp(60 + 20 * wind) if wind < 2 else _linear(wind, 12, 5)), note return _linear(wind, 0, 8), note def humidity_score(rule: dict, humidity: float) -> tuple[int, str]: note = f"습도 {round(humidity)}%" if rule["type"] == "range": return _peak(humidity, rule["lo"], rule["hi"], rule.get("best"), 2), note if rule["type"] == "higher": return _linear(humidity, 40, 90), note if rule["type"] == "lower": return _linear(humidity, 90, 40), note return 50, note def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]: if pm25 is None: return _UNKNOWN, "미세먼지 정보 없음" 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": key = "holiday" if ctx.is_holiday and "holiday" in rule else _WEEKDAY[ctx.day.weekday()] v = rule.get(key, rule.get("default", 100)) return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}" if kind == "moon": return _clamp(20 + 80 * (1 - ctx.moon)), f"달 밝기 {round(ctx.moon * 100)}%" if kind == "sunset_score": return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), ( f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else "노을 점수 계산 전" ) return _clamp(rule["value"]), "시간대 그대로" def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]: """걸린 조건의 이유와 상한(cap). cap 이 없으면 0점. (최소, 최대) 값은 '이상'이면 최대, '미만'이면 최소로 본다.""" for r in rules: v = agg.get(r["field"]) if isinstance(v, tuple): v = v[1] if r["op"] == ">=" else v[0] if v is None: continue hit = (v >= r["value"]) if r["op"] == ">=" else (v < r["value"]) if r["op"] == "<" else (v == r["value"]) if hit: return zero_text(r), r.get("cap", 0) return None, None _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: if r["field"] == "warning": return "강풍 특보가 있으면" op = "이상" if r["op"] == ">=" else "미만" return f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {op}이면" def zero_rules_text(rules: list[dict]) -> str: if not rules: return "없음 (재미로 보는 지수)" parts = [zero_text(r) for r in rules] caps = {r.get("cap") for r in rules} tail = f"{caps.pop()}점 아래로" if caps != {None} and len(caps) == 1 else "바로 0점" return " 또는 ".join(p.removesuffix("이면") for p in parts) + f"이면 {tail}" def _summary(hours: list[Hour]) -> str: mid = hours[len(hours) // 2] wind = mid.wind_ms tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else ( "바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else "맑음" ) return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}" def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]: """지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽.""" best: Optional[Result] = None weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES} rules = definition.factor_rules for hours in windows: if not hours: continue max_prob = max(max(h.rain_prob for h in hours), ctx.lookahead_rain_prob) 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()} notes = {a: n for a, (_, n) in scored.items()} worst = min((factors[a] for a in AXES if weights[a]), default=100) score = round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100)) agg = { "rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25, "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: score = min(score, cap) result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=_summary(hours), window=(hours[0].hour, hours[-1].hour)) if best is None or result.score > best.score: best = result return best