Files
o2o-weather/backend/services/saju/climate.py
T
minaChoi 0399942fb1 feat: 날씨 사주 — 원국(만세력)·일진 해석·조후 날씨 궁합으로 오늘 점수와 할 일, 레벨로 이번 주·금전·연애·궁합·이달·올해
- 엔진(services/saju): 절입 시각을 천문 계산(KASI 대비 최대 41초), 지방평균시·서머타임 보정, 네 기둥, 십성·합충형파해원진·도화·홍염, 조후(한난조습)와 시간별 날씨 맞춤
- API: POST /v1/saju/reading, POST /v1/saju/match (레벨 5). 생년월일은 저장하지 않음, 레벨은 서버에서 잠금
- 화면(/saju): 오늘의 점수(사주+날씨 궁합)와 결정 카드(언제·할 것·조심할 것·좋은 흐름·입을 것·갈 곳), 내 기운(계절·날씨 장면 16종), 잠긴 것은 다음 하나와 남은 각
- 오늘 탭 아이콘 줄에 날씨 사주, 사주 보면 +10각
- GA4 saju_input·saju_view
2026-10-28 15:44:08 +09:00

193 lines
8.6 KiB
Python

"""조후(한난조습): 내 사주의 차고 더움·마르고 젖음과 오늘 날씨가 잘 맞는지."""
from dataclasses import dataclass
from typing import Iterable
from services.saju.pillars import Chart
# 글자별 (한난, 조습) 초안 — 주인 확인 필요. 한난: 차가움 −1 … 따뜻함 +1, 조습: 마름 −1 … 습함 +1
# 丙丁巳午는 불이라 따뜻하고 말리며, 壬癸亥子는 물이라 차고 젖는다. 庚辛申酉는 가을 쇠라 서늘하고 마르고,
# 戊未戌는 마른 흙(조토), 己丑辰은 젖은 흙(습토)이다. 甲乙寅卯 나무는 온화하되 寅卯는 초봄 남은 추위로 조금 서늘하게 둔다
CHAR_CLIMATE: dict[str, tuple[float, float]] = {
"甲": (0.0, 0.1), "乙": (0.0, 0.2),
"丙": (1.0, -0.5), "丁": (0.7, -0.3),
"戊": (0.3, -0.6), "己": (0.0, 0.6),
"庚": (-0.5, -0.5), "辛": (-0.4, -0.4),
"壬": (-0.7, 0.9), "癸": (-0.6, 1.0),
"子": (-1.0, 0.8), "丑": (-0.8, 0.6), # 한겨울 물, 언 젖은 흙
"寅": (-0.3, 0.0), "卯": (-0.1, 0.2),
"辰": (0.0, 0.6), # 봄 젖은 흙 (물 창고)
"巳": (0.8, -0.3), "午": (1.0, -0.5),
"未": (0.6, -0.7), # 여름 끝 마른 흙
"申": (-0.3, -0.3), "酉": (-0.5, -0.5),
"戌": (0.2, -0.8), # 가을 마른 흙 (불 창고)
"亥": (-0.7, 0.8),
}
# 자리별 비중. 태어난 달(월령)이 계절을 정하므로 월지를 가장 크게
CHART_WEIGHTS = {
("year", "stem"): 1.0, ("year", "branch"): 1.0, ("month", "stem"): 1.0, ("month", "branch"): 3.0,
("day", "stem"): 1.0, ("day", "branch"): 1.5, ("hour", "stem"): 1.0, ("hour", "branch"): 1.0,
}
SEASONS = {"寅卯辰": "봄", "巳午未": "여름", "申酉戌": "가을", "亥子丑": "겨울"}
# 날씨 → 같은 두 축. 한난: 체감 15°C 가 0, 15°C 차이마다 ±1. 조습: 습도 55% 가 0, 35%p 차이마다 ±1, 비가 오면 최소 +0.8
WEATHER_SCALE = {"neutral_c": 15.0, "span_c": 15.0, "neutral_humidity": 55.0, "span_humidity": 35.0, "rain_moist": 0.8}
# 맞춤 점수 (초안)
MATCH = {
"pull": 0.3, # 날씨가 사주를 움직이는 정도 (날씨 1 이 사주 축을 0.3 옮긴다)
"balanced": 0.1, # 사주 축 값이 이보다 작으면 이미 균형
"mild": 0.3, # 날씨 축 값이 이보다 작으면 순한 날씨
"keep_gain": 0.3, # 균형인 축에서 순한 날씨면 +, 거센 날씨면 − 를 주는 세기
"axis_share": {"temp": 0.6, "moist": 0.4}, # 한난을 조습보다 먼저 본다
"scale": 120, # 효과 합을 점수로 바꾸는 배율 (50 ± scale × 효과)
"trim": 5, # 3시간 창 끝 시간이 나머지 평균보다 이만큼 낮으면 빼고 2시간으로
}
DAY_HOURS = range(6, 22) # 하루 점수·좋은 시간대를 볼 시각 (06~21시)
AXES = ("temp", "moist")
@dataclass(frozen=True)
class HourWeather:
hour: int # 0~23
feels_c: float
humidity: float # %
raining: bool = False
@dataclass(frozen=True)
class ChartClimate:
temp: float
moist: float
label: str # 따뜻·마름 / 따뜻·촉촉 / 서늘·마름 / 서늘·촉촉
season: str # 월지 계절
need: dict[str, str] # {"temp": warm|cool|mild, "moist": dry|moist|mild}
parts: tuple[dict, ...] # 글자별 기여 {"position", "part", "char", "temp", "moist", "weight"}
@dataclass(frozen=True)
class HourMatch:
hour: int
score: int
weather: dict[str, float] # 날씨를 두 축으로 바꾼 값
effect: dict[str, float] # 축별 효과 (+ 균형 쪽, − 반대쪽)
@dataclass(frozen=True)
class ClimateMatch:
chart: ChartClimate
score: int # 50 이 보통
hours: tuple[HourMatch, ...]
best_hours: tuple[int, ...]
reasons: tuple[dict, ...] # 좋은 시간대의 축별 이유
def _clamp(x: float, lo: float = -1.0, hi: float = 1.0) -> float:
return max(lo, min(hi, x))
def chart_climate(chart: Chart) -> ChartClimate:
parts = []
for pos, p in chart.pillars().items():
for part, char in (("stem", p.stem), ("branch", p.branch)):
t, m = CHAR_CLIMATE[char]
parts.append({"position": pos, "part": part, "char": char, "temp": t, "moist": m, "weight": CHART_WEIGHTS[(pos, part)]})
total = sum(x["weight"] for x in parts)
temp = round(sum(x["temp"] * x["weight"] for x in parts) / total, 3)
moist = round(sum(x["moist"] * x["weight"] for x in parts) / total, 3)
b = MATCH["balanced"]
need = {
"temp": "warm" if temp < -b else "cool" if temp > b else "mild",
"moist": "dry" if moist > b else "moist" if moist < -b else "mild",
}
label = f"{'따뜻' if temp >= 0 else '서늘'}·{'촉촉' if moist >= 0 else '마름'}"
season = next(name for group, name in SEASONS.items() if chart.month.branch in group)
return ChartClimate(temp, moist, label, season, need, tuple(parts))
def weather_vector(w: HourWeather) -> dict[str, float]:
s = WEATHER_SCALE
temp = _clamp((w.feels_c - s["neutral_c"]) / s["span_c"])
moist = _clamp((w.humidity - s["neutral_humidity"]) / s["span_humidity"])
if w.raining:
moist = max(moist, s["rain_moist"])
return {"temp": round(temp, 3), "moist": round(moist, 3)}
def axis_effect(chart_value: float, weather_value: float) -> float:
"""균형(0)에 얼마나 가까워지는지. 이미 균형인 축은 순한 날씨를 반긴다."""
moved = abs(chart_value) - abs(chart_value + MATCH["pull"] * weather_value)
calm = max(0.0, 1 - abs(chart_value) / MATCH["balanced"])
keep = MATCH["keep_gain"] * calm * (MATCH["mild"] - abs(weather_value))
return moved + keep
def _hour_score(effect: dict[str, float]) -> float:
total = sum(MATCH["axis_share"][a] * effect[a] for a in AXES)
return _clamp(50 + MATCH["scale"] * total, 0, 100)
def best_window(scores: dict[int, float]) -> tuple[int, ...]:
"""06~21시 중 평균 점수가 가장 높은 연속 3시간(같으면 이른 쪽). 끝 시간이 처지면 2시간으로 줄인다."""
for size in (3, 2, 1):
windows = [tuple(range(s, s + size)) for s in DAY_HOURS if all(h in scores and h in DAY_HOURS for h in range(s, s + size))]
if windows:
break
else:
return ()
best = max(windows, key=lambda hs: (sum(scores[h] for h in hs) / len(hs), -hs[0]))
if len(best) == 3:
first, mid, last = (scores[h] for h in best)
if first < (mid + last) / 2 - MATCH["trim"]:
best = best[1:]
elif last < (first + mid) / 2 - MATCH["trim"]:
best = best[:2]
return best
def _weather_text(rows: list[HourWeather]) -> str:
feels = sum(r.feels_c for r in rows) / len(rows)
humidity = sum(r.humidity for r in rows) / len(rows)
rain = ", 비" if any(r.raining for r in rows) else ""
return f"체감 {feels:.0f}°, 습도 {humidity:.0f}%{rain}"
def _reasons(climate: ChartClimate, rows: list[HourWeather], matches: list[HourMatch]) -> tuple[dict, ...]:
mild = MATCH["mild"]
words = {"temp": ("warms", "cools"), "moist": ("moistens", "dries")}
out = []
for axis in AXES:
w = sum(m.weather[axis] for m in matches) / len(matches)
effect = sum(m.effect[axis] for m in matches) / len(matches)
up, down = words[axis]
out.append({
"axis": axis,
"need": climate.need[axis],
"effect": up if w > mild else down if w < -mild else "mild",
"helps": effect > 0,
"points": round(MATCH["scale"] * MATCH["axis_share"][axis] * effect, 1),
"weather": _weather_text(rows),
})
return tuple(out)
def climate_match(chart: Chart, weather: Iterable[HourWeather]) -> ClimateMatch:
"""시간별 날씨가 사주를 균형 쪽으로 옮기는지. 점수 50 이 보통, 높을수록 잘 맞는다."""
climate = chart_climate(chart)
rows = sorted(weather, key=lambda w: w.hour)
if not rows:
raise ValueError("시간별 날씨가 없습니다")
raw: dict[int, float] = {}
matches = []
for w in rows:
if not 0 <= w.hour <= 23 or w.hour in raw:
raise ValueError(f"시각은 0~23 에서 한 번씩: {w.hour}")
vec = weather_vector(w)
effect = {"temp": axis_effect(climate.temp, vec["temp"]), "moist": axis_effect(climate.moist, vec["moist"])}
raw[w.hour] = _hour_score(effect)
matches.append(HourMatch(w.hour, round(raw[w.hour]), vec, {a: round(v, 3) for a, v in effect.items()}))
day = [raw[h] for h in raw if h in DAY_HOURS] or list(raw.values())
best = best_window(raw)
picked = [m for m in matches if m.hour in best]
reasons = _reasons(climate, [w for w in rows if w.hour in best], picked) if best else ()
return ClimateMatch(climate, round(sum(day) / len(day)), tuple(matches), best, reasons)