- 각 점수: 편한 범위 안에서도 최적값에서만 100, 가장 나쁜 요인이 전체를 끌어내림 - 피드 노을 시간대 각 정렬 오류 수정 - 주말 카드 매일 노출, 예보가 닿으면 다음 주말 슬라이드 추가, 주말·행사 탭 열흘 - 지역 256→230 (일반구 39개를 시 13개로) - 회의 기록과 TODO.md 추가
212 lines
8.6 KiB
Python
212 lines
8.6 KiB
Python
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", "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
|
|
|
|
|
|
@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 '밖'}"
|
|
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 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": "흐린 하늘"}
|
|
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "", "cloudy_ratio": "%"}
|
|
|
|
|
|
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}") 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)
|
|
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),
|
|
"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,
|
|
}
|
|
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
|