Files
o2o-weather/backend/services/saju/pillars.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

113 lines
4.6 KiB
Python

"""사주 네 기둥. 연주는 입춘, 월주는 절입 시각(절대 시각)으로 가르고, 일주·시주는 지방평균시로 가른다."""
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta
from typing import Literal, Optional
from common.utils.kma_time import KST
from services.saju.birth import SEOUL_LON, SolarTime, check_date, to_solar_time
from services.saju.ganji import BRANCHES, STEMS, ganji, ko
from services.saju.solar_terms import Jeol, jeol_around, jeol_of_year
# 자시 처리. midnight: 지방평균시 0시에 날이 바뀌고 23~24시는 그날의 자시(야자시).
# 23h: 23시에 다음 날로 넘어간다. 두 방식 모두 23~01시 시주는 다음 날 자시 간지(甲일 밤 23시 → 丙子)로 같다
ZiRule = Literal["midnight", "23h"]
_DAY_ZERO = date(1900, 1, 1) # 甲戌일
_DAY_ZERO_INDEX = 10
_TIME_UNKNOWN_AT = time(12) # 시간을 모를 때 연·월주를 가를 기준 시각 (KST)
@dataclass(frozen=True)
class Pillar:
stem: str
branch: str
@property
def name(self) -> str:
return self.stem + self.branch
@property
def ko(self) -> str:
return ko(self.name)
@dataclass(frozen=True)
class Chart:
year: Pillar
month: Pillar
day: Pillar
hour: Optional[Pillar] # 태어난 시간을 모르면 None
birth_date: date
birth_time: Optional[time]
longitude: float
zi_rule: ZiRule
solar: Optional[SolarTime] # 시간 보정 내역 (시간 모르면 None)
jeol: Jeol # 월주를 정한 절 (직전 절입)
next_jeol: Jeol
jeol_on_birth_day: bool # 시간을 모르는데 그날 절이 들어 연·월주가 갈릴 수 있음
@property
def hour_known(self) -> bool:
return self.hour is not None
@property
def day_stem(self) -> str:
return self.day.stem
def pillars(self) -> dict[str, Pillar]:
"""알고 있는 기둥만 연·월·일·시 순으로."""
all_ = {"year": self.year, "month": self.month, "day": self.day, "hour": self.hour}
return {k: v for k, v in all_.items() if v is not None}
def day_pillar(d: date) -> Pillar:
"""그날 일진. 1900-01-01 甲戌부터 60일 주기."""
name = ganji(_DAY_ZERO_INDEX + (d - _DAY_ZERO).days)
return Pillar(name[0], name[1])
def year_pillar(saju_year: int) -> Pillar:
name = ganji(saju_year - 4)
return Pillar(name[0], name[1])
def month_pillar(year_stem: str, month_branch: str) -> Pillar:
"""연간으로 寅월 천간을 정한다 (甲己→丙寅, 乙庚→戊寅, 丙辛→庚寅, 丁壬→壬寅, 戊癸→甲寅)."""
first = STEMS.index(year_stem) % 5 * 2 + 2
offset = (BRANCHES.index(month_branch) - 2) % 12
return Pillar(STEMS[(first + offset) % 10], month_branch)
def hour_pillar(local_mean: datetime) -> Pillar:
"""시지는 23시부터 두 시간씩. 시간은 23시에 다음 날 자시로 이어지므로 시간을 그 다음 날 일간으로 정한다 (甲己→甲子)."""
shifted = local_mean + timedelta(hours=1)
branch = shifted.hour // 2
first = STEMS.index(day_pillar(shifted.date()).stem) % 5 * 2
return Pillar(STEMS[(first + branch) % 10], BRANCHES[branch])
def saju_year_of(at: datetime) -> int:
"""입춘 전이면 전해."""
ipchun = next(j for j in jeol_of_year(at.year) if j.name == "입춘")
return at.year if at >= ipchun.at else at.year - 1
def make_chart(birth_date: date, birth_time: Optional[time] = None, longitude: float = SEOUL_LON, zi_rule: ZiRule = "midnight") -> Chart:
"""양력 생년월일(시)로 사주를 세운다. 시간은 태어난 곳 시계 시각 그대로 넣는다 (서머타임·표준시 변경은 여기서 걷어냄)."""
check_date(birth_date)
if zi_rule not in ("midnight", "23h"):
raise ValueError(f"자시 규칙은 midnight 또는 23h: {zi_rule}")
solar = to_solar_time(birth_date, birth_time, longitude) if birth_time is not None else None
at = solar.utc.astimezone(KST) if solar else datetime.combine(birth_date, _TIME_UNKNOWN_AT, tzinfo=KST)
jeol, next_jeol = jeol_around(at)
year = year_pillar(saju_year_of(at))
month = month_pillar(year.stem, jeol.month_branch)
if solar:
day_date = (solar.local_mean + timedelta(hours=1 if zi_rule == "23h" else 0)).date()
hour = hour_pillar(solar.local_mean)
else:
day_date, hour = birth_date, None
on_term_day = solar is None and birth_date in (jeol.at.date(), next_jeol.at.date())
return Chart(year, month, day_pillar(day_date), hour, birth_date, birth_time, longitude, zi_rule, solar, jeol, next_jeol, on_term_day)