Merge branch 'main' into feat/open-meteo
# Conflicts: # backend/router/v1/index/index.py # backend/services/calc/index_calc.py # backend/services/index_service.py # backend/tests/conftest.py # backend/tests/test_index_api.py # backend/tests/test_index_calc.py # backend/tests/test_sky_api.py # backend/worker_main.py
This commit is contained in:
commit
1a1df4bb87
111 files changed
+5787
-679
No files matched your search
@@ -1,5 +1,7 @@
|
||||
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
|
||||
|
||||
@@ -7,8 +9,6 @@ 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
|
||||
@@ -45,6 +45,16 @@ class Context:
|
||||
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
|
||||
@@ -53,6 +63,7 @@ class Result:
|
||||
zero_reason: Optional[str]
|
||||
summary: str
|
||||
window: tuple[int, int] = field(default=(0, 0))
|
||||
estimated: bool = False
|
||||
|
||||
|
||||
def _clamp(v: float) -> int:
|
||||
@@ -74,7 +85,7 @@ def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float)
|
||||
|
||||
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)}°"
|
||||
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 '밖'}"
|
||||
@@ -85,15 +96,18 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
return _linear(t, rule["zero"], rule["full"]), shown
|
||||
|
||||
|
||||
def rain_score(rule: dict, max_prob: int, raining: bool) -> tuple[int, str]:
|
||||
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"비 소식, 확률 {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}%")
|
||||
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 or rule["type"] == "ignore":
|
||||
return (_UNKNOWN if wind is None else 50), ("바람 정보 없음" if wind is None else f"바람 초속 {wind:g}m")
|
||||
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"]
|
||||
@@ -117,13 +131,13 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
return _linear(humidity, 40, 90), note
|
||||
if rule["type"] == "lower":
|
||||
return _linear(humidity, 90, 40), note
|
||||
return 50, note
|
||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
||||
|
||||
|
||||
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 ''}"
|
||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
@@ -154,9 +168,29 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
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"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), "시간대 그대로"
|
||||
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": "시간대 알맞음"}
|
||||
# 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":
|
||||
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]]:
|
||||
@@ -169,7 +203,8 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
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)
|
||||
cap = r.get("cap", 0)
|
||||
return f"{_cond(r)[0]} {_tail(cap)}", cap
|
||||
return None, None
|
||||
|
||||
|
||||
@@ -177,43 +212,65 @@ _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": "°"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
|
||||
|
||||
def zero_text(r: dict) -> str:
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있으면"
|
||||
op = "이상" if r["op"] == ">=" else "미만"
|
||||
return f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {op}이면"
|
||||
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 "없음 (재미로 보는 지수)"
|
||||
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}"
|
||||
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 "맑음"
|
||||
"바람 살랑" 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}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
for hours in windows:
|
||||
if not hours:
|
||||
continue
|
||||
max_prob = max(max(h.rain_prob for h in hours), ctx.lookahead_rain_prob)
|
||||
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)
|
||||
@@ -224,7 +281,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
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),
|
||||
"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),
|
||||
@@ -235,8 +292,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
}
|
||||
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))
|
||||
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)),
|
||||
@@ -251,3 +307,118 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
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}", 0) 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),
|
||||
**{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()}
|
||||
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)
|
||||
@@ -58,4 +58,38 @@ def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_clou
|
||||
]
|
||||
|
||||
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "흐림"}
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "잿빛"}
|
||||
|
||||
GO_SCORE = 60
|
||||
MAYBE_SCORE = 40
|
||||
VERDICT_LINE = {"go": "나가 볼 만해요", "maybe": "애매해요", "rest": "쉬어요"}
|
||||
|
||||
|
||||
def verdict(value: int) -> str:
|
||||
return "go" if value >= GO_SCORE else "maybe" if value >= MAYBE_SCORE else "rest"
|
||||
|
||||
|
||||
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 reason(near20: Layers, far100: Layers) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
||||
if near20.low >= 60:
|
||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
||||
canvas = round(max(near20.mid, near20.high))
|
||||
if canvas < 10:
|
||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
||||
if canvas > 85:
|
||||
return f"중·높은 구름이 {canvas}%로 두꺼워 빛이 덜 비쳐요"
|
||||
if 25 <= canvas <= 75:
|
||||
return f"중·높은 구름이 {canvas}% 알맞게 깔리고 해 지는 쪽이 트였어요"
|
||||
return f"물들 중·높은 구름이 {canvas}%로 {'적은' if canvas < 25 else '많은'} 편이에요"
|
||||
|
||||
|
||||
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime) -> list[dict]:
|
||||
"""일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워. 분 아래는 버린다."""
|
||||
rows = [("golden", "골든아워", golden_at), ("sun", "해 져요", sun_at), ("peak", "가장 붉을 때", peak_at), ("blue", "블루아워", blue_at)]
|
||||
return [{"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label} for kind, label, at in rows if at is not None]
|
||||
@@ -4,6 +4,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
_SUN_ALTITUDE = -0.833
|
||||
_CIVIL_ALTITUDE = -6.0
|
||||
_GOLDEN_ALTITUDE = 6.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,6 +15,7 @@ class SunTimes:
|
||||
sunset_azimuth: int
|
||||
dawn_start_at: datetime
|
||||
sunrise_azimuth: int
|
||||
golden_start_at: datetime
|
||||
|
||||
|
||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||
@@ -41,6 +43,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
at = lambda minutes: base + timedelta(minutes=minutes) # noqa: E731
|
||||
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
||||
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
||||
h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
||||
return SunTimes(
|
||||
@@ -50,4 +53,5 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
sunset_azimuth=round(360 - azimuth),
|
||||
dawn_start_at=at(noon_min - h_civil),
|
||||
sunrise_azimuth=round(azimuth),
|
||||
golden_start_at=at(noon_min + h_golden),
|
||||
)
|
||||
Reference in new issue
Block a user