feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- 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>
This commit is contained in:
1 parent
9cdc0d8fea
commit
e134295ce5
135 files changed
+9123
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,196 @@
|
||||
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
|
||||
@@ -0,0 +1,11 @@
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_SYNODIC_DAYS = 29.530588
|
||||
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def illumination(at: datetime) -> float:
|
||||
"""달이 밝게 보이는 비율 0(그믐)~1(보름). 평균 삭망월 근사."""
|
||||
phase = ((at - _KNOWN_NEW_MOON).total_seconds() / 86400 % _SYNODIC_DAYS) / _SYNODIC_DAYS
|
||||
return (1 - math.cos(2 * math.pi * phase)) / 2
|
||||
@@ -0,0 +1,61 @@
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 50, 100)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Layers:
|
||||
low: float
|
||||
mid: float
|
||||
high: float
|
||||
|
||||
|
||||
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
|
||||
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
|
||||
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
|
||||
def grade(value: int) -> SkyGrade:
|
||||
if value >= 80:
|
||||
return SkyGrade.RED
|
||||
if value >= 60:
|
||||
return SkyGrade.GLOW
|
||||
if value >= 40:
|
||||
return SkyGrade.SOFT
|
||||
return SkyGrade.GRAY
|
||||
|
||||
|
||||
def confidence(model_scores: list[int]) -> Confidence:
|
||||
"""모델끼리 점수가 비슷할수록 확신이 높다."""
|
||||
if len(model_scores) < 2:
|
||||
return Confidence.LOW
|
||||
spread = statistics.pstdev(model_scores)
|
||||
return Confidence.HIGH if spread < 8 else Confidence.NORMAL if spread < 15 else Confidence.LOW
|
||||
|
||||
|
||||
def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_cloud: float) -> list[dict]:
|
||||
"""노을은 해 진 뒤 10~20분이 가장 붉다. 높은 구름이 많을수록 늦게까지 물든다."""
|
||||
peak_min = 10 + round(min(high_cloud, 100) / 10)
|
||||
sun_at, twilight_at = sun_at.replace(second=0, microsecond=0), twilight_at.replace(second=0, microsecond=0)
|
||||
if kind is SkyType.SUNSET:
|
||||
return [
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 져요"},
|
||||
{"at": (sun_at + timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
|
||||
]
|
||||
return [
|
||||
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "푸른 새벽"},
|
||||
{"at": (sun_at - timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
|
||||
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 떠요"},
|
||||
]
|
||||
|
||||
|
||||
GRADE_LABEL = {SkyGrade.RED: "붉음", SkyGrade.GLOW: "고움", SkyGrade.SOFT: "은은함", SkyGrade.GRAY: "흐림"}
|
||||
@@ -0,0 +1,53 @@
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
_SUN_ALTITUDE = -0.833
|
||||
_CIVIL_ALTITUDE = -6.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SunTimes:
|
||||
sunrise_at: datetime
|
||||
sunset_at: datetime
|
||||
dusk_end_at: datetime
|
||||
sunset_azimuth: int
|
||||
dawn_start_at: datetime
|
||||
sunrise_azimuth: int
|
||||
|
||||
|
||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||
"""NOAA 근사식. (태양 적위 도, 남중 시각 UTC 분)."""
|
||||
g = 2 * math.pi / 365 * (d.timetuple().tm_yday - 1)
|
||||
eqtime = 229.18 * (
|
||||
0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g) - 0.014615 * math.cos(2 * g) - 0.040849 * math.sin(2 * g)
|
||||
)
|
||||
decl = (
|
||||
0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g) - 0.006758 * math.cos(2 * g)
|
||||
+ 0.000907 * math.sin(2 * g) - 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g)
|
||||
)
|
||||
return math.degrees(decl), 720 - 4 * lon - eqtime
|
||||
|
||||
|
||||
def _hour_angle(lat: float, decl: float, altitude: float) -> float:
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
cos_h = (math.sin(math.radians(altitude)) - math.sin(phi) * math.sin(dl)) / (math.cos(phi) * math.cos(dl))
|
||||
return math.degrees(math.acos(max(-1.0, min(1.0, cos_h))))
|
||||
|
||||
|
||||
def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
decl, noon_min = _solar(d, lon)
|
||||
base = datetime(d.year, d.month, d.day, tzinfo=timezone.utc)
|
||||
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
|
||||
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(
|
||||
sunrise_at=at(noon_min - h_sun),
|
||||
sunset_at=at(noon_min + h_sun),
|
||||
dusk_end_at=at(noon_min + h_civil),
|
||||
sunset_azimuth=round(360 - azimuth),
|
||||
dawn_start_at=at(noon_min - h_civil),
|
||||
sunrise_azimuth=round(azimuth),
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def wet_bulb_c(temp_c: float, humidity: float) -> float:
|
||||
"""Stull(2011) 습구온도 근사식."""
|
||||
t, rh = temp_c, humidity
|
||||
return (
|
||||
t * math.atan(0.151977 * math.sqrt(rh + 8.313659))
|
||||
+ math.atan(t + rh)
|
||||
- math.atan(rh - 1.676331)
|
||||
+ 0.00391838 * rh ** 1.5 * math.atan(0.023101 * rh)
|
||||
- 4.686035
|
||||
)
|
||||
|
||||
|
||||
def feels_like_c(temp_c: float, humidity: float, wind_ms: Optional[float], month: int) -> float:
|
||||
"""기상청 체감온도: 5~9월은 여름식(습도), 10~4월은 겨울식(바람)."""
|
||||
if 5 <= month <= 9:
|
||||
tw = wet_bulb_c(temp_c, humidity)
|
||||
return round(-0.2442 + 0.55399 * tw + 0.45535 * temp_c - 0.0022 * tw ** 2 + 0.00278 * tw * temp_c + 3.0, 1)
|
||||
v = (wind_ms or 0.0) * 3.6
|
||||
if temp_c > 10 or v < 4.8:
|
||||
return round(temp_c, 1)
|
||||
return round(13.12 + 0.6215 * temp_c - 11.37 * v ** 0.16 + 0.3965 * temp_c * v ** 0.16, 1)
|
||||
|
||||
|
||||
def discomfort_index(temp_c: float, humidity: float) -> int:
|
||||
return round(0.81 * temp_c + 0.01 * humidity * (0.99 * temp_c - 14.3) + 46.3)
|
||||
Reference in new issue
Block a user