Files
o2o-weather/backend/services/calc/my_gak_calc.py
T
minaChoi 93e041bb91 feat: 10/21 회의 반영 — 공유 링크·로그인 없이 댓글·구글 로그인만, 히어로·오늘의 각 좋아요·댓글, 히어로 오늘/내일 스위치, 단풍 지도 65곳·3단계
- 공유: 이미지와 함께 고정 URL을 넘기고 링크도 클립보드에 복사
- 로그인 창은 구글만, 댓글은 로그인 없이 '동네 익명'(링크·전화번호 막기, IP당 하루 20개, 같은 IP만 지우기)
- 히어로·오늘의 각 카드에 좋아요·댓글 (PostType HERO·TODAY_GAK)
- 히어로 오늘/내일 스위치: 내일 구간별 날씨 점수·기온·최저최고·습도·1위 각, /v1/weather/today?day=tomorrow
- 단풍 지도: 단풍 그림 지도, 단풍 전·첫 단풍·절정, 단풍잎·은행잎, 명소 65곳(산림청 예측 + 가까운 지점 날짜)
- 하단 탭 바 불투명 (홈 바 자리로 글이 비치지 않게)
- 사람 글 동네 우선 정렬·내 글 목록, 내 각 '있는 각에서 불러오기'
- 댓글 표 user_id NULL 허용·ip_hash·region_name (운영 DB ALTER 필요)
2026-10-21 17:10:29 +09:00

119 lines
4.9 KiB
Python

from dataclasses import dataclass
from types import SimpleNamespace
from typing import Literal, Optional
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
Rain = Literal["dry", "wet"]
Air = Literal["good", "normal"]
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
def _n(v: float) -> float:
"""근거 문구에 15.0° 대신 15° 로 나오게."""
return int(v) if float(v).is_integer() else v
@dataclass(frozen=True)
class MyRule:
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
wind_max: Optional[float] = None # 바람 상한(m/s)
air: Optional[Air] = None # 미세먼지 허용 단계
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
slots: tuple[str, ...] = SLOTS # 볼 시간대
def axes(rule: MyRule) -> list[str]:
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
def definition(rule: MyRule) -> SimpleNamespace:
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
used = axes(rule)
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
return SimpleNamespace(
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
factor_rules={
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
"rain": {"dir": rule.rain or "dry"},
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
"air": _AIR[rule.air] if rule.air else None,
"time": {"type": "fixed", "value": 100},
},
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
)
# 공식 각을 내 각 조건으로 옮길 때 쓰는 대표 시각(해 뜨고 지는 시각은 계절마다 달라 가운데 값으로)
_SUNRISE_HOUR, _SUNSET_HOUR = 6, 18
_TEMP_MIN, _TEMP_MAX = -20, 40
def _slot_of_hour(h: int) -> str:
h %= 24
if NIGHT_END_HOUR <= h < 11:
return "morning"
if 11 <= h < _SUNSET_HOUR - 2:
return "day"
if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1:
return "evening"
return "night"
def _window_slots(windows: list[dict]) -> list[str]:
hours: set[int] = set()
for w in windows:
if "around" in w:
mid = _SUNRISE_HOUR if w["around"] == "sunrise" else _SUNSET_HOUR
hours.update(range(mid - w["hours"], mid + w["hours"]))
else:
hours.update(range(w["from"], w["to"]))
got = {_slot_of_hour(h) for h in hours}
return [s for s in SLOTS if s in got]
def _preset_temp(r: dict) -> Optional[list[float]]:
off = r.get("offset", 0)
t = r["type"]
if t == "range":
lo, hi = r["lo"] - off, r["hi"] - off
elif t == "higher":
lo, hi = r["full"] - off, _TEMP_MAX
elif t == "lower":
lo, hi = _TEMP_MIN, r["full"] - off
else:
return None # 범위에서 멀수록 좋은 규칙은 범위 하나로 옮길 수 없다
lo, hi = max(_TEMP_MIN, lo), min(_TEMP_MAX, hi)
return [_n(lo), _n(hi)] if lo < hi else None
_PRESET_HUMIDITY = {"higher": [60, 100], "lower": [0, 60]}
def preset(defn) -> dict:
"""공식 각을 내 각 조건(MyGakRule 모양)으로 비슷하게 옮긴다. 비중 0인 요소와 옮길 수 없는 규칙은 뺀다."""
r = defn.factor_rules
out: dict = {"slots": _window_slots(defn.windows) or list(SLOTS)}
if defn.weight_temp and (temp := _preset_temp(r["temp"])):
out["temp"] = temp
if defn.weight_rain:
out["rain"] = r["rain"]["dir"]
wind = r.get("wind", {})
if defn.weight_wind and wind.get("type") in ("calm", "moderate"):
out["wind_max"] = _n(max(1, wind["ok"])) if wind["type"] == "calm" else 5
air = r.get("air")
if defn.weight_air and not (air and air["full"] > air["zero"]):
out["air"] = "normal"
hum = r.get("humidity", {})
if defn.weight_humidity and hum.get("type") in ("range", "higher", "lower"):
out["humidity"] = [hum["lo"], hum["hi"]] if hum["type"] == "range" else _PRESET_HUMIDITY[hum["type"]]
return out