Files
o2o-weather/backend/services/calc/index_calc.py
T
minaChoi ddf05aeb5c feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?'
- 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준
- 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수
- 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리
- 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정
- 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성
- 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시
- 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집
- 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
2026-10-06 16:36:11 +09:00

384 lines
17 KiB
Python

from collections import Counter
from dataclasses import dataclass, field
from datetime import date
from math import cos, pi
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(frozen=True)
class DayForecast:
"""중기예보(일 단위) 하루치. 시간별 예보가 닿지 않는 날의 예상 점수 재료."""
temp_min_c: Optional[float]
temp_max_c: Optional[float]
rain_prob_am: int
rain_prob_pm: int
sky: Sky
@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))
estimated: bool = False
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, until: str = "") -> tuple[int, str]:
prob = f"{until} 비 확률 {max_prob}%" if until else f"비 확률 {max_prob}%"
if rule["dir"] == "wet":
return (100 if raining else _clamp(max_prob)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, {prob}" if raining else prob)
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
if wind is None:
return _UNKNOWN, f"바람 정보가 없어 {_UNKNOWN}점으로 둬요"
if rule["type"] == "ignore":
return 50, f"바람 초속 {wind:g}m, 이 각엔 상관없어 50점으로 둬요"
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, f"{note}, 이 각엔 상관없어 50점으로 둬요"
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
if pm25 is None:
return _UNKNOWN, f"미세먼지 정보가 없어 {_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 f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
)
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
def axis_label(axis: str, rules: dict) -> str:
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
if axis == "rain":
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
if axis == "air":
return "공기 맑음"
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
return table[rules[axis]["type"]]
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:
cap = r.get("cap", 0)
return f"{_cond(r)[0]} {_tail(cap)}", cap
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 _cond(r: dict) -> tuple[str, str, str]:
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
if r["field"] == "warning":
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
return f"{base}이라", f"{base}이거나", f"{base}이면"
def _tail(cap: int) -> str:
return f"최대 {cap}점" if cap else "0점"
def zero_rules_text(rules: list[dict]) -> str:
if not rules:
return "없음 (재미로 보는 지수)"
groups: dict[int, list[dict]] = {}
for r in rules:
groups.setdefault(r.get("cap", 0), []).append(r)
return ", ".join(
" ".join([_cond(r)[1] for r in rs[:-1]] + [_cond(rs[-1])[2]]) + f" {_tail(cap)}" for cap, rs in groups.items()
)
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
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 _SKY_WORD[mid.sky]
)
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int:
worst = min((factors[a] for a in AXES if weights[a]), default=100)
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
def _until(definition) -> str:
ahead = max((w.get("lookahead_days", 0) for w in getattr(definition, "windows", None) or []), default=0)
return {1: "내일까지", 2: "모레까지"}.get(ahead, f"{ahead}일 뒤까지") if ahead else ""
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
until = _until(definition)
for hours in windows:
if not hours:
continue
own_prob = max(h.rain_prob for h in hours)
max_prob = max(own_prob, 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, 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),
"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 = _weighted(factors, weights)
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
def hour_temp(lo: float, hi: float, hour: int) -> float:
"""최저·최고 기온으로 그 시각 기온을 어림한다. 새벽 6시 최저, 오후 3시 최고. 24시 넘으면 다음 날 같은 시각."""
h = hour % 24
f = (1 - cos(pi * (h - 6) / 9)) / 2 if 6 <= h <= 15 else (1 + cos(pi * ((h - 15) % 24) / 15)) / 2
return round(lo + (hi - lo) * f, 1)
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지는 정보 없음으로 둔다. 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}
rules = definition.factor_rules
until = _until(definition)
after = next_fc or fc
for hours in windows:
if not hours:
continue
temps = [hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours]
own_prob = max(fc.rain_prob_am if h < 12 else fc.rain_prob_pm if h < 24 else after.rain_prob_am for h in hours)
max_prob = max(own_prob, ctx.lookahead_rain_prob)
humidity = (50, "습도 이 각엔 상관없어 50점으로 둬요") if rules["humidity"]["type"] == "ignore" else (
_UNKNOWN, f"습도 정보가 없어 {_UNKNOWN}점으로 둬요"
)
temp, temp_note = temp_score(rules["temp"], mean(temps))
scored = {
"temp": (temp, f"{temp_note} (최저·최고 기온으로 어림)"),
"rain": rain_score(rules["rain"], max_prob, False, until if max_prob > own_prob else ""),
"wind": wind_score(rules["wind"], None),
"humidity": humidity,
"air": air_score(None, None),
"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 = _weighted(factors, weights)
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
if reason is not None:
score = min(score, cap)
mid = hours[len(hours) // 2]
summary = f"{hour_label(mid % 24)} {round(hour_temp(fc.temp_min_c, fc.temp_max_c, mid))}° 예상, 비 {max_prob}%"
result = Result(score=score, factors=factors, notes=notes, zero_reason=reason, summary=summary, window=(hours[0], hours[-1]), estimated=True)
if best is None or result.score > best.score:
best = result
return best
# 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다.
OUTING_HOURS = (10, 18)
_OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10}
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}}
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
@dataclass
class Outing:
score: int
factors: dict[str, int]
notes: dict[str, str]
reason: str # 순위 옆 한 줄 근거 ("비 10% · 체감 21° · 맑음")
capped: bool # 비 때문에 최대 30점으로 묶였는지
estimated: bool = False
def _outing(scored: dict[str, tuple[int, str]], prob: int, raining: bool, temp_word: str, sky: Sky, estimated: bool) -> Outing:
factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()}
worst = min(factors.values())
score = round(sum(factors[a] * w for a, w in _OUTING_WEIGHTS.items()) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
capped = raining or prob >= _OUTING_RAIN_PROB
if capped:
score = min(score, _OUTING_RAIN_CAP)
notes["rain"] += f", 비 확률 {_OUTING_RAIN_PROB}% 이상이거나 비 소식이면 최대 {_OUTING_RAIN_CAP}점"
reason = " · ".join(["비 소식" if raining else f"비 {prob}%", temp_word, _SKY_WORD[sky]])
return Outing(score=score, factors=factors, notes=notes, reason=reason, capped=capped, estimated=estimated)
def outing(hours: list[Hour]) -> Optional[Outing]:
"""시간별 예보로 내는 나들이 점수. 10~17시가 다 있어야 한다."""
if len(hours) < OUTING_HOURS[1] - OUTING_HOURS[0]:
return None
prob = max(h.rain_prob for h in hours)
raining = any(h.rain_type is not RainType.NONE for h in hours)
feels = mean(h.feels_c for h in hours)
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
sky = Counter(h.sky for h in hours).most_common(1)[0][0]
scored = {
"temp": temp_score(_OUTING_RULES["temp"], feels),
"rain": rain_score(_OUTING_RULES["rain"], prob, raining),
"sky": (round(mean(_OUTING_SKY[h.sky] for h in hours)), f"하늘 {_SKY_WORD[sky]}"),
"wind": wind_score(_OUTING_RULES["wind"], max(winds) if winds else None),
}
return _outing(scored, prob, raining, f"체감 {round(feels)}°", sky, False)
def outing_estimate(fc: DayForecast) -> Optional[Outing]:
"""중기예보(하루 단위)로 내는 예상 나들이 점수. 바람은 정보 없음으로 둔다."""
if fc.temp_min_c is None or fc.temp_max_c is None:
return None
hours = range(*OUTING_HOURS)
temp = mean(hour_temp(fc.temp_min_c, fc.temp_max_c, h) for h in hours)
prob = max(fc.rain_prob_am, fc.rain_prob_pm)
value, note = temp_score(_OUTING_RULES["temp"], temp)
scored = {
"temp": (value, f"{note} (최저·최고 기온으로 어림)"),
"rain": rain_score(_OUTING_RULES["rain"], prob, False),
"sky": (_OUTING_SKY[fc.sky], f"하늘 {_SKY_WORD[fc.sky]}"),
"wind": wind_score(_OUTING_RULES["wind"], None),
}
return _outing(scored, prob, False, f"낮 {round(temp)}°", fc.sky, True)