- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가 - 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시) - 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리 - 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리 - pytest 66개 (테스트 전용 DB·Redis 사용) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
7.9 KiB
Python
197 lines
7.9 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
|
|
|
|
|
|
@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 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"]
|
|
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
|
return _clamp(100 - 8 * dist), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if dist == 0 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":
|
|
return (100 if wind <= rule["ok"] else _linear(wind, rule["limit"], rule["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":
|
|
dist = 0 if rule["lo"] <= humidity <= rule["hi"] else min(abs(humidity - rule["lo"]), abs(humidity - rule["hi"]))
|
|
return _clamp(100 - 2 * dist), 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()}
|
|
score = round(sum(factors[a] * weights[a] for a in AXES) / 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
|