import statistics from dataclasses import dataclass from datetime import datetime, timedelta from common.enums import Confidence, SkyGrade, SkySituation, SkyType DISTANCES_KM = (20, 100) # 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함). _CLEAR_CANVAS = 0.2 # 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다. RAIN_BEFORE_HOURS = (2, 6) @dataclass(frozen=True) class Layers: low: float mid: float high: float @dataclass(frozen=True) class Air: """구 중심의 해 질(뜰) 무렵 공기. 값이 없으면 보정하지 않는다.""" visibility_km: float | None = None humidity: float | None = None rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률 rain_now: int | None = None def score(near20: Layers, far100: Layers) -> int: """머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다.""" canvas = max(near20.mid, near20.high) f_canvas = _CLEAR_CANVAS + (1 - _CLEAR_CANVAS) * canvas / 50 if canvas <= 50 else max(0.0, 1 - (canvas - 50) / 50) f_near = 1 - 0.8 * near20.low / 100 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 _ramp(v: float, bad: float, good: float, low: float) -> float: """good 쪽은 1.0, bad 쪽은 low, 사이는 직선.""" t = max(0.0, min(1.0, (v - bad) / (good - bad))) return low + (1 - low) * t def air_factor(air: Air) -> float: """공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다.""" f = 1.0 if air.visibility_km is not None: f *= _ramp(air.visibility_km, 5, 40, 0.6) if air.humidity is not None: f *= _ramp(air.humidity, 90, 50, 0.75) if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40: f *= 1.15 return f 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: "잿빛"} 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 situation(near20: Layers, far100: Layers) -> SkySituation: """하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양.""" if far100.low + 0.5 * far100.mid >= 60: return SkySituation.COVERED if near20.low >= 60: return SkySituation.LOW_CLOUD canvas = max(near20.mid, near20.high) if canvas < 25: return SkySituation.FEW if canvas > 75: return SkySituation.THICK return SkySituation.GLOW SITUATION_LINE = { SkySituation.COVERED: "구름에 가려요", SkySituation.LOW_CLOUD: "낮은 구름이 덮어요", SkySituation.FEW: "구름이 적어 짧게 끝나요", SkySituation.GLOW: "하늘이 넓게 물들 수 있어요", SkySituation.THICK: "구름이 두꺼워 색이 약해요", } SITUATION_VERDICT = { SkySituation.COVERED: "rest", SkySituation.LOW_CLOUD: "rest", SkySituation.FEW: "maybe", SkySituation.GLOW: "go", SkySituation.THICK: "maybe", } VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2} 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]