Merge remote-tracking branch 'origin/main' into feat/weather-game
# Conflicts: # shared/api/client/@tanstack/react-query.gen.ts # shared/api/client/index.ts # shared/api/client/sdk.gen.ts # shared/api/client/types.gen.ts
This commit is contained in:
commit
9e7bd54c7e
48 files changed
+3253
-189
No files matched your search
@@ -26,6 +26,7 @@ class ErrorType(Enum):
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
TERMS_REQUIRED = 4005
|
||||
LEVEL_REQUIRED = 4006 # 계정 레벨이 모자라 아직 열리지 않음
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
|
||||
@@ -26,13 +26,6 @@ class CardCRUD:
|
||||
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
|
||||
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
|
||||
|
||||
async def latest_published(self, s: AsyncSession, template: str) -> Optional[CardSet]:
|
||||
"""그 틀로 가장 최근에 피드에 올린 카드뉴스"""
|
||||
return await s.scalar(
|
||||
select(CardSet).where(CardSet.template == template, CardSet.status == CardStatus.PUBLISHED.value, CardSet.post_id.is_not(None))
|
||||
.order_by(CardSet.published_at.desc()).limit(1)
|
||||
)
|
||||
|
||||
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
|
||||
if not card_ids:
|
||||
return []
|
||||
|
||||
@@ -16,6 +16,7 @@ from router.v1.index.index import router as index_router
|
||||
from router.v1.my_gak.my_gak import router as my_gak_router
|
||||
from router.v1.fortune.fortune import router as fortune_router
|
||||
from router.v1.level.level import router as level_router
|
||||
from router.v1.saju.saju import router as saju_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
@@ -52,6 +53,7 @@ app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(fortune_router)
|
||||
app.include_router(level_router)
|
||||
app.include_router(saju_router)
|
||||
app.include_router(talk_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
|
||||
@@ -14,7 +14,7 @@ from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.card_crud import CardCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList, Res_LatestCard
|
||||
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList
|
||||
from services.bot_comment import fill_bot_comments
|
||||
from services.external import instagram
|
||||
from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day
|
||||
@@ -82,16 +82,6 @@ async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList:
|
||||
])
|
||||
|
||||
|
||||
@router.get("/latest", response_model=Res_LatestCard, response_model_exclude_none=True, summary="그 틀로 가장 최근에 피드에 올린 카드뉴스의 포스트 (오늘 탭 '오늘 코디' 아이콘)")
|
||||
async def latest_card(template: str = Query(..., pattern=r"^[a-z_]{1,20}$")) -> Res_LatestCard:
|
||||
err, card = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.latest_published(s, template))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_LatestCard(result=error_info(err))
|
||||
if card is None:
|
||||
return Res_LatestCard()
|
||||
return Res_LatestCard(post_id=card.post_id, published_at=card.published_at.astimezone(KST) if card.published_at else None)
|
||||
|
||||
|
||||
@router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)])
|
||||
async def create_card(req: Req_CardCreate) -> Res_Card:
|
||||
images = _jpegs(req.images)
|
||||
|
||||
@@ -18,11 +18,6 @@ class Req_CardCreate(WebPacketProtocol):
|
||||
publish: bool = Field(default=False, description="true 면 만들자마자 그날 피드에 올린다. false 면 승인 대기")
|
||||
|
||||
|
||||
class Res_LatestCard(Res_WebPacketProtocol):
|
||||
post_id: Optional[int] = None
|
||||
published_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class Res_Card(Res_WebPacketProtocol):
|
||||
card_id: Optional[int] = None
|
||||
status: Optional[CardStatus] = None
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,134 @@
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Req_Saju(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
birth_date: date = Field(description="양력 생년월일 (1900-01-01 ~ 오늘)")
|
||||
birth_time: Optional[str] = Field(None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$", description="태어난 시각 HH:MM (모르면 없음)")
|
||||
longitude: float = Field(126.98, ge=124, le=132, description="태어난 곳 경도 (시각 보정)")
|
||||
gender: Optional[Literal["male", "female"]] = Field(None, description="연애운에서 이성 기운을 볼 때만")
|
||||
|
||||
|
||||
class SajuPillar(WebPacketProtocol):
|
||||
position: str = Field(description="year·month·day·hour")
|
||||
stem: str
|
||||
branch: str
|
||||
stem_ko: str
|
||||
branch_ko: str
|
||||
stem_element: str = Field(description="木火土金水")
|
||||
branch_element: str
|
||||
|
||||
|
||||
class SajuMe(WebPacketProtocol):
|
||||
pillars: list[SajuPillar]
|
||||
hour_known: bool
|
||||
jeol_warning: bool = Field(description="시각을 모르는데 태어난 날 절이 들어 연·월주가 갈릴 수 있음")
|
||||
scene: str = Field(description="내 기운 이름 (예: 봄비 기운)")
|
||||
scene_desc: str
|
||||
scene_icon: str
|
||||
season: Optional[str] = None
|
||||
climate: Optional[str] = Field(None, description="따뜻·마름 / 따뜻·촉촉 / 서늘·마름 / 서늘·촉촉")
|
||||
need: list[str] = Field([], description="내 기운에 필요한 것 (따뜻함·마른 공기 등)")
|
||||
|
||||
|
||||
class SajuCard(WebPacketProtocol):
|
||||
kind: str = Field(description="when·do·avoid·good·wear")
|
||||
title: str
|
||||
body: str
|
||||
sub: Optional[str] = None
|
||||
|
||||
|
||||
class SajuToday(WebPacketProtocol):
|
||||
day: date
|
||||
pillar: str = Field(description="오늘 간지 한글 (을해)")
|
||||
ten_god: str
|
||||
title: str
|
||||
score: int = Field(description="오늘 점수 = 사주 + 날씨 궁합")
|
||||
saju_score: int
|
||||
weather_points: Optional[int] = Field(None, description="날씨 궁합이 더하거나 뺀 점수")
|
||||
why: list[str] = Field([], description="점수에 크게 작용한 사실")
|
||||
cards: list[SajuCard]
|
||||
|
||||
|
||||
class SajuDay(WebPacketProtocol):
|
||||
day: date
|
||||
weekday: str
|
||||
icon: Optional[str] = None
|
||||
word: Optional[str] = None
|
||||
temp_min: Optional[int] = None
|
||||
temp_max: Optional[int] = None
|
||||
score: int
|
||||
title: str
|
||||
best: bool = False
|
||||
|
||||
|
||||
class SajuLoveDay(WebPacketProtocol):
|
||||
day: date
|
||||
weekday: str
|
||||
icon: Optional[str] = None
|
||||
word: Optional[str] = None
|
||||
temp_max: Optional[int] = None
|
||||
body: str
|
||||
why: str
|
||||
|
||||
|
||||
class SajuLove(WebPacketProtocol):
|
||||
good: Optional[SajuLoveDay] = None
|
||||
caution: Optional[SajuLoveDay] = None
|
||||
gender_known: bool
|
||||
|
||||
|
||||
class SajuPeriod(WebPacketProtocol):
|
||||
label: str = Field(description="이달 · 10/8 한로 ~ 11/7 / 2026년")
|
||||
pillar: str
|
||||
ten_god: str
|
||||
title: str
|
||||
body: str
|
||||
notes: list[str] = []
|
||||
months: list[int] = Field([], description="올해: 잘 맞는 달 (양력 달)")
|
||||
|
||||
|
||||
class SajuLock(WebPacketProtocol):
|
||||
key: str
|
||||
name: str
|
||||
level: int
|
||||
unlocked: bool
|
||||
|
||||
|
||||
class Res_Saju(Res_WebPacketProtocol):
|
||||
me: Optional[SajuMe] = None
|
||||
today: Optional[SajuToday] = None
|
||||
week: Optional[list[SajuDay]] = Field(None, description="레벨 2부터")
|
||||
money: Optional[list[str]] = Field(None, description="레벨 3부터: 이번 주 돈을 정할 날·피할 날")
|
||||
work: Optional[list[str]] = None
|
||||
love: Optional[SajuLove] = Field(None, description="레벨 4부터")
|
||||
month: Optional[SajuPeriod] = Field(None, description="레벨 6부터")
|
||||
year: Optional[SajuPeriod] = Field(None, description="레벨 7부터")
|
||||
level: int = 1
|
||||
logged_in: bool = False
|
||||
locks: list[SajuLock] = []
|
||||
|
||||
|
||||
class SajuBirth(WebPacketProtocol):
|
||||
birth_date: date
|
||||
birth_time: Optional[str] = Field(None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
|
||||
longitude: float = Field(126.98, ge=124, le=132)
|
||||
|
||||
|
||||
class Req_SajuMatch(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
me: SajuBirth
|
||||
friend: SajuBirth
|
||||
|
||||
|
||||
class Res_SajuMatch(Res_WebPacketProtocol):
|
||||
score: Optional[int] = None
|
||||
title: Optional[str] = None
|
||||
lines: list[str] = []
|
||||
friend_scene: Optional[str] = Field(None, description="친구의 기운 이름")
|
||||
day: Optional[SajuDay] = Field(None, description="이번 주 둘 다 좋은 날")
|
||||
@@ -0,0 +1,73 @@
|
||||
from datetime import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.saju.protocol import Req_Saju, Req_SajuMatch, Res_Saju, Res_SajuMatch, SajuBirth, SajuCard, SajuDay, SajuLock, SajuLove, SajuLoveDay, SajuMe, SajuPeriod, SajuPillar, SajuToday
|
||||
from services import saju_text as T
|
||||
from services.level_service import UNLOCKS
|
||||
from services.saju.ganji import branch_element, ko, stem_element
|
||||
from services.saju_service import Reading, SajuService, shown_saju, weather_points
|
||||
|
||||
router = APIRouter(prefix="/v1/saju", tags=["saju"])
|
||||
_WEEKDAY = "월화수목금토일"
|
||||
|
||||
|
||||
def _res(r: Reading) -> Res_Saju:
|
||||
c = r.chart
|
||||
pillars = [("year", c.year), ("month", c.month), ("day", c.day)] + ([("hour", c.hour)] if c.hour else [])
|
||||
today = r.today
|
||||
best = max(r.week, key=lambda d: d.score).day if r.week else None
|
||||
return Res_Saju(
|
||||
me=SajuMe(
|
||||
pillars=[SajuPillar(position=pos, stem=p.stem, branch=p.branch, stem_ko=ko(p.stem), branch_ko=ko(p.branch), stem_element=stem_element(p.stem), branch_element=branch_element(p.branch)) for pos, p in pillars],
|
||||
hour_known=c.hour is not None, jeol_warning=c.jeol_on_birth_day, scene=r.scene[0], scene_desc=r.scene[1], scene_icon=r.scene_icon, need=r.need,
|
||||
),
|
||||
today=SajuToday(
|
||||
day=today.day, pillar=ko(today.facts.pillar.stem + today.facts.pillar.branch), ten_god=today.facts.stem_ten_god, title=T.TEN_GOD_TEXT[today.facts.stem_ten_god][0],
|
||||
score=today.score, saju_score=shown_saju(today.facts.score), weather_points=weather_points(today.climate_score),
|
||||
why=r.why, cards=[SajuCard(**x.__dict__) for x in r.cards],
|
||||
),
|
||||
week=[
|
||||
SajuDay(day=d.day, weekday=_WEEKDAY[d.day.weekday()], icon=d.weather.icon if d.weather else None, word=d.weather.word if d.weather else None,
|
||||
temp_min=d.weather.temp_min if d.weather else None, temp_max=d.weather.temp_max if d.weather else None,
|
||||
score=d.score, title=T.TEN_GOD_TEXT[d.facts.stem_ten_god][0], best=d.day == best)
|
||||
for d in r.week
|
||||
] if r.week else None,
|
||||
money=r.money, work=r.work,
|
||||
love=SajuLove(good=SajuLoveDay(**r.love["good"]) if r.love.get("good") else None, caution=SajuLoveDay(**r.love["caution"]) if r.love.get("caution") else None,
|
||||
gender_known=r.love.get("gender") is not None) if r.love else None,
|
||||
month=SajuPeriod(label=f"이달 · {r.month['from']:%-m/%-d} {r.month['jeol']} ~ {r.month['until']:%-m/%-d}", **{k: r.month[k] for k in ("pillar", "ten_god", "title", "body", "notes")}) if r.month else None,
|
||||
year=SajuPeriod(label=f"{r.year['year']}년" + (" 미리 보기" if r.year["preview"] else ""), months=r.year["months"], **{k: r.year[k] for k in ("pillar", "ten_god", "title", "body", "notes")}) if r.year else None,
|
||||
level=r.level, logged_in=r.logged_in,
|
||||
locks=[SajuLock(key=k, name=n, level=lv, unlocked=r.logged_in and r.level >= lv) for lv, items in UNLOCKS.items() for k, n in items],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reading", response_model=Res_Saju, response_model_exclude_none=True, summary="날씨 사주: 내 기운, 오늘 점수(사주+날씨 궁합)와 할 일, 레벨로 열리는 이번 주·금전·연애·이달·올해. 생년월일은 저장하지 않는다")
|
||||
async def reading(req: Req_Saju, user: Optional[User] = Depends(optional_user), service: SajuService = Depends()) -> Res_Saju:
|
||||
t = time(*map(int, req.birth_time.split(":"))) if req.birth_time else None
|
||||
err, r = await service.reading(req.birth_date, t, req.longitude, req.gender, req.region_code, user)
|
||||
return Res_Saju(result=error_info(err)) if err is not ErrorType.SUCCESS or r is None else _res(r)
|
||||
|
||||
|
||||
def _birth(b: SajuBirth) -> tuple:
|
||||
return b.birth_date, time(*map(int, b.birth_time.split(":"))) if b.birth_time else None, b.longitude
|
||||
|
||||
|
||||
@router.post("/match", response_model=Res_SajuMatch, response_model_exclude_none=True, summary="궁합 (계정 레벨 5부터): 일간·일지·기운으로 본 사이, 이번 주 둘 다 좋은 날. 생년월일은 저장하지 않는다")
|
||||
async def match(req: Req_SajuMatch, user: Optional[User] = Depends(optional_user), service: SajuService = Depends()) -> Res_SajuMatch:
|
||||
err, m = await service.match(_birth(req.me), _birth(req.friend), req.region_code, user)
|
||||
if err is not ErrorType.SUCCESS or m is None:
|
||||
return Res_SajuMatch(result=error_info(err))
|
||||
d = m.day
|
||||
return Res_SajuMatch(
|
||||
score=m.score, title=m.title, lines=m.lines, friend_scene=m.friend_scene,
|
||||
day=SajuDay(day=d.day, weekday=_WEEKDAY[d.day.weekday()], icon=d.weather.icon if d.weather else None, word=d.weather.word if d.weather else None,
|
||||
temp_min=d.weather.temp_min if d.weather else None, temp_max=d.weather.temp_max if d.weather else None, score=d.score,
|
||||
title=T.TEN_GOD_TEXT[d.facts.stem_ten_god][0], best=True) if d else None,
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,80 @@
|
||||
"""태어난 시계 시각 → 지방평균시. 그때 한국 표준시(UTC 오프셋)와 서머타임을 걷어낸 뒤 출생지 경도로 맞춘다. 균시차는 넣지 않는다.
|
||||
|
||||
출처 (표준시·서머타임 모두 같은 표, 두 곳이 일치):
|
||||
- IANA tz database `asia` 파일 Rule ROK · Zone Asia/Seoul — https://github.com/eggert/tz/blob/main/asia
|
||||
(서머타임 끝 날짜 근거로 국가기록원 관보 1955~1960, 1948·1988 시작은 당시 신문 확인 기록이 주석에 있다)
|
||||
- 위키백과 '한국 표준시' 일광 절약 시간제 표 — https://ko.wikipedia.org/wiki/한국_표준시
|
||||
(표준시 변경 근거: 1908 칙령 제5호, 1912 조선총독부 고시 제338호, 1954 대통령령 제876호, 1961 법률 제676호)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
SEOUL_LON = 126.978 # 서울시청
|
||||
MIN_DATE, MAX_DATE = date(1900, 1, 1), date(2100, 12, 31)
|
||||
|
||||
# 표준시 오프셋(분)과 그 오프셋이 시작된 현지 시계 시각. 1908-04-01 전은 지방시를 썼다고 본다
|
||||
_STANDARD: tuple[tuple[datetime, int], ...] = (
|
||||
(datetime(1908, 4, 1), 510), # UTC+8:30 (동경 127.5°)
|
||||
(datetime(1912, 1, 1), 540), # UTC+9
|
||||
(datetime(1954, 3, 21), 510),
|
||||
(datetime(1961, 8, 10), 540),
|
||||
)
|
||||
|
||||
# 서머타임(+1시간) 현지 시계 구간 [시작, 끝). 시작은 표준시 시계, 끝은 서머타임 시계 기준.
|
||||
# 끝나기 직전 한 시간은 두 번 지나가는데 서머타임 쪽(먼저 지나간 시각)으로 본다.
|
||||
DST_PERIODS: tuple[tuple[datetime, datetime], ...] = (
|
||||
(datetime(1948, 6, 1, 0), datetime(1948, 9, 13, 0)),
|
||||
(datetime(1949, 4, 3, 0), datetime(1949, 9, 11, 0)),
|
||||
(datetime(1950, 4, 1, 0), datetime(1950, 9, 10, 0)),
|
||||
(datetime(1951, 5, 6, 0), datetime(1951, 9, 9, 0)),
|
||||
(datetime(1955, 5, 5, 0), datetime(1955, 9, 9, 0)),
|
||||
(datetime(1956, 5, 20, 0), datetime(1956, 9, 30, 0)),
|
||||
(datetime(1957, 5, 5, 0), datetime(1957, 9, 22, 0)),
|
||||
(datetime(1958, 5, 4, 0), datetime(1958, 9, 21, 0)),
|
||||
(datetime(1959, 5, 3, 0), datetime(1959, 9, 20, 0)),
|
||||
(datetime(1960, 5, 1, 0), datetime(1960, 9, 18, 0)),
|
||||
(datetime(1987, 5, 10, 2), datetime(1987, 10, 11, 3)),
|
||||
(datetime(1988, 5, 8, 2), datetime(1988, 10, 9, 3)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SolarTime:
|
||||
clock: datetime # 입력한 시계 시각
|
||||
utc: datetime
|
||||
local_mean: datetime # 출생지 지방평균시 (tz 없음)
|
||||
utc_offset_min: int # 그때 시계의 UTC 오프셋 (서머타임 포함, 1908년 전은 출생지 지방시)
|
||||
dst: bool
|
||||
correction_min: float # local_mean − clock (분)
|
||||
|
||||
|
||||
def check_date(d: date) -> None:
|
||||
if not MIN_DATE <= d <= MAX_DATE:
|
||||
raise ValueError(f"1900~2100년만 계산합니다: {d}")
|
||||
|
||||
|
||||
def is_dst(clock: datetime) -> bool:
|
||||
return any(start <= clock < end for start, end in DST_PERIODS)
|
||||
|
||||
|
||||
def standard_offset_min(clock: datetime, longitude: float) -> float:
|
||||
"""그때 한국 표준시 UTC 오프셋(분). 1908-04-01 전은 출생지 지방시."""
|
||||
offset = longitude * 4
|
||||
for start, minutes in _STANDARD:
|
||||
if clock >= start:
|
||||
offset = minutes
|
||||
return offset
|
||||
|
||||
|
||||
def to_solar_time(d: date, t: time, longitude: float = SEOUL_LON) -> SolarTime:
|
||||
"""시계 시각을 지방평균시로. 평소(UTC+9)엔 (경도 − 135) × 4분, 서울은 약 −32분."""
|
||||
check_date(d)
|
||||
if not -180 <= longitude <= 180:
|
||||
raise ValueError(f"경도가 이상합니다: {longitude}")
|
||||
clock = datetime.combine(d, t.replace(tzinfo=None))
|
||||
dst = is_dst(clock)
|
||||
offset = standard_offset_min(clock, longitude) + (60 if dst else 0)
|
||||
utc = (clock - timedelta(minutes=offset)).replace(tzinfo=timezone.utc)
|
||||
local_mean = utc.replace(tzinfo=None) + timedelta(minutes=longitude * 4)
|
||||
return SolarTime(clock, utc, local_mean, round(offset), dst, (local_mean - clock).total_seconds() / 60)
|
||||
@@ -0,0 +1,192 @@
|
||||
"""조후(한난조습): 내 사주의 차고 더움·마르고 젖음과 오늘 날씨가 잘 맞는지."""
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""오늘 일진과 내 사주가 만나는 사실들, 연애 기운, 사주 점수."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
|
||||
from services.saju.ganji import main_stem
|
||||
from services.saju.pillars import Chart, Pillar, day_pillar
|
||||
from services.saju.rules import (
|
||||
OFFICER, PALACE, WEALTH, Relation, branch_relations, branch_ten_god, dohwa_of, hongyeom_of, stem_relations, ten_god,
|
||||
triple_relations,
|
||||
)
|
||||
|
||||
# 사주 점수 가중치 (초안, 주인이 조정). 50 에서 시작해 사실마다 더하고 0~100 으로 자른다. 용신은 보지 않는다
|
||||
SCORE_WEIGHTS = {
|
||||
"base": 50,
|
||||
# 오늘 천간의 십성
|
||||
"ten_god": {"비견": 2, "겁재": -2, "식신": 4, "상관": -2, "편재": 3, "정재": 4, "편관": -4, "정관": 3, "편인": -1, "정인": 4},
|
||||
"branch_ten_god_share": 0.5, # 오늘 지지(정기) 십성은 천간 점수의 이 비율
|
||||
"relation": {
|
||||
"천간합": 4, "천간충": -5, "육합": 5, "삼합": 6, "반합": 3, "충": -6, "형": -4, "삼형": -6, "자형": -2, "파": -2, "해": -2, "원진": -3,
|
||||
},
|
||||
"position_share": {"year": 0.8, "month": 1.0, "day": 1.5, "hour": 0.8}, # 관계 점수에 곱함. 삼합·삼형은 1
|
||||
"도화": 3,
|
||||
"홍염": 2,
|
||||
}
|
||||
|
||||
Gender = Literal["male", "female"]
|
||||
LOVE_DAY_RELATIONS = ("육합", "반합", "충", "형", "자형", "원진")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Interaction:
|
||||
position: str # year·month·day·hour (삼합·삼형은 묶인 자리 중 첫 자리)
|
||||
palace: str
|
||||
part: str # stem·branch
|
||||
relation: Relation
|
||||
positions: tuple[str, ...] = () # 삼합·삼형에 묶인 원국 자리 전부
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LoveFacts:
|
||||
relevant: bool
|
||||
gender: Optional[Gender]
|
||||
reasons: tuple[dict, ...] # {"kind": 재성|관성|도화|홍염|일지, ...}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Contribution:
|
||||
fact: str # 십성 이름, 관계 이름, 도화, 홍염
|
||||
chars: str
|
||||
position: Optional[str]
|
||||
points: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DailyFacts:
|
||||
day: date
|
||||
pillar: Pillar
|
||||
stem_ten_god: str
|
||||
branch_main_stem: str
|
||||
branch_ten_god: str
|
||||
interactions: tuple[Interaction, ...]
|
||||
dohwa: tuple[dict, ...] # 오늘 지지가 도화일 때 {"basis": "year"|"day", "branch": 도화 지지}
|
||||
hongyeom: bool
|
||||
love: LoveFacts
|
||||
score: int
|
||||
contributions: tuple[Contribution, ...]
|
||||
|
||||
|
||||
def interactions(chart: Chart, today: Pillar) -> list[Interaction]:
|
||||
"""오늘 천간·지지와 원국 각 기둥의 합·충·형·파·해·원진. 오늘 글자가 있어야 완성되는 삼합·삼형도 넣는다."""
|
||||
pillars = chart.pillars()
|
||||
out = []
|
||||
for pos, p in pillars.items():
|
||||
out += [Interaction(pos, PALACE[pos], "stem", r) for r in stem_relations(today.stem, p.stem)]
|
||||
out += [Interaction(pos, PALACE[pos], "branch", r) for r in branch_relations(today.branch, p.branch)]
|
||||
natal = [p.branch for p in pillars.values()]
|
||||
already = {r.group for r in triple_relations(natal)}
|
||||
for r in triple_relations(natal + [today.branch]):
|
||||
if today.branch in r.group and r.group not in already:
|
||||
joined = tuple(pos for pos, p in pillars.items() if p.branch in r.group)
|
||||
out.append(Interaction(joined[0], PALACE[joined[0]], "branch", r, joined))
|
||||
return out
|
||||
|
||||
|
||||
def dohwa_hits(chart: Chart, branch: str) -> list[dict]:
|
||||
return [{"basis": basis, "branch": branch} for basis, p in (("year", chart.year), ("day", chart.day)) if dohwa_of(p.branch) == branch]
|
||||
|
||||
|
||||
def love_facts(chart: Chart, today: Pillar, gender: Optional[Gender] = None) -> LoveFacts:
|
||||
"""남자는 재성, 여자는 관성 날. 성별을 모르면 도화·홍염·일지 관계만."""
|
||||
if gender not in (None, "male", "female"):
|
||||
raise ValueError(f"성별은 male·female·None: {gender}")
|
||||
reasons: list[dict] = []
|
||||
stars, label = {"male": (WEALTH, "재성"), "female": (OFFICER, "관성")}.get(gender or "", ((), ""))
|
||||
for part, god in (("stem", ten_god(chart.day_stem, today.stem)), ("branch", branch_ten_god(chart.day_stem, today.branch))):
|
||||
if god in stars:
|
||||
reasons.append({"kind": label, "part": part, "ten_god": god})
|
||||
reasons += [{"kind": "도화", **hit} for hit in dohwa_hits(chart, today.branch)]
|
||||
if hongyeom_of(chart.day_stem) == today.branch:
|
||||
reasons.append({"kind": "홍염", "branch": today.branch})
|
||||
for r in branch_relations(today.branch, chart.day.branch):
|
||||
if r.kind in LOVE_DAY_RELATIONS:
|
||||
reasons.append({"kind": "일지", "relation": r.kind, "chars": r.chars})
|
||||
return LoveFacts(bool(reasons), gender, tuple(reasons))
|
||||
|
||||
|
||||
def score(chart: Chart, today: Pillar, found: list[Interaction], dohwa: list[dict], hongyeom: bool) -> tuple[int, list[Contribution]]:
|
||||
"""사주 점수와 사실별 점수. 삼합·삼형이 완성되면 같은 묶음의 반합·형은 겹쳐 세지 않는다."""
|
||||
w = SCORE_WEIGHTS
|
||||
stem_god, branch_god = ten_god(chart.day_stem, today.stem), branch_ten_god(chart.day_stem, today.branch)
|
||||
parts = [
|
||||
Contribution(stem_god, today.stem, None, w["ten_god"][stem_god]),
|
||||
Contribution(branch_god, today.branch, None, w["ten_god"][branch_god] * w["branch_ten_god_share"]),
|
||||
]
|
||||
triples = {(i.relation.kind, i.relation.group) for i in found if i.positions}
|
||||
absorbed = {("반합", g) for k, g in triples if k == "삼합"} | {("형", g) for k, g in triples if k == "삼형"}
|
||||
for i in found:
|
||||
r = i.relation
|
||||
if (r.kind, r.group) in absorbed:
|
||||
continue
|
||||
share = 1.0 if i.positions else w["position_share"][i.position]
|
||||
parts.append(Contribution(r.kind, r.chars, i.position, w["relation"][r.kind] * share))
|
||||
parts += [Contribution("도화", hit["branch"], hit["basis"], w["도화"]) for hit in dohwa]
|
||||
if hongyeom:
|
||||
parts.append(Contribution("홍염", today.branch, None, w["홍염"]))
|
||||
parts = [Contribution(c.fact, c.chars, c.position, round(c.points, 2)) for c in parts]
|
||||
total = w["base"] + sum(c.points for c in parts)
|
||||
return round(max(0, min(100, total))), parts
|
||||
|
||||
|
||||
def daily_facts(chart: Chart, day: date, gender: Optional[Gender] = None) -> DailyFacts:
|
||||
today = day_pillar(day)
|
||||
found = interactions(chart, today)
|
||||
dohwa = dohwa_hits(chart, today.branch)
|
||||
hongyeom = hongyeom_of(chart.day_stem) == today.branch
|
||||
total, parts = score(chart, today, found, dohwa, hongyeom)
|
||||
return DailyFacts(
|
||||
day=day,
|
||||
pillar=today,
|
||||
stem_ten_god=ten_god(chart.day_stem, today.stem),
|
||||
branch_main_stem=main_stem(today.branch),
|
||||
branch_ten_god=branch_ten_god(chart.day_stem, today.branch),
|
||||
interactions=tuple(found),
|
||||
dohwa=tuple(dohwa),
|
||||
hongyeom=hongyeom,
|
||||
love=love_facts(chart, today, gender),
|
||||
score=total,
|
||||
contributions=tuple(parts),
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""천간·지지 기본표. 글자는 한자 한 글자로 다루고, 화면용 한글 이름은 KO 로 바꾼다."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
STEMS = "甲乙丙丁戊己庚辛壬癸"
|
||||
BRANCHES = "子丑寅卯辰巳午未申酉戌亥"
|
||||
ELEMENTS = "木火土金水"
|
||||
|
||||
KO = dict(zip(STEMS + BRANCHES + ELEMENTS, "갑을병정무기경신임계" + "자축인묘진사오미신유술해" + "목화토금수"))
|
||||
|
||||
BRANCH_ELEMENT = dict(zip(BRANCHES, "水土木木土火火土金金土水"))
|
||||
|
||||
# 지장간 (여기, 중기, 정기). 중기가 없는 왕지는 None. 국내에서 흔히 쓰는 표
|
||||
HIDDEN_STEMS: dict[str, tuple[str, Optional[str], str]] = {
|
||||
"子": ("壬", None, "癸"),
|
||||
"丑": ("癸", "辛", "己"),
|
||||
"寅": ("戊", "丙", "甲"),
|
||||
"卯": ("甲", None, "乙"),
|
||||
"辰": ("乙", "癸", "戊"),
|
||||
"巳": ("戊", "庚", "丙"),
|
||||
"午": ("丙", "己", "丁"),
|
||||
"未": ("丁", "乙", "己"),
|
||||
"申": ("戊", "壬", "庚"),
|
||||
"酉": ("庚", None, "辛"),
|
||||
"戌": ("辛", "丁", "戊"),
|
||||
"亥": ("戊", "甲", "壬"),
|
||||
}
|
||||
|
||||
|
||||
def stem_element(stem: str) -> str:
|
||||
return ELEMENTS[STEMS.index(stem) // 2]
|
||||
|
||||
|
||||
def stem_yang(stem: str) -> bool:
|
||||
return STEMS.index(stem) % 2 == 0
|
||||
|
||||
|
||||
def branch_element(branch: str) -> str:
|
||||
return BRANCH_ELEMENT[branch]
|
||||
|
||||
|
||||
def branch_yang(branch: str) -> bool:
|
||||
"""자리(체) 기준 음양. 子는 양, 亥는 음. 십성은 정기로 따로 본다."""
|
||||
return BRANCHES.index(branch) % 2 == 0
|
||||
|
||||
|
||||
def main_stem(branch: str) -> str:
|
||||
"""지지의 정기."""
|
||||
return HIDDEN_STEMS[branch][2]
|
||||
|
||||
|
||||
def ganji(index: int) -> str:
|
||||
"""60갑자 순번(甲子=0)을 '甲子' 두 글자로."""
|
||||
return STEMS[index % 10] + BRANCHES[index % 12]
|
||||
|
||||
|
||||
def ko(chars: str) -> str:
|
||||
return "".join(KO.get(c, c) for c in chars)
|
||||
@@ -0,0 +1,112 @@
|
||||
"""사주 네 기둥. 연주는 입춘, 월주는 절입 시각(절대 시각)으로 가르고, 일주·시주는 지방평균시로 가른다."""
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""명리 규칙. 문장이 아니라 구조화된 사실만 돌려준다."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from itertools import combinations
|
||||
from typing import Optional
|
||||
|
||||
from services.saju.ganji import ELEMENTS, main_stem, stem_element, stem_yang
|
||||
|
||||
# 궁: 기둥 자리의 뜻
|
||||
PALACE = {"year": "조상·사회", "month": "부모·직장", "day": "나·배우자", "hour": "자녀·미래"}
|
||||
|
||||
# 일간 기준 관계(같은 오행, 내가 낳음, 내가 극함, 나를 극함, 나를 낳음) × (음양 같음, 다름)
|
||||
_TEN_GODS = (("비견", "겁재"), ("식신", "상관"), ("편재", "정재"), ("편관", "정관"), ("편인", "정인"))
|
||||
WEALTH = ("편재", "정재")
|
||||
OFFICER = ("편관", "정관")
|
||||
|
||||
STEM_HAP = {"甲己": "土", "乙庚": "金", "丙辛": "水", "丁壬": "木", "戊癸": "火"}
|
||||
STEM_CHUNG = ("甲庚", "乙辛", "丙壬", "丁癸")
|
||||
|
||||
YUKHAP = {"子丑": "土", "寅亥": "木", "卯戌": "火", "辰酉": "金", "巳申": "水", "午未": "火"}
|
||||
SAMHAP = {"申子辰": "水", "亥卯未": "木", "寅午戌": "火", "巳酉丑": "金"} # 생지·왕지·묘지 순
|
||||
CHUNG = ("子午", "丑未", "寅申", "卯酉", "辰戌", "巳亥")
|
||||
HYEONG = {"寅巳": "寅巳申", "巳申": "寅巳申", "申寅": "寅巳申", "丑戌": "丑戌未", "戌未": "丑戌未", "未丑": "丑戌未", "子卯": "子卯"}
|
||||
SAMHYEONG = ("寅巳申", "丑戌未")
|
||||
JAHYEONG = "辰午酉亥"
|
||||
PA = ("子酉", "丑辰", "寅亥", "卯午", "巳申", "未戌")
|
||||
HAE = ("子未", "丑午", "寅巳", "卯辰", "申亥", "酉戌")
|
||||
WONJIN = ("子未", "丑午", "寅酉", "卯申", "辰亥", "巳戌")
|
||||
|
||||
# 도화: 삼합 묶음의 왕지 다음 자리
|
||||
DOHWA = {"寅午戌": "卯", "申子辰": "酉", "巳酉丑": "午", "亥卯未": "子"}
|
||||
# 홍염: 일간 기준. 책마다 다른 표가 있어 이 표로 고정한다
|
||||
HONGYEOM = {"甲": "午", "乙": "午", "丙": "寅", "丁": "未", "戊": "辰", "己": "辰", "庚": "戌", "辛": "酉", "壬": "子", "癸": "申"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Relation:
|
||||
kind: str # 천간합·천간충·육합·삼합·반합·충·형·삼형·자형·파·해·원진
|
||||
chars: str # 관계를 이루는 글자 (넣은 순서)
|
||||
element: Optional[str] = None # 합으로 생기는 오행
|
||||
group: Optional[str] = None # 삼합·형 묶음 (예: 亥卯未, 寅巳申)
|
||||
|
||||
|
||||
def _pair_in(a: str, b: str, pairs) -> bool:
|
||||
return a + b in pairs or b + a in pairs
|
||||
|
||||
|
||||
def ten_god(day_stem: str, stem: str) -> str:
|
||||
"""일간 기준 천간의 십성."""
|
||||
rel = (ELEMENTS.index(stem_element(stem)) - ELEMENTS.index(stem_element(day_stem))) % 5
|
||||
return _TEN_GODS[rel][0 if stem_yang(stem) == stem_yang(day_stem) else 1]
|
||||
|
||||
|
||||
def branch_ten_god(day_stem: str, branch: str) -> str:
|
||||
"""지지의 십성은 정기로 본다."""
|
||||
return ten_god(day_stem, main_stem(branch))
|
||||
|
||||
|
||||
def stem_relations(a: str, b: str) -> list[Relation]:
|
||||
out = []
|
||||
for pair, element in STEM_HAP.items():
|
||||
if _pair_in(a, b, (pair,)):
|
||||
out.append(Relation("천간합", a + b, element))
|
||||
if _pair_in(a, b, STEM_CHUNG):
|
||||
out.append(Relation("천간충", a + b))
|
||||
return out
|
||||
|
||||
|
||||
def branch_relations(a: str, b: str) -> list[Relation]:
|
||||
"""두 지지 사이의 육합·반합·충·형·자형·파·해·원진. 한 쌍이 여러 관계를 함께 가질 수 있다 (예: 巳申 = 육합·형·파)."""
|
||||
out = []
|
||||
for pair, element in YUKHAP.items():
|
||||
if _pair_in(a, b, (pair,)):
|
||||
out.append(Relation("육합", a + b, element))
|
||||
for group, element in SAMHAP.items():
|
||||
# 반합은 생지+왕지, 왕지+묘지만
|
||||
if _pair_in(a, b, (group[:2], group[1:])):
|
||||
out.append(Relation("반합", a + b, element, group))
|
||||
if _pair_in(a, b, CHUNG):
|
||||
out.append(Relation("충", a + b))
|
||||
if a == b and a in JAHYEONG:
|
||||
out.append(Relation("자형", a + b))
|
||||
for pair, group in HYEONG.items():
|
||||
if _pair_in(a, b, (pair,)):
|
||||
out.append(Relation("형", a + b, group=group))
|
||||
for kind, pairs in (("파", PA), ("해", HAE), ("원진", WONJIN)):
|
||||
if _pair_in(a, b, pairs):
|
||||
out.append(Relation(kind, a + b))
|
||||
return out
|
||||
|
||||
|
||||
def triple_relations(branches: list[str]) -> list[Relation]:
|
||||
"""세 지지가 모두 있어야 성립하는 삼합·삼형."""
|
||||
out = []
|
||||
present = set(branches)
|
||||
for group, element in SAMHAP.items():
|
||||
if set(group) <= present:
|
||||
out.append(Relation("삼합", group, element, group))
|
||||
for group in SAMHYEONG:
|
||||
if set(group) <= present:
|
||||
out.append(Relation("삼형", group, group=group))
|
||||
return out
|
||||
|
||||
|
||||
def dohwa_of(branch: str) -> str:
|
||||
"""branch 가 속한 삼합 묶음의 도화 지지."""
|
||||
return next(target for group, target in DOHWA.items() if branch in group)
|
||||
|
||||
|
||||
def hongyeom_of(day_stem: str) -> str:
|
||||
return HONGYEOM[day_stem]
|
||||
|
||||
|
||||
def natal_relations(pillars: dict) -> list[dict]:
|
||||
"""원국 기둥끼리의 관계. pillars 는 {자리: Pillar}."""
|
||||
out = []
|
||||
for (p1, a), (p2, b) in combinations(pillars.items(), 2):
|
||||
for part, rels in (("stem", stem_relations(a.stem, b.stem)), ("branch", branch_relations(a.branch, b.branch))):
|
||||
out += [{"positions": (p1, p2), "part": part, "relation": r} for r in rels]
|
||||
for r in triple_relations([p.branch for p in pillars.values()]):
|
||||
out.append({"positions": tuple(k for k, p in pillars.items() if p.branch in r.group), "part": "branch", "relation": r})
|
||||
return out
|
||||
|
||||
|
||||
def chart_ten_gods(day_stem: str, pillars: dict) -> dict[str, dict[str, Optional[str]]]:
|
||||
"""자리별 천간·지지 십성. 일간 자리는 None."""
|
||||
return {
|
||||
pos: {"stem": None if pos == "day" else ten_god(day_stem, p.stem), "branch": branch_ten_god(day_stem, p.branch)}
|
||||
for pos, p in pillars.items()
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"""절입 시각. 태양 시황경을 Meeus 천문 알고리즘 25장(VSOP87 요약표·장동·광행차)으로 구하고 ΔT 는 Espenak–Meeus 다항식을 쓴다.
|
||||
|
||||
1900~2100년 범위에서 쓴다. 한국천문연구원 발표 시각과의 비교는 tests/test_saju_engine.py 에 있다.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import lru_cache
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
_J2000 = 2451545.0
|
||||
_EPOCH = datetime(2000, 1, 1, 12, tzinfo=timezone.utc)
|
||||
_TROPICAL_YEAR = 365.2422
|
||||
|
||||
# 절 12개: (이름, 태양 황경, 그 절부터 시작하는 월지)
|
||||
JEOL: tuple[tuple[str, int, str], ...] = (
|
||||
("소한", 285, "丑"), ("입춘", 315, "寅"), ("경칩", 345, "卯"), ("청명", 15, "辰"),
|
||||
("입하", 45, "巳"), ("망종", 75, "午"), ("소서", 105, "未"), ("입추", 135, "申"),
|
||||
("백로", 165, "酉"), ("한로", 195, "戌"), ("입동", 225, "亥"), ("대설", 255, "子"),
|
||||
)
|
||||
|
||||
# Meeus 부록 III 지구 VSOP87 요약표: (A, B, C) → A·cos(B + C·τ), 단위 1e-8 rad / 1e-8 AU
|
||||
_L0 = (
|
||||
(175347046, 0, 0), (3341656, 4.6692568, 6283.07585), (34894, 4.6261, 12566.1517), (3497, 2.7441, 5753.3849),
|
||||
(3418, 2.8289, 3.5231), (3136, 3.6277, 77713.7715), (2676, 4.4181, 7860.4194), (2343, 6.1352, 3930.2097),
|
||||
(1324, 0.7425, 11506.7698), (1273, 2.0371, 529.691), (1199, 1.1096, 1577.3435), (990, 5.233, 5884.927),
|
||||
(902, 2.045, 26.298), (857, 3.508, 398.149), (780, 1.179, 5223.694), (753, 2.533, 5507.553),
|
||||
(505, 4.583, 18849.228), (492, 4.205, 775.523), (357, 2.92, 0.067), (317, 5.849, 11790.629),
|
||||
(284, 1.899, 796.298), (271, 0.315, 10977.079), (243, 0.345, 5486.778), (206, 4.806, 2544.314),
|
||||
(205, 1.869, 5573.143), (202, 2.458, 6069.777), (156, 0.833, 213.299), (132, 3.411, 2942.463),
|
||||
(126, 1.083, 20.775), (115, 0.645, 0.98), (103, 0.636, 4694.003), (102, 0.976, 15720.839),
|
||||
(102, 4.267, 7.114), (99, 6.21, 2146.17), (98, 0.68, 155.42), (86, 5.98, 161000.69),
|
||||
(85, 1.3, 6275.96), (85, 3.67, 71430.7), (80, 1.81, 17260.15), (79, 3.04, 12036.46),
|
||||
(75, 1.76, 5088.63), (74, 3.5, 3154.69), (74, 4.68, 801.82), (70, 0.83, 9437.76),
|
||||
(62, 3.98, 8827.39), (61, 1.82, 7084.9), (57, 2.78, 6286.6), (56, 4.39, 14143.5),
|
||||
(56, 3.47, 6279.55), (52, 0.19, 12139.55), (52, 1.33, 1748.02), (51, 0.28, 5856.48),
|
||||
(49, 0.49, 1194.45), (41, 5.37, 8429.24), (41, 2.4, 19651.05), (39, 6.17, 10447.39),
|
||||
(37, 6.04, 10213.29), (37, 2.57, 1059.38), (36, 1.71, 2352.87), (36, 1.78, 6812.77),
|
||||
(33, 0.59, 17789.85), (30, 0.44, 83996.85), (30, 2.74, 1349.87), (25, 3.16, 4690.48),
|
||||
)
|
||||
_L1 = (
|
||||
(628331966747, 0, 0), (206059, 2.678235, 6283.07585), (4303, 2.6351, 12566.1517), (425, 1.59, 3.523),
|
||||
(119, 5.796, 26.298), (109, 2.966, 1577.344), (93, 2.59, 18849.23), (72, 1.14, 529.69),
|
||||
(68, 1.87, 398.15), (67, 4.41, 5507.55), (59, 2.89, 5223.69), (56, 2.17, 155.42),
|
||||
(45, 0.4, 796.3), (36, 0.47, 775.52), (29, 2.65, 7.11), (21, 5.34, 0.98),
|
||||
(19, 1.85, 5486.78), (19, 4.97, 213.3), (17, 2.99, 6275.96), (16, 0.03, 2544.31),
|
||||
(16, 1.43, 2146.17), (15, 1.21, 10977.08), (12, 2.83, 1748.02), (12, 3.26, 5088.63),
|
||||
(12, 5.27, 1194.45), (12, 2.08, 4694.0), (11, 0.77, 553.57), (10, 1.3, 6286.6),
|
||||
(10, 4.24, 1349.87), (9, 2.7, 242.73), (9, 5.64, 951.72), (8, 5.3, 2352.87),
|
||||
(6, 2.65, 9437.76), (6, 4.67, 4690.48),
|
||||
)
|
||||
_L2 = (
|
||||
(52919, 0, 0), (8720, 1.0721, 6283.0758), (309, 0.867, 12566.152), (27, 0.05, 3.52),
|
||||
(16, 5.19, 26.3), (16, 3.68, 155.42), (10, 0.76, 18849.23), (9, 2.06, 77713.77),
|
||||
(7, 0.83, 775.52), (5, 4.66, 1577.34), (4, 1.03, 7.11), (4, 3.44, 5573.14),
|
||||
(3, 5.14, 796.3), (3, 6.05, 5507.55), (3, 1.19, 242.73), (3, 6.12, 529.69),
|
||||
(3, 0.31, 398.15), (3, 2.28, 553.57), (2, 4.38, 5223.69), (2, 3.75, 0.98),
|
||||
)
|
||||
_L3 = ((289, 5.844, 6283.076), (35, 0, 0), (17, 5.49, 12566.15), (3, 5.2, 155.42), (1, 4.72, 3.52), (1, 5.3, 18849.23), (1, 5.97, 242.73))
|
||||
_L4 = ((114, 3.142, 0), (8, 4.13, 6283.08), (1, 3.84, 12566.15))
|
||||
_L5 = ((1, 3.14, 0),)
|
||||
_R0 = (
|
||||
(100013989, 0, 0), (1670700, 3.0984635, 6283.07585), (13956, 3.05525, 12566.1517), (3084, 5.1985, 77713.7715),
|
||||
(1628, 1.1739, 5753.3849), (1576, 2.8469, 7860.4194), (925, 5.453, 11506.77), (542, 4.564, 3930.21),
|
||||
(472, 3.661, 5884.927), (346, 0.964, 5507.553), (329, 5.9, 5223.694), (307, 0.299, 5573.143),
|
||||
(243, 4.273, 11790.629), (212, 5.847, 1577.344), (186, 5.022, 10977.079), (175, 3.012, 18849.228),
|
||||
(110, 5.055, 5486.778), (98, 0.89, 6069.78), (86, 5.69, 15720.84), (86, 1.27, 161000.69),
|
||||
(65, 0.27, 17260.15), (63, 0.92, 529.69), (57, 2.01, 83996.85), (56, 5.24, 71430.7),
|
||||
(49, 3.25, 2544.31), (47, 2.58, 775.52), (45, 5.54, 9437.76), (43, 6.01, 6275.96),
|
||||
(39, 5.36, 4694.0), (38, 2.39, 8827.39), (37, 0.83, 19651.05), (37, 4.9, 12139.55),
|
||||
(36, 1.67, 12036.46), (35, 1.84, 2942.46), (33, 0.24, 7084.9), (32, 0.18, 5088.63),
|
||||
(32, 1.78, 398.15), (28, 1.21, 6286.6), (28, 1.9, 6279.55), (26, 4.59, 10447.39),
|
||||
)
|
||||
_R1 = (
|
||||
(103019, 1.10749, 6283.07585), (1721, 1.0644, 12566.1517), (702, 3.142, 0), (32, 1.02, 18849.23),
|
||||
(31, 2.84, 5507.55), (25, 1.32, 5223.69), (18, 1.42, 1577.34), (10, 5.91, 10977.08),
|
||||
(9, 1.42, 6275.96), (9, 0.27, 5486.78),
|
||||
)
|
||||
_R2 = ((4359, 5.7846, 6283.0758), (124, 5.579, 12566.152), (12, 3.14, 0), (9, 3.63, 77713.77), (6, 1.87, 5573.14), (3, 5.47, 18849.23))
|
||||
_R3 = ((145, 4.273, 6283.076), (7, 3.92, 12566.15))
|
||||
_R4 = ((4, 2.56, 6283.08),)
|
||||
|
||||
# Meeus 표 22.A 장동 황경 성분 큰 항 13개: (D, M, M', F, Ω 계수, sin 계수, T 계수) 단위 0.0001″. 빠진 항은 모두 0.01″ 미만
|
||||
_NUTATION = (
|
||||
(0, 0, 0, 0, 1, -171996, -174.2), (-2, 0, 0, 2, 2, -13187, -1.6), (0, 0, 0, 2, 2, -2274, -0.2),
|
||||
(0, 0, 0, 0, 2, 2062, 0.2), (0, 1, 0, 0, 0, 1426, -3.4), (0, 0, 1, 0, 0, 712, 0.1),
|
||||
(-2, 1, 0, 2, 2, -517, 1.2), (0, 0, 0, 2, 1, -386, -0.4), (0, 0, 1, 2, 2, -301, 0),
|
||||
(-2, -1, 0, 2, 2, 217, -0.5), (-2, 0, 1, 0, 0, -158, 0), (-2, 0, 0, 2, 1, 129, 0.1), (0, 0, -1, 2, 2, 123, 0),
|
||||
)
|
||||
|
||||
|
||||
def _series(terms: tuple, tau: float) -> float:
|
||||
return sum(a * math.cos(b + c * tau) for a, b, c in terms)
|
||||
|
||||
|
||||
def _poly(groups: tuple, tau: float) -> float:
|
||||
return sum(_series(g, tau) * tau**i for i, g in enumerate(groups)) / 1e8
|
||||
|
||||
|
||||
def nutation_longitude(jde: float) -> float:
|
||||
"""황경 장동 Δψ (각초)."""
|
||||
t = (jde - _J2000) / 36525
|
||||
d = 297.85036 + 445267.11148 * t - 0.0019142 * t * t + t**3 / 189474
|
||||
m = 357.52772 + 35999.05034 * t - 0.0001603 * t * t - t**3 / 300000
|
||||
mp = 134.96298 + 477198.867398 * t + 0.0086972 * t * t + t**3 / 56250
|
||||
f = 93.27191 + 483202.017538 * t - 0.0036825 * t * t + t**3 / 327270
|
||||
om = 125.04452 - 1934.136261 * t + 0.0020708 * t * t + t**3 / 450000
|
||||
total = 0.0
|
||||
for cd, cm, cmp, cf, co, s0, s1 in _NUTATION:
|
||||
arg = math.radians(cd * d + cm * m + cmp * mp + cf * f + co * om)
|
||||
total += (s0 + s1 * t) * math.sin(arg)
|
||||
return total / 10000
|
||||
|
||||
|
||||
def sun_apparent_longitude(jde: float) -> float:
|
||||
"""역학시(JDE) 기준 태양 시황경(도, 0~360)."""
|
||||
tau = (jde - _J2000) / 365250
|
||||
lon = math.degrees(_poly((_L0, _L1, _L2, _L3, _L4, _L5), tau)) + 180
|
||||
r = _poly((_R0, _R1, _R2, _R3, _R4), tau)
|
||||
# FK5 보정 −0.09033″, 장동, 광행차 −20.4898″/R
|
||||
lon += (-0.09033 + nutation_longitude(jde) - 20.4898 / r) / 3600
|
||||
return lon % 360
|
||||
|
||||
|
||||
def delta_t(year: float) -> float:
|
||||
"""ΔT = TT − UT (초). Espenak & Meeus (NASA 일식 누리집) 다항식, 1860~2150년 구간."""
|
||||
y = year
|
||||
if y < 1900:
|
||||
t = y - 1860
|
||||
return 7.62 + 0.5737 * t - 0.251754 * t**2 + 0.01680668 * t**3 - 0.0004473624 * t**4 + t**5 / 233174
|
||||
if y < 1920:
|
||||
t = y - 1900
|
||||
return -2.79 + 1.494119 * t - 0.0598939 * t**2 + 0.0061966 * t**3 - 0.000197 * t**4
|
||||
if y < 1941:
|
||||
t = y - 1920
|
||||
return 21.20 + 0.84493 * t - 0.0761 * t**2 + 0.0020936 * t**3
|
||||
if y < 1961:
|
||||
t = y - 1950
|
||||
return 29.07 + 0.407 * t - t**2 / 233 + t**3 / 2547
|
||||
if y < 1986:
|
||||
t = y - 1975
|
||||
return 45.45 + 1.067 * t - t**2 / 260 - t**3 / 718
|
||||
if y < 2005:
|
||||
t = y - 2000
|
||||
return 63.86 + 0.3345 * t - 0.060374 * t**2 + 0.0017275 * t**3 + 0.000651814 * t**4 + 0.00002373599 * t**5
|
||||
if y < 2050:
|
||||
t = y - 2000
|
||||
return 62.92 + 0.32217 * t + 0.005589 * t**2
|
||||
return -20 + 32 * ((y - 1820) / 100) ** 2 - 0.5628 * (2150 - y)
|
||||
|
||||
|
||||
def _to_datetime(jd: float) -> datetime:
|
||||
return _EPOCH + timedelta(days=jd - _J2000)
|
||||
|
||||
|
||||
def _jd(at: datetime) -> float:
|
||||
return _J2000 + (at - _EPOCH).total_seconds() / 86400
|
||||
|
||||
|
||||
def term_moment(year: int, longitude: float) -> datetime:
|
||||
"""그해 태양 시황경이 longitude 가 되는 시각 (UTC). 270° 넘는 절기(소한·입춘 등)는 그해 1~3월 것."""
|
||||
days = longitude / 360 * _TROPICAL_YEAR - (_TROPICAL_YEAR if longitude > 270 else 0)
|
||||
jde = _jd(datetime(year, 3, 20, tzinfo=timezone.utc)) + days
|
||||
for _ in range(20):
|
||||
diff = (longitude - sun_apparent_longitude(jde) + 180) % 360 - 180
|
||||
jde += diff / 360 * _TROPICAL_YEAR
|
||||
if abs(diff) < 1e-9:
|
||||
break
|
||||
decimal_year = year + (jde - _jd(datetime(year, 1, 1, tzinfo=timezone.utc))) / _TROPICAL_YEAR
|
||||
return _to_datetime(jde - delta_t(decimal_year) / 86400)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jeol:
|
||||
name: str
|
||||
longitude: int
|
||||
month_branch: str # 이 절부터 바뀌는 월지
|
||||
at: datetime # KST
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def jeol_of_year(year: int) -> tuple[Jeol, ...]:
|
||||
"""그해 양력 1~12월에 드는 절 12개 (소한 → 대설 순)."""
|
||||
return tuple(Jeol(name, lon, branch, term_moment(year, lon).astimezone(KST)) for name, lon, branch in JEOL)
|
||||
|
||||
|
||||
def jeol_around(at: datetime) -> tuple[Jeol, Jeol]:
|
||||
"""at 직전(같은 시각 포함)에 든 절과 다음 절."""
|
||||
terms = [j for y in (at.year - 1, at.year, at.year + 1) for j in jeol_of_year(y)]
|
||||
i = max(k for k, j in enumerate(terms) if j.at <= at)
|
||||
return terms[i], terms[i + 1]
|
||||
@@ -0,0 +1,441 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, time, timedelta
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User, WeatherDaily, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services import saju_text as T
|
||||
from services.level_service import award, level_of, unlock_level
|
||||
from services.saju.climate import HourWeather, chart_climate, climate_match
|
||||
from services.saju.daily import DailyFacts, daily_facts, interactions, score as pillar_score
|
||||
from services.saju.ganji import branch_element, ko, stem_element
|
||||
from services.saju.pillars import Chart, Pillar, make_chart
|
||||
from services.saju.rules import branch_relations, stem_relations, ten_god
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import WeekService
|
||||
|
||||
Gender = Literal["male", "female"]
|
||||
WEEK_DAYS = 7
|
||||
# 오늘 점수 = 사주 점수 + (날씨 궁합 − 50) × 이 비율. 화면 점수는 평균 68 쯤에서 퍼지게 늘린다 (날씨 점수처럼 50 이 '나쁨'으로 읽히지 않게)
|
||||
WEATHER_SHARE = 0.6
|
||||
SHOW_CENTER, SHOW_SPREAD, SHOW_MIN, SHOW_MAX = 68, 1.2, 25, 98
|
||||
RIVALS = ("비견", "겁재")
|
||||
CROWDED = 3 # 원국에 비겁이 이만큼 이상이면 비겁 날 돈 조심 (군겁쟁재)
|
||||
_WEEKDAY = "월화수목금토일"
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayWeather:
|
||||
hours: list[HourWeather]
|
||||
icon: str
|
||||
word: str
|
||||
temp_min: Optional[int]
|
||||
temp_max: Optional[int]
|
||||
by_hour: dict[int, tuple[float, str]] = field(default_factory=dict) # 시각 → (기온, 하늘 말)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayReading:
|
||||
day: date
|
||||
facts: DailyFacts
|
||||
weather: Optional[DayWeather]
|
||||
climate_score: Optional[int]
|
||||
best_hours: tuple[int, ...]
|
||||
reasons: tuple[dict, ...]
|
||||
score: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Card:
|
||||
kind: str # when·do·avoid·good·wear
|
||||
title: str
|
||||
body: str
|
||||
sub: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reading:
|
||||
chart: Chart
|
||||
scene: tuple[str, str]
|
||||
scene_icon: str
|
||||
need: list[str]
|
||||
today: DayReading
|
||||
cards: list[Card]
|
||||
why: list[str]
|
||||
level: int
|
||||
logged_in: bool
|
||||
week: Optional[list[DayReading]] = None
|
||||
money: Optional[str] = None
|
||||
work: Optional[str] = None
|
||||
love: Optional[dict] = None
|
||||
month: Optional[dict] = None
|
||||
year: Optional[dict] = None
|
||||
|
||||
|
||||
def _icon(sky: Sky, rain: RainType) -> str:
|
||||
if rain is RainType.SNOW:
|
||||
return "snow"
|
||||
if rain is not RainType.NONE:
|
||||
return "rain"
|
||||
return {Sky.CLEAR: "sun", Sky.PARTLY: "sun_cloud", Sky.CLOUDY: "cloud"}[sky]
|
||||
|
||||
|
||||
def _word(sky: Sky, rain: RainType) -> str:
|
||||
return "눈" if rain is RainType.SNOW else "비" if rain is not RainType.NONE else _SKY_WORD[sky]
|
||||
|
||||
|
||||
def hourly_weather(rows: list[WeatherHourly]) -> Optional[DayWeather]:
|
||||
"""시간별 예보 → 06~21시 날씨. 칸이 모자라면 None"""
|
||||
rows = [r for r in rows if 6 <= r.forecast_at.astimezone(KST).hour <= 21]
|
||||
if len(rows) < 6:
|
||||
return None
|
||||
hours = [HourWeather(hour=r.forecast_at.astimezone(KST).hour, feels_c=float(r.feels_c), humidity=float(r.humidity), raining=r.rain_type != RainType.NONE.value) for r in rows]
|
||||
wet = [RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value]
|
||||
noon = min(rows, key=lambda r: abs(r.forecast_at.astimezone(KST).hour - 14))
|
||||
rain = wet[0] if wet else RainType.NONE
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
return DayWeather(
|
||||
hours=hours, icon=_icon(Sky(noon.sky), rain), word=_word(Sky(noon.sky), rain), temp_min=round(min(temps)), temp_max=round(max(temps)),
|
||||
by_hour={r.forecast_at.astimezone(KST).hour: (float(r.temp_c), _word(Sky(r.sky), RainType(r.rain_type))) for r in rows},
|
||||
)
|
||||
|
||||
|
||||
def daily_weather(d: WeatherDaily) -> Optional[DayWeather]:
|
||||
"""중기예보(하루 최저·최고)로 06~21시를 어림한다: 6시 최저 → 15시 최고 → 21시 중간"""
|
||||
if d.temp_min_c is None or d.temp_max_c is None:
|
||||
return None
|
||||
lo, hi = float(d.temp_min_c), float(d.temp_max_c)
|
||||
rain = RainType(d.rain_type)
|
||||
wet = rain is not RainType.NONE or d.rain_prob >= 60
|
||||
hours = []
|
||||
for h in range(6, 22):
|
||||
t = lo + (hi - lo) * (h - 6) / 9 if h <= 15 else hi - (hi - lo) * (h - 15) / 12
|
||||
hours.append(HourWeather(hour=h, feels_c=t, humidity=85 if wet else 55, raining=wet))
|
||||
return DayWeather(hours=hours, icon=_icon(Sky(d.sky), rain), word=_word(Sky(d.sky), rain), temp_min=round(lo), temp_max=round(hi))
|
||||
|
||||
|
||||
def shown_saju(saju: int) -> int:
|
||||
return max(SHOW_MIN, min(SHOW_MAX, round(SHOW_CENTER + (saju - 50) * SHOW_SPREAD)))
|
||||
|
||||
|
||||
def weather_points(climate: Optional[int]) -> Optional[int]:
|
||||
return None if climate is None else round((climate - 50) * WEATHER_SHARE * SHOW_SPREAD)
|
||||
|
||||
|
||||
def total_score(saju: int, climate: Optional[int]) -> int:
|
||||
return max(SHOW_MIN, min(SHOW_MAX, shown_saju(saju) + (weather_points(climate) or 0)))
|
||||
|
||||
|
||||
def window_text(best: tuple[int, ...]) -> str:
|
||||
"""좋은 시각들 → '오후 1~4시' / '오전 11시~오후 2시' / '오후 3시 전후'"""
|
||||
if not best:
|
||||
return ""
|
||||
lo, hi = min(best), max(best) + 1
|
||||
if lo + 1 == hi:
|
||||
return f"{T.hour_word(lo)} 전후"
|
||||
a, b = T.hour_word(lo).split(" "), T.hour_word(hi).split(" ")
|
||||
return f"{a[0]} {a[1][:-1]}~{b[1]}" if a[0] == b[0] else f"{a[0]} {a[1]}~{b[0]} {b[1]}"
|
||||
|
||||
|
||||
def _pillars(chart: Chart) -> dict[str, Pillar]:
|
||||
out = {"year": chart.year, "month": chart.month, "day": chart.day}
|
||||
if chart.hour is not None:
|
||||
out["hour"] = chart.hour
|
||||
return out
|
||||
|
||||
|
||||
def crowded_rivals(chart: Chart) -> bool:
|
||||
"""원국에 비견·겁재(일간 포함)가 많은지"""
|
||||
me = chart.day.stem
|
||||
stems = [p.stem for p in _pillars(chart).values()]
|
||||
branches = [p.branch for p in _pillars(chart).values()]
|
||||
n = sum(1 for s in stems if ten_god(me, s) in RIVALS) + sum(1 for b in branches if stem_element(me) == branch_element(b))
|
||||
return n >= CROWDED
|
||||
|
||||
|
||||
def why_words(facts: DailyFacts) -> list[str]:
|
||||
"""점수에 가장 크게 작용한 사실 셋을 사람 말로"""
|
||||
out = []
|
||||
for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]:
|
||||
place = f"{T.PLACE_WORD[c.position]} 자리와 " if c.position else ""
|
||||
sign = "+" if c.points >= 0 else "−"
|
||||
out.append(f"{place}{c.fact}({'·'.join(ko(ch) for ch in c.chars)}) {sign}{abs(round(c.points))}")
|
||||
return out
|
||||
|
||||
|
||||
def _rel(i) -> str:
|
||||
return f"{T.PLACE_WORD[i.position]} 자리와 {i.relation.kind}({'·'.join(ko(ch) for ch in i.relation.chars)})"
|
||||
|
||||
|
||||
def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]:
|
||||
"""조심할 것 두 가지까지: 돈(군겁쟁재)과 가장 무거운 관계 (나·연인 자리 먼저)"""
|
||||
lines, subs = [], []
|
||||
if facts.stem_ten_god in RIVALS and crowded_rivals(chart):
|
||||
lines.append(T.CROWDED_RIVALS)
|
||||
subs.append(f"원국에 같은 기운이 많은 날 {T.josa(facts.stem_ten_god, '이가')} 들어와요")
|
||||
bad = sorted((i for i in facts.interactions if i.relation.kind in {k for k, _ in T.AVOID_TEXT}), key=lambda i: 0 if i.position == "day" else 1)
|
||||
for i in bad:
|
||||
body = T.AVOID_TEXT.get((i.relation.kind, i.position)) or T.AVOID_TEXT.get((i.relation.kind, ""))
|
||||
if body and body not in lines:
|
||||
lines.append(body)
|
||||
subs.append(_rel(i))
|
||||
break
|
||||
if not lines:
|
||||
return None
|
||||
return Card(kind="avoid", title="오늘 조심할 것", body="\n".join(lines[:2]), sub=" · ".join(subs[:2]))
|
||||
|
||||
|
||||
def good_card(facts: DailyFacts) -> Optional[Card]:
|
||||
good = sorted((i for i in facts.interactions if i.relation.kind in T.GOOD_RELATIONS), key=lambda i: 0 if i.position == "day" else 1)
|
||||
if not good:
|
||||
return None
|
||||
i = good[0]
|
||||
return Card(kind="good", title="오늘 좋은 흐름", body=T.GOOD_TEXT[i.position], sub=_rel(i))
|
||||
|
||||
|
||||
def when_card(r: DayReading) -> Optional[Card]:
|
||||
if not r.best_hours or r.weather is None:
|
||||
return None
|
||||
h = r.best_hours[0]
|
||||
temp, word = r.weather.by_hour.get(h, (None, r.weather.word))
|
||||
helps = [T.NEED_WORD[(x["axis"], x["need"])] for x in r.reasons if x.get("helps") and (x["axis"], x["need"]) in T.NEED_WORD]
|
||||
body = f"내 기운에 필요한 {T.josa('·'.join(helps), '이가')} 가장 많이 오는 때예요. 중요한 일은 이때 하세요." if helps else "오늘 날씨가 내 기운과 가장 무난한 때예요. 중요한 일은 이때 하세요."
|
||||
sub = f"{word} {round(temp)}°" if temp is not None else word
|
||||
return Card(kind="when", title=window_text(r.best_hours), body=body, sub=sub)
|
||||
|
||||
|
||||
def needs_of(chart_need: dict) -> list[tuple[str, str]]:
|
||||
"""조후에서 채워야 할 축 (순한 축은 뺀다)"""
|
||||
return [(a, n) for a, n in chart_need.items() if n != "mild"]
|
||||
|
||||
|
||||
def wear_card(r: DayReading, needs: list[tuple[str, str]], place: Optional[str]) -> Optional[Card]:
|
||||
if r.weather is None:
|
||||
return None
|
||||
feels = min(h.feels_c for h in r.weather.hours)
|
||||
color = T.NEED_COLOR[needs[0]] if needs else None
|
||||
body = f"아침저녁 체감 {round(feels)}°라 {T.clothes(feels)}" + (f", 색은 {color} 포인트" if color else "")
|
||||
return Card(kind="wear", title="입을 것 · 갈 곳", body=body, sub=f"갈 곳: {place}" if place else None)
|
||||
|
||||
|
||||
def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) -> dict:
|
||||
"""이번 주 연애 기운이 좋은 날과 조심할 날. 비 오는 날은 좋은 날에서 뒤로"""
|
||||
goods, bads = [], []
|
||||
for r in week:
|
||||
kinds = set()
|
||||
for x in r.facts.love.reasons:
|
||||
k = x["kind"]
|
||||
if k == "일지":
|
||||
rel = x.get("relation")
|
||||
(kinds.add("일지합") if rel in ("육합", "반합", "삼합") else bads.append((r, rel)))
|
||||
else:
|
||||
kinds.add(k)
|
||||
good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds]
|
||||
if good:
|
||||
goods.append((r, good))
|
||||
goods.sort(key=lambda g: (g[0].weather is not None and g[0].weather.icon in ("rain", "snow"), -g[0].score))
|
||||
out: dict = {"gender": gender}
|
||||
if goods:
|
||||
r, kinds = goods[0]
|
||||
rainy = r.weather is not None and r.weather.icon in ("rain", "snow")
|
||||
out["good"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "icon": r.weather.icon if r.weather else None, "word": r.weather.word if r.weather else None,
|
||||
"temp_max": r.weather.temp_max if r.weather else None, "body": T.LOVE_GOOD[kinds[0]] + (" " + T.LOVE_RAINY if rainy else ""), "why": "·".join(kinds)}
|
||||
if bads:
|
||||
r, rel = bads[0]
|
||||
out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD.get(rel, "말을 한 번 더 고르세요."), "why": f"나·연인 자리와 {rel}"}
|
||||
return out
|
||||
|
||||
|
||||
MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "편관", "정인", "상관")
|
||||
|
||||
|
||||
def _day_word(r: DayReading) -> str:
|
||||
return f"{_WEEKDAY[r.day.weekday()]} {r.day.day}일({T.TEN_GOD_TEXT[r.facts.stem_ten_god][0]})"
|
||||
|
||||
|
||||
def money_work(week: list[DayReading]) -> tuple[list[str], list[str]]:
|
||||
"""금전·일: 이번 주에 정할 날과 피할 날 (오늘 카드를 되풀이하지 않는다)"""
|
||||
def pick(gods: tuple[str, ...]) -> Optional[DayReading]:
|
||||
return next((r for r in week if r.facts.stem_ten_god in gods), None)
|
||||
|
||||
money, work = [], []
|
||||
if (g := pick(MONEY_GOOD)) is not None:
|
||||
money.append(f"큰 결제·계약은 {_day_word(g)}에 하세요.")
|
||||
if (b := pick(MONEY_BAD)) is not None:
|
||||
money.append(f"돈 빌려주기·공동 지출은 {_day_word(b)}엔 피하세요.")
|
||||
if (w := pick(WORK_GOOD)) is not None:
|
||||
work.append(f"보고·발표·면접은 {_day_word(w)}에 잡으세요.")
|
||||
if not money:
|
||||
money.append("이번 주는 돈이 크게 움직이는 날이 없어요. 평소대로 쓰세요.")
|
||||
if not work:
|
||||
work.append("이번 주는 하던 일을 마무리하기 좋아요.")
|
||||
return money, work
|
||||
|
||||
|
||||
def year_months(chart: Chart, year: int) -> list[int]:
|
||||
"""그해 열두 달(절 기준) 중 내 사주와 잘 맞는 달 셋 (달 번호는 그 절이 드는 양력 달)"""
|
||||
scored = []
|
||||
for m in range(1, 13):
|
||||
mp = make_chart(date(year, m, 15), time(12, 0)).month
|
||||
found = interactions(chart, mp)
|
||||
scored.append((pillar_score(chart, mp, found, [], False)[0], m))
|
||||
return sorted(m for _, m in sorted(scored, reverse=True)[:3])
|
||||
|
||||
|
||||
def period(chart: Chart, p: Pillar, unit: str) -> dict:
|
||||
"""이달·올해: 그 간지 천간 십성 + 원국과의 관계"""
|
||||
god = ten_god(chart.day.stem, p.stem)
|
||||
title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god]
|
||||
return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i) for i in interactions(chart, p)]}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Match:
|
||||
score: int
|
||||
title: str
|
||||
lines: list[str]
|
||||
day: Optional[DayReading] # 이번 주 둘 다 좋은 날
|
||||
friend_scene: str
|
||||
|
||||
|
||||
MATCH_SCORE = {"base": 55, "stem_hap": 12, "resource": 8, "wealth": 5, "output": 5, "rival": 2, "officer": 0, "branch_hap": 8, "branch_bad": -8, "climate_ok": 10}
|
||||
|
||||
|
||||
def match_reading(me: Chart, friend: Chart, my_days: list[DayReading], friend_days: list[DayReading]) -> Match:
|
||||
god = ten_god(me.day.stem, friend.day.stem)
|
||||
title, body = next(v for k, v in T.MATCH_TEXT.items() if god in k)
|
||||
group = next(g for k, g in (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource")) if god in k)
|
||||
score, lines = MATCH_SCORE["base"] + MATCH_SCORE[group], [body]
|
||||
if any(r.kind == "천간합" for r in stem_relations(me.day.stem, friend.day.stem)):
|
||||
score += MATCH_SCORE["stem_hap"]
|
||||
lines.append(T.MATCH_STEM_HAP)
|
||||
for r in branch_relations(me.day.branch, friend.day.branch):
|
||||
if r.kind in T.MATCH_BRANCH:
|
||||
score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"]
|
||||
lines.append(T.MATCH_BRANCH[r.kind])
|
||||
break
|
||||
a, b = chart_climate(me), chart_climate(friend)
|
||||
if a.temp * b.temp < 0 or a.moist * b.moist < 0:
|
||||
score += MATCH_SCORE["climate_ok"]
|
||||
lines.append(T.MATCH_CLIMATE_OK)
|
||||
else:
|
||||
need = [T.NEED_WORD[n] for n in needs_of(a.need)]
|
||||
if need:
|
||||
lines.append(T.MATCH_CLIMATE_SAME.format(need=T.josa("·".join(need), "이가")))
|
||||
both = [(x, y) for x, y in zip(my_days, friend_days)]
|
||||
best = max(both, key=lambda p: min(p[0].score, p[1].score))[0] if both else None
|
||||
return Match(score=max(0, min(100, score)), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0])
|
||||
|
||||
|
||||
class SajuService:
|
||||
def __init__(
|
||||
self, regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD), week_crud: WeekCRUD = Depends(WeekCRUD),
|
||||
weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService),
|
||||
) -> None:
|
||||
self.regions, self.weather, self.week_crud, self.weather_service, self.week = regions, weather, week_crud, weather_service, week
|
||||
|
||||
async def _weather(self, region_code: str, start: date) -> tuple[ErrorType, dict[date, DayWeather]]:
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, {}
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, {}
|
||||
await self.weather_service.ensure_vilage(region, now_kst())
|
||||
t0 = kst_midnight(start)
|
||||
err, hourly = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, t0, t0 + timedelta(days=WEEK_DAYS)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, {}
|
||||
err, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.week_crud.daily(s, region.code, start, start + timedelta(days=WEEK_DAYS - 1)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, {}
|
||||
out: dict[date, DayWeather] = {}
|
||||
for i in range(WEEK_DAYS):
|
||||
d = start + timedelta(days=i)
|
||||
w = hourly_weather([r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d])
|
||||
if w is None:
|
||||
dd = next((x for x in daily or [] if x.forecast_date == d), None)
|
||||
w = daily_weather(dd) if dd else None
|
||||
if w is not None:
|
||||
out[d] = w
|
||||
return ErrorType.SUCCESS, out
|
||||
|
||||
def _day(self, chart: Chart, d: date, w: Optional[DayWeather], gender: Optional[Gender]) -> DayReading:
|
||||
facts = daily_facts(chart, d, gender)
|
||||
if w is None:
|
||||
return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=facts.score)
|
||||
m = climate_match(chart, w.hours)
|
||||
return DayReading(day=d, facts=facts, weather=w, climate_score=m.score, best_hours=m.best_hours, reasons=m.reasons, score=total_score(facts.score, m.score))
|
||||
|
||||
def _year(self, chart: Chart, today: date) -> dict:
|
||||
"""올해 운. 11월부터는 다음 해 미리 보기 (입춘 뒤 날짜로 그해 간지)"""
|
||||
y = today.year + 1 if today.month >= 11 else today.year
|
||||
p = make_chart(date(y, 6, 1), time(12, 0)).year
|
||||
return {**period(chart, p, "해"), "year": y, "preview": y != today.year, "months": year_months(chart, y)}
|
||||
|
||||
async def match(
|
||||
self, me: tuple[date, Optional[time], float], friend: tuple[date, Optional[time], float], region_code: str, user: Optional[User],
|
||||
) -> tuple[ErrorType, Optional[Match]]:
|
||||
"""궁합 (레벨 5부터, 로그인 필요)"""
|
||||
if user is None or level_of(user.points) < unlock_level("saju_match"):
|
||||
return ErrorType.AUTH_REQUIRED if user is None else ErrorType.LEVEL_REQUIRED, None
|
||||
try:
|
||||
a, b = make_chart(*me), make_chart(*friend)
|
||||
except ValueError:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = now_kst().date()
|
||||
err, weather = await self._weather(region_code, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
ds = [today + timedelta(days=i) for i in range(WEEK_DAYS)]
|
||||
return ErrorType.SUCCESS, match_reading(a, b, [self._day(a, d, weather.get(d), None) for d in ds], [self._day(b, d, weather.get(d), None) for d in ds])
|
||||
|
||||
async def reading(
|
||||
self, birth_date: date, birth_time: Optional[time], longitude: float, gender: Optional[Gender], region_code: str, user: Optional[User],
|
||||
) -> tuple[ErrorType, Optional[Reading]]:
|
||||
try:
|
||||
chart = make_chart(birth_date, birth_time, longitude)
|
||||
except ValueError:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = now_kst().date()
|
||||
err, weather = await self._weather(region_code, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
days = [self._day(chart, today + timedelta(days=i), weather.get(today + timedelta(days=i)), gender) for i in range(WEEK_DAYS)]
|
||||
r0 = days[0]
|
||||
m0 = climate_match(chart, r0.weather.hours) if r0.weather else None
|
||||
chart_climate = m0.chart if m0 else None
|
||||
scene = T.SCENES[(chart_climate.season, chart_climate.label)] if chart_climate else ("", "")
|
||||
needs = needs_of(chart_climate.need) if chart_climate else []
|
||||
_, places, _, _ = await self.week.places(region_code, today, None)
|
||||
place = next((p.place.name for p in places if p.is_good), places[0].place.name if places else None)
|
||||
todo = T.TEN_GOD_TEXT[r0.facts.stem_ten_god][1]
|
||||
cards = [c for c in (when_card(r0), Card(kind="do", title="오늘 할 것", body=todo, sub=f"오늘은 {T.josa(r0.facts.stem_ten_god, '이가')} 들어오는 날"), avoid_card(chart, r0.facts), good_card(r0.facts), wear_card(r0, needs, place)) if c]
|
||||
|
||||
level = 1
|
||||
if user is not None:
|
||||
total = await award(user.user_id, "saju")
|
||||
level = level_of(total or user.points)
|
||||
|
||||
def unlocked(key: str) -> bool:
|
||||
return user is not None and level >= unlock_level(key)
|
||||
|
||||
now_chart = make_chart(today, time(12, 0))
|
||||
return ErrorType.SUCCESS, Reading(
|
||||
chart=chart, scene=scene, scene_icon=T.SCENE_ICON.get(chart_climate.label, "sun") if chart_climate else "sun",
|
||||
need=[T.NEED_WORD[n] for n in needs], today=r0, cards=cards, why=why_words(r0.facts), level=level, logged_in=user is not None,
|
||||
week=days if unlocked("saju_week") else None,
|
||||
money=money_work(days)[0] if unlocked("saju_money") else None,
|
||||
work=money_work(days)[1] if unlocked("saju_money") else None,
|
||||
love=love_week(chart, days, gender) if unlocked("saju_love") else None,
|
||||
month={**period(chart, now_chart.month, "달"), "from": now_chart.jeol.at.date(), "until": now_chart.next_jeol.at.date(), "jeol": now_chart.jeol.name} if unlocked("saju_month") else None,
|
||||
year=self._year(chart, today) if unlocked("saju_year") else None,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다 (초안, 사용자 검토 대상)."""
|
||||
|
||||
# 오늘 천간 십성 → (제목, 오늘 할 것)
|
||||
TEN_GOD_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("내 힘으로 밀고 가는 날", "혼자 끝낼 수 있는 일을 오늘 끝내세요."),
|
||||
"겁재": ("내 몫을 지키는 날", "남 눈치 보지 말고 내가 정한 일을 밀고 가세요."),
|
||||
"식신": ("즐기고 먹는 날", "맛있는 걸 먹고 좋아하는 일에 시간을 쓰세요."),
|
||||
"상관": ("말과 재주가 빛나는 날", "발표·제안·글쓰기처럼 밖으로 꺼내는 일을 하세요."),
|
||||
"편재": ("기회가 들어오는 날", "들어오는 제안은 들어 보고, 큰돈은 하루 생각한 뒤 정하세요."),
|
||||
"정재": ("차곡차곡 모으는 날", "정리·가계부·저축처럼 꼼꼼한 일을 하세요."),
|
||||
"편관": ("버티면 크는 날", "미뤄 둔 어려운 일에 먼저 손대 보세요."),
|
||||
"정관": ("믿음을 얻는 날", "약속 시간과 규칙을 지키면 평가가 올라가요."),
|
||||
"편인": ("혼자 생각하는 날", "혼자 있는 시간에 떠오른 생각을 적어 두세요."),
|
||||
"정인": ("배우고 도움받는 날", "공부·자격증·조언 구하기에 좋아요."),
|
||||
}
|
||||
|
||||
# 원국 자리 → 화면에 쓰는 짧은 이름
|
||||
PLACE_WORD = {"year": "윗사람·바깥 일", "month": "직장·집안", "day": "나·연인", "hour": "아랫사람·앞날"}
|
||||
|
||||
# (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로
|
||||
AVOID_TEXT: dict[tuple[str, str], str] = {
|
||||
("원진", "day"): "연인·배우자에게 사소한 서운함이 생기기 쉬워요. 큰 이야기는 내일로 미루세요.",
|
||||
("충", "day"): "가까운 사람과 부딪히기 쉬워요. 다툼이 될 만한 이야기는 피하세요.",
|
||||
("충", "month"): "직장·집안 일정이 흔들리기 쉬워요. 이직·이사 같은 큰 결정은 미루세요.",
|
||||
("충", "year"): "윗사람·바깥 일에서 변수가 생기기 쉬워요. 약속은 한 번 더 확인하세요.",
|
||||
("충", "hour"): "앞날 계획이 흔들리기 쉬워요. 일정은 여유 있게 잡으세요.",
|
||||
("원진", ""): "사소한 오해가 생기기 쉬워요. 말투를 한 번 더 고르세요.",
|
||||
("형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("자형", ""): "생각이 많아 혼자 지치기 쉬워요. 오늘은 일찍 쉬세요.",
|
||||
("파", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("해", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("천간충", ""): "마음이 이리저리 흔들리기 쉬워요. 결정은 하나씩 하세요.",
|
||||
}
|
||||
# 비겁이 많은 원국에 비겁 날 (군겁쟁재)
|
||||
CROWDED_RIVALS = "같이 쓰는 돈·더치페이·빌려주는 돈은 오늘 정하지 마세요."
|
||||
|
||||
# 자리 → 좋은 흐름 (합이 들 때)
|
||||
GOOD_TEXT = {
|
||||
"day": "연인·배우자와 가까워지는 날이에요. 같이 보낼 시간을 잡아 보세요.",
|
||||
"month": "직장·팀 일이 잘 맞물려요. 협업 제안을 꺼내기 좋아요.",
|
||||
"year": "윗사람·바깥 사람에게 도움을 받기 쉬워요. 부탁할 일을 꺼내 보세요.",
|
||||
"hour": "아랫사람·후배와 사이가 좋아지는 날이에요.",
|
||||
}
|
||||
GOOD_RELATIONS = ("천간합", "육합", "삼합", "반합")
|
||||
|
||||
# 금전운 · 일운: 오늘 천간 십성 → 한 줄
|
||||
MONEY_TEXT = {
|
||||
"비견": "같이 쓰는 돈은 각자 내는 게 편한 날이에요.",
|
||||
"겁재": "빌려주거나 함께 투자하는 돈은 오늘 정하지 마세요.",
|
||||
"식신": "즐기는 데 쓰는 돈이 늘기 쉬워요. 한도를 먼저 정하세요.",
|
||||
"상관": "충동 구매가 생기기 쉬워요. 장바구니에 하루 두었다 사세요.",
|
||||
"편재": "뜻밖의 수입이나 할인 기회가 와요. 들어올 돈부터 챙기세요.",
|
||||
"정재": "가계부·적금처럼 돈을 정리하기 좋아요.",
|
||||
"편관": "갑자기 나갈 돈이 생기기 쉬워요. 여윳돈을 남겨 두세요.",
|
||||
"정관": "공과금·세금처럼 정해진 돈을 처리하기 좋아요.",
|
||||
"편인": "돈보다 정보가 남는 날이에요. 가격 비교를 해 두세요.",
|
||||
"정인": "배우는 데 쓰는 돈은 아깝지 않은 날이에요.",
|
||||
}
|
||||
WORK_TEXT = {
|
||||
"비견": "혼자 끝낼 수 있는 일에 집중하세요.",
|
||||
"겁재": "공동 작업은 역할과 몫을 먼저 나누세요.",
|
||||
"식신": "편하게 꺼낸 아이디어가 반응이 좋아요.",
|
||||
"상관": "발표·제안에 좋아요. 윗사람 앞에선 말을 한 번 고르세요.",
|
||||
"편재": "새 거래·새 사람과 일을 시작하기 좋아요.",
|
||||
"정재": "숫자를 맞추고 결과를 정리하는 일에 좋아요.",
|
||||
"편관": "어려운 일을 맡으면 인정받아요.",
|
||||
"정관": "보고·결재처럼 정해진 일을 처리하기 좋아요.",
|
||||
"편인": "자료 조사·기획처럼 준비하는 일에 좋아요.",
|
||||
"정인": "배우거나 도움을 청하면 일이 풀려요.",
|
||||
}
|
||||
|
||||
# 연애 기운이 드는 이유 → 한 줄
|
||||
LOVE_GOOD = {
|
||||
"도화": "사람들 눈에 잘 띄는 날이에요. 새 만남에 좋아요.",
|
||||
"홍염": "매력이 드러나는 날이에요.",
|
||||
"일지합": "연인과 가까워지는 날이에요.",
|
||||
"재성": "이성 기운이 들어오는 날이에요.",
|
||||
"관성": "이성 기운이 들어오는 날이에요.",
|
||||
}
|
||||
LOVE_BAD = {
|
||||
"원진": "서운한 말이 오가기 쉬워요.",
|
||||
"충": "다투기 쉬워요.",
|
||||
"형": "오해가 생기기 쉬워요.",
|
||||
"자형": "혼자 속앓이하기 쉬워요.",
|
||||
}
|
||||
|
||||
# 내 기운: 태어난 계절 × 원국의 결
|
||||
SCENES: dict[tuple[str, str], tuple[str, str]] = {
|
||||
("봄", "따뜻·마름"): ("봄햇살 기운", "새싹을 키우는 맑은 봄볕"),
|
||||
("봄", "따뜻·촉촉"): ("봄 아지랑이 기운", "따뜻하고 포근한 봄 오후"),
|
||||
("봄", "서늘·마름"): ("꽃샘바람 기운", "쌀쌀해도 꽃을 피우는 봄바람"),
|
||||
("봄", "서늘·촉촉"): ("봄비 기운", "새싹을 깨우는 촉촉한 이른 봄비"),
|
||||
("여름", "따뜻·마름"): ("한낮 땡볕 기운", "뜨겁고 환한 여름 한낮"),
|
||||
("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근하다 시원하게 쏟아지는 여름비"),
|
||||
("여름", "서늘·마름"): ("여름밤 바람 기운", "열기를 식혀 주는 여름밤 바람"),
|
||||
("여름", "서늘·촉촉"): ("장맛비 기운", "오래 촉촉하게 내리는 장맛비"),
|
||||
("가을", "따뜻·마름"): ("가을 햇살 기운", "곡식을 익히는 가을볕"),
|
||||
("가을", "따뜻·촉촉"): ("가을비 기운", "단풍을 적시는 포근한 가을비"),
|
||||
("가을", "서늘·마름"): ("소슬바람 기운", "선선하고 맑은 가을바람"),
|
||||
("가을", "서늘·촉촉"): ("새벽 서리 기운", "찬 이슬이 맺히는 늦가을 새벽"),
|
||||
("겨울", "따뜻·마름"): ("겨울 햇살 기운", "추위 속에 비치는 겨울볕"),
|
||||
("겨울", "따뜻·촉촉"): ("함박눈 기운", "포근하게 쌓이는 함박눈"),
|
||||
("겨울", "서늘·마름"): ("칼바람 기운", "맑고 매서운 겨울바람"),
|
||||
("겨울", "서늘·촉촉"): ("겨울 안개 기운", "차고 축축한 겨울 새벽 안개"),
|
||||
}
|
||||
SCENE_ICON = {"따뜻·마름": "sun", "따뜻·촉촉": "sun_cloud", "서늘·마름": "coldwind", "서늘·촉촉": "rain"}
|
||||
|
||||
# 조후에서 필요한 것 → 말
|
||||
NEED_WORD = {("temp", "warm"): "따뜻함", ("temp", "cool"): "시원함", ("moist", "dry"): "마른 공기", ("moist", "moist"): "촉촉함"}
|
||||
# 필요한 기운을 채우는 색 (오방색)
|
||||
NEED_COLOR = {("temp", "warm"): "빨강·주황", ("temp", "cool"): "검정·남색", ("moist", "dry"): "노랑·베이지", ("moist", "moist"): "초록·하늘색"}
|
||||
|
||||
|
||||
def clothes(feels_min: float) -> str:
|
||||
"""하루 중 가장 추운 체감으로 겉옷"""
|
||||
if feels_min <= 0:
|
||||
return "두꺼운 패딩"
|
||||
if feels_min <= 5:
|
||||
return "패딩이나 두꺼운 코트"
|
||||
if feels_min <= 10:
|
||||
return "코트나 두꺼운 니트"
|
||||
if feels_min <= 16:
|
||||
return "얇은 니트나 가디건"
|
||||
if feels_min <= 22:
|
||||
return "긴팔 한 장"
|
||||
return "반팔"
|
||||
|
||||
|
||||
def hour_word(h: int) -> str:
|
||||
"""오후 3시 전후 꼴"""
|
||||
word = "새벽" if h < 6 else "오전" if h < 12 else "오후"
|
||||
return f"{word} {h % 12 or 12}시"
|
||||
|
||||
|
||||
def josa(word: str, pair: str) -> str:
|
||||
"""받침 있으면 앞, 없으면 뒤: josa('공기', '이가') → '공기가'"""
|
||||
last = word[-1] if word else ""
|
||||
has = "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0
|
||||
return word + (pair[0] if has or not ("가" <= last <= "힣") else pair[1])
|
||||
|
||||
# 궁합: 친구 일간이 나에게 무슨 십성인지 → (제목, 설명)
|
||||
MATCH_TEXT = {
|
||||
("비견", "겁재"): ("친구처럼 대등한 사이", "좋아하는 게 비슷해 편한 사이예요. 정할 일은 차례를 나눠 정하세요."),
|
||||
("식신", "상관"): ("내가 챙겨 주는 사이", "내가 아이디어와 마음을 더 많이 주는 쪽이에요."),
|
||||
("편재", "정재"): ("내가 이끄는 사이", "내가 정하고 이끌 때 둘 다 편해지는 사이예요."),
|
||||
("편관", "정관"): ("나를 다잡아 주는 사이", "상대가 내 기준을 세워 주고 정리해 줘요."),
|
||||
("편인", "정인"): ("나를 키워 주는 사이", "상대가 나를 돕고 채워 주는 쪽이에요."),
|
||||
}
|
||||
MATCH_STEM_HAP = "일간끼리 합이라 처음부터 잘 끌리는 사이예요."
|
||||
MATCH_BRANCH = {"육합": "함께 있으면 편안한 사이예요.", "반합": "함께 있으면 편안한 사이예요.", "충": "생활 리듬이 달라 부딪히기 쉬워요. 약속은 미리 맞추세요.", "원진": "사소한 일에 서운해하기 쉬워요. 말로 먼저 풀어 주세요."}
|
||||
MATCH_CLIMATE_OK = "서로의 날씨를 맞춰 주는 사이예요. 함께 있으면 둘 다 균형이 잡혀요."
|
||||
MATCH_CLIMATE_SAME = "둘 다 {need} 필요한 기운이라, 그런 날씨에 함께 나가면 좋아요."
|
||||
|
||||
# 이달 · 올해: 그 간지 천간 십성 → (제목, 설명)
|
||||
MONTH_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("내 힘으로 서는 달", "혼자 해 온 일을 굳히기 좋은 달이에요. 새 일은 내 손으로 시작하세요."),
|
||||
"겁재": ("내 몫을 지키는 달", "돈 약속·공동 투자는 서두르지 말고, 내 몫부터 정해 두세요."),
|
||||
"식신": ("즐기며 채우는 달", "취미·맛집·여행처럼 나를 채우는 일에 시간을 쓰세요."),
|
||||
"상관": ("말과 재주가 빛나는 달", "발표·제안·창작처럼 밖으로 꺼내는 일이 잘 돼요."),
|
||||
"편재": ("기회가 들어오는 달", "새 제안과 사람이 많이 들어와요. 큰돈은 한 번 더 따져 보고 정하세요."),
|
||||
"정재": ("차곡차곡 모으는 달", "저축·정리·계약처럼 꼼꼼한 일이 잘 맞아요."),
|
||||
"편관": ("버티면 크는 달", "맡는 일이 무거워지지만 끝내면 크게 인정받아요."),
|
||||
"정관": ("믿음을 쌓는 달", "약속과 규칙을 지키면 자리와 평가가 올라가요."),
|
||||
"편인": ("생각을 다지는 달", "공부·기획·정리처럼 혼자 하는 일에 좋아요."),
|
||||
"정인": ("배우고 도움받는 달", "공부를 시작하거나 도움을 청하기 좋아요."),
|
||||
}
|
||||
YEAR_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("홀로서기의 해", "내 이름으로 하는 일을 시작하고 굳히기 좋은 해예요."),
|
||||
"겁재": ("내 몫을 지키는 해", "같이 하는 돈·사업은 몫을 분명히 나누세요."),
|
||||
"식신": ("즐기며 넓히는 해", "좋아하는 일을 키우고 몸을 챙기기 좋은 해예요."),
|
||||
"상관": ("재주를 드러내는 해", "창작·발표·이직처럼 나를 보여 주는 일이 잘 맞아요."),
|
||||
"편재": ("기회가 넓어지는 해", "새 사람·새 돈길이 열려요. 크게 벌이는 일은 나눠서 하세요."),
|
||||
"정재": ("차곡차곡 쌓는 해", "저축·자산 정리·안정된 수입을 만들기 좋은 해예요."),
|
||||
"편관": ("단단해지는 해", "책임이 커지는 해예요. 버틴 만큼 자리가 생겨요."),
|
||||
"정관": ("자리를 얻는 해", "승진·자격·약속처럼 제도 안의 일이 잘 풀려요."),
|
||||
"편인": ("나를 다시 짜는 해", "공부·기획·방향 전환을 준비하기 좋은 해예요."),
|
||||
"정인": ("배우고 받는 해", "공부·자격증, 도와줄 사람을 만나기 좋은 해예요."),
|
||||
}
|
||||
LOVE_RAINY = "비가 오니 실내 약속으로 잡으세요."
|
||||
@@ -143,15 +143,3 @@ async def test_instagram_requires_token(offline, admin_key, monkeypatch):
|
||||
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_latest_card_by_template_is_public(offline, admin_key):
|
||||
async with client() as c:
|
||||
assert "post_id" not in (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
|
||||
ootd = (await c.post("/v1/card", json=body(template="ootd", title="오늘 코디", publish=True), headers=admin_key)).json()
|
||||
await c.post("/v1/card", json=body(template="ootd", title="승인 대기 코디"), headers=admin_key)
|
||||
await c.post("/v1/card", json=body(publish=True), headers=admin_key)
|
||||
# 그 틀로 피드에 올린 것 중 가장 최근 (승인 대기·다른 틀은 빼고)
|
||||
latest = (await c.get("/v1/card/latest", params={"template": "ootd"})).json()
|
||||
assert latest["post_id"] == ootd["post_id"] and latest["published_at"]
|
||||
assert (await c.get("/v1/card/latest", params={"template": "../x"})).status_code == 422
|
||||
@@ -0,0 +1,83 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import update
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User
|
||||
from router.router import app
|
||||
from services.saju_service import window_text
|
||||
|
||||
REGION = "1144000000"
|
||||
BIRTH = {"region_code": REGION, "birth_date": "1995-03-14"}
|
||||
pytestmark = pytest.mark.usefixtures("no_bot_comments")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str, points: int = 0) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
if points:
|
||||
await DB_SESSION_MNG.execute_lambda_write(lambda s: s.execute(update(User).where(User.login_id == login_id).values(points=points)))
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def test_window_text():
|
||||
assert window_text((13, 14, 15)) == "오후 1~4시"
|
||||
assert window_text((11, 12, 13)) == "오전 11시~오후 2시"
|
||||
assert window_text((15,)) == "오후 3시 전후"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reading_for_anyone_gives_me_today_and_cards(offline):
|
||||
async with client() as c:
|
||||
r = (await c.post("/v1/saju/reading", json=BIRTH)).json()
|
||||
assert [p["stem"] + p["branch"] for p in r["me"]["pillars"]] == ["乙亥", "己卯", "甲辰"] and r["me"]["hour_known"] is False
|
||||
assert r["me"]["scene"].endswith("기운") and r["today"]["title"] and 0 <= r["today"]["score"] <= 100
|
||||
kinds = [x["kind"] for x in r["today"]["cards"]]
|
||||
assert "when" in kinds and "do" in kinds and "wear" in kinds
|
||||
# 로그인 안 하면 레벨로 여는 것은 모두 잠김, 내용도 안 옴
|
||||
assert r["logged_in"] is False and all(not x["unlocked"] for x in r["locks"])
|
||||
assert "week" not in r and "love" not in r and "money" not in r
|
||||
# 시각을 주면 시주까지
|
||||
r = (await c.post("/v1/saju/reading", json={**BIRTH, "birth_time": "07:30"})).json()
|
||||
assert len(r["me"]["pillars"]) == 4 and r["me"]["hour_known"] is True
|
||||
assert (await c.post("/v1/saju/reading", json={**BIRTH, "birth_date": "1899-12-31"})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post("/v1/saju/reading", json={**BIRTH, "birth_time": "25:00"})).status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_level_unlocks_sections_and_awards_once(offline):
|
||||
async with client() as c:
|
||||
h = await _login(c, "saju_01")
|
||||
r = (await c.post("/v1/saju/reading", json=BIRTH, headers=h)).json()
|
||||
assert r["logged_in"] is True and r["level"] == 1 and "week" not in r
|
||||
await c.post("/v1/saju/reading", json=BIRTH, headers=h)
|
||||
me = (await c.get("/v1/level/me", headers=h)).json()
|
||||
assert next(a["earned"] for a in me["today"] if a["action"] == "saju") == 10
|
||||
|
||||
h4 = await _login(c, "saju_04", points=200)
|
||||
r = (await c.post("/v1/saju/reading", json={**BIRTH, "gender": "male"}, headers=h4)).json()
|
||||
assert r["level"] == 4
|
||||
assert len(r["week"]) == 7 and sum(d["best"] for d in r["week"]) == 1
|
||||
assert r["money"] and r["work"] and all(isinstance(x, str) for x in r["money"]) and r["love"]["gender_known"] is True
|
||||
assert "month" not in r and "year" not in r
|
||||
unlocked = {x["key"]: x["unlocked"] for x in r["locks"]}
|
||||
assert unlocked["saju_love"] and not unlocked["saju_match"]
|
||||
|
||||
h7 = await _login(c, "saju_07", points=1000)
|
||||
r = (await c.post("/v1/saju/reading", json=BIRTH, headers=h7)).json()
|
||||
assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and len(r["year"]["months"]) == 3
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_match_needs_level_five(offline):
|
||||
body = {"region_code": REGION, "me": {"birth_date": "1995-03-14"}, "friend": {"birth_date": "1996-11-02"}}
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/saju/match", json=body)).json()["result"]["desc"] == "AUTH_REQUIRED"
|
||||
h = await _login(c, "match_01")
|
||||
assert (await c.post("/v1/saju/match", json=body, headers=h)).json()["result"]["desc"] == "LEVEL_REQUIRED"
|
||||
h5 = await _login(c, "match_05", points=400)
|
||||
m = (await c.post("/v1/saju/match", json=body, headers=h5)).json()
|
||||
assert m["title"].endswith("사이") and m["lines"] and 0 <= m["score"] <= 100 and m["day"]["weekday"] and m["friend_scene"].endswith("기운")
|
||||
@@ -0,0 +1,262 @@
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.saju.birth import to_solar_time
|
||||
from services.saju.climate import HourWeather, axis_effect, chart_climate, climate_match
|
||||
from services.saju.daily import SCORE_WEIGHTS, daily_facts
|
||||
from services.saju.pillars import day_pillar, make_chart
|
||||
from services.saju.rules import (
|
||||
branch_relations, branch_ten_god, chart_ten_gods, dohwa_of, hongyeom_of, stem_relations, ten_god, triple_relations,
|
||||
)
|
||||
from services.saju.solar_terms import JEOL, jeol_of_year, nutation_longitude, sun_apparent_longitude
|
||||
|
||||
EXAMPLE = make_chart(date(1995, 3, 14))
|
||||
|
||||
# 한국천문연구원(KASI) 발표 절입 시각 (KST, 월일시분). 순서: 소한 입춘 경칩 청명 입하 망종 소서 입추 백로 한로 입동 대설
|
||||
# - 2000~2028: KASI 특일 정보 API 24절기 조회(get24DivisionsInfo, kst 필드)
|
||||
# https://www.data.go.kr/data/15012690/openapi.do · http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/get24DivisionsInfo
|
||||
# - 2023·2024 는 KASI 역서 '24기와 기타 명절과 잡절' 표와도 같다
|
||||
# https://astro.kasi.re.kr/file/astro_almanac_pdf/20221209095149975.pdf (2023 역서 8쪽)
|
||||
# https://astro.kasi.re.kr/file/astro_almanac_pdf/20231023135218580.pdf (2024 역서 8쪽)
|
||||
# 2011 입동은 API 가 11-08 09:26 을 주지만 계산값 03:35 와 약 6시간 어긋나고 민간 만세력도 03:35 라 API 자료 오류로 보고 뺀다 (--------)
|
||||
KASI_JEOL = {
|
||||
2000: "01061001 02042140 03051543 04042032 05051350 06051759 07070414 08071403 09071659 10080838 11071148 12070437",
|
||||
2001: "01051549 02040329 03052133 04050224 05051945 06052354 07071007 08071952 09072246 10081425 11071737 12071029",
|
||||
2002: "01052144 02040924 03060328 04050818 05060137 06060545 07071556 08080139 09080431 10082009 11072322 12071614",
|
||||
2003: "01060328 02041505 03060905 04051352 05060710 06061120 07072136 08080724 09081020 10090201 11080513 12072205",
|
||||
2004: "01060919 02042056 03051456 04041943 05051302 06051714 07070331 08071320 09071613 10080749 11071059 12070349",
|
||||
2005: "01051503 02040243 03052045 04050134 05051853 06052302 07070917 08071903 09072157 10081333 11071642 12070933",
|
||||
2006: "01052047 02040827 03060229 04050715 05060031 06060437 07071451 08080041 09080339 10081921 11072235 12071527",
|
||||
2007: "01060240 02041418 03060818 04051305 05060620 06061027 07072042 08080631 09080929 10090111 11080424 12072114",
|
||||
2008: "01060825 02042000 03051359 04041846 05051203 06051612 07070227 08071216 09071514 10080657 11071010 12070302",
|
||||
2009: "01051414 02040150 03051947 04050034 05051751 06052159 07070813 08071801 09072058 10081240 11071556 12070852",
|
||||
2010: "01052009 02040748 03060146 04050630 05052344 06060349 07071402 08072349 09080245 10081826 11072142 12071438",
|
||||
2011: "01060155 02041333 03060730 04051212 05060523 06060927 07071942 08080533 09080834 10090019 -------- 12072029",
|
||||
2012: "01060744 02041922 03051321 04041805 05051120 06051526 07070141 08071130 09071429 10080612 11070926 12070219",
|
||||
2013: "01051334 02040113 03051915 04050002 05051718 06052123 07070734 08071720 09072016 10081158 11071514 12070808",
|
||||
2014: "01051924 02040703 03060102 04050547 05052259 06060303 07071315 08072302 09080201 10081747 11072107 12071404",
|
||||
2015: "01060120 02041258 03060656 04051139 05060452 06060858 07071912 08080501 09080759 10082343 11080258 12071953",
|
||||
2016: "01060708 02041846 03051243 04041727 05051042 06051448 07070103 08071053 09071351 10080533 11070848 12070141",
|
||||
2017: "01051256 02040034 03051833 04042317 05051631 06052037 07070651 08071640 09071939 10081122 11071438 12070733",
|
||||
2018: "01051849 02040628 03060028 04050513 05052225 06060229 07071242 08072231 09080130 10081715 11072032 12071326",
|
||||
2019: "01060039 02041214 03060610 04051051 05060403 06060806 07071821 08080413 09080717 10082306 11080224 12071918",
|
||||
2020: "01060630 02041803 03051157 04041638 05050951 06051358 07070014 08071006 09071308 10080455 11070814 12070109",
|
||||
2021: "01051223 02032359 03051754 04042235 05051547 06051952 07070605 08071554 09071853 10081039 11071359 12070657",
|
||||
2022: "01051814 02040551 03052344 04050420 05052126 06060126 07071138 08072129 09080032 10081622 11071945 12071246",
|
||||
2023: "01060005 02041143 03060536 04051013 05060319 06060718 07071731 08080323 09080627 10082216 11080136 12071833",
|
||||
2024: "01060549 02041727 03051123 04041602 05050910 06051310 07062320 08070909 09071211 10080400 11070720 12070017",
|
||||
2025: "01051133 02032310 03051707 04042149 05051457 06051857 07070505 08071452 09071752 10080941 11071304 12070605",
|
||||
2026: "01051723 02040502 03052259 04050340 05052049 06060048 07071057 08072043 09072341 10081529 11071852 12071153",
|
||||
2027: "01052310 02041046 03060440 04050917 05060225 06060626 07071637 08080227 09080528 10082117 11080039 12071738",
|
||||
2028: "01060455 02041631 03051025 04041503 05050812 06051216 07062230 08070821 09071122 10080309 11070627 12062325",
|
||||
}
|
||||
|
||||
|
||||
def test_sun_longitude_and_nutation_match_meeus_examples():
|
||||
# Meeus 예제 25.b (1992-10-13 0h TD): 시황경 199°54′21.818″, 예제 22.a·25.b 의 Δψ
|
||||
assert sun_apparent_longitude(2448908.5) == pytest.approx(199 + 54 / 60 + 21.818 / 3600, abs=0.5 / 3600)
|
||||
assert nutation_longitude(2446895.5) == pytest.approx(-3.788, abs=0.05)
|
||||
assert nutation_longitude(2448908.5) == pytest.approx(15.908, abs=0.05)
|
||||
|
||||
|
||||
def test_jeol_times_within_a_minute_of_kasi():
|
||||
worst = 0.0
|
||||
for year, row in KASI_JEOL.items():
|
||||
mine = jeol_of_year(year)
|
||||
for j, token in zip(mine, row.split()):
|
||||
if token.startswith("-"):
|
||||
continue
|
||||
kasi = datetime(year, int(token[:2]), int(token[2:4]), int(token[4:6]), int(token[6:]), tzinfo=KST)
|
||||
worst = max(worst, abs((j.at - kasi).total_seconds()))
|
||||
# KASI 는 분 단위로 발표하므로 반올림 오차 30초 + 계산 오차
|
||||
assert worst < 60
|
||||
|
||||
|
||||
def test_jeol_order_holds_for_whole_range():
|
||||
names = [name for name, _, _ in JEOL]
|
||||
prev = None
|
||||
for year in range(1900, 2101):
|
||||
terms = jeol_of_year(year)
|
||||
assert [t.name for t in terms] == names
|
||||
assert date(year, 2, 3) <= terms[1].at.date() <= date(year, 2, 5) # 입춘
|
||||
for t in terms:
|
||||
if prev:
|
||||
assert timedelta(days=29) < t.at - prev < timedelta(days=32)
|
||||
prev = t.at
|
||||
|
||||
|
||||
def test_day_pillars():
|
||||
assert day_pillar(date(1900, 1, 1)).name == "甲戌"
|
||||
assert day_pillar(date(2000, 1, 1)).name == "戊午"
|
||||
assert day_pillar(date(2024, 1, 1)).name == "甲子"
|
||||
assert day_pillar(date(2026, 10, 28)).name == "乙亥"
|
||||
assert day_pillar(date(2026, 10, 28)).ko == "을해"
|
||||
|
||||
|
||||
def test_example_chart_without_birth_time():
|
||||
c = EXAMPLE
|
||||
assert (c.year.name, c.month.name, c.day.name) == ("乙亥", "己卯", "甲辰")
|
||||
assert c.hour is None and not c.hour_known and c.solar is None
|
||||
assert c.jeol.name == "경칩" and not c.jeol_on_birth_day
|
||||
assert list(c.pillars()) == ["year", "month", "day"]
|
||||
# 2000-01-01 은 소한·입춘 전이라 전해 己卯년 子월
|
||||
c2000 = make_chart(date(2000, 1, 1))
|
||||
assert (c2000.year.name, c2000.month.name, c2000.day.name) == ("己卯", "丙子", "戊午")
|
||||
|
||||
|
||||
def test_ipchun_boundary_ten_minutes_each_side():
|
||||
# 2024 입춘 02-04 17:27 KST (KASI). 시계 시각 기준으로 10분 전·후
|
||||
before = make_chart(date(2024, 2, 4), time(17, 17))
|
||||
after = make_chart(date(2024, 2, 4), time(17, 37))
|
||||
assert (before.year.name, before.month.name) == ("癸卯", "乙丑")
|
||||
assert (after.year.name, after.month.name) == ("甲辰", "丙寅")
|
||||
# 2023 입춘 02-04 11:43
|
||||
assert make_chart(date(2023, 2, 4), time(11, 33)).year.name == "壬寅"
|
||||
assert make_chart(date(2023, 2, 4), time(11, 53)).year.name == "癸卯"
|
||||
# 시간을 모르는 절입일은 표시
|
||||
assert make_chart(date(2024, 2, 4)).jeol_on_birth_day
|
||||
|
||||
|
||||
def test_hour_pillars_and_zi_rule():
|
||||
# 서울은 지방평균시가 약 32분 늦다: 10:00 → 09:28 巳시, 甲일 巳시 = 己巳
|
||||
c = make_chart(date(1995, 3, 14), time(10, 0))
|
||||
assert round(c.solar.correction_min) == -32 and c.hour.name == "己巳"
|
||||
assert make_chart(date(1995, 3, 14), time(13, 40)).hour.name == "辛未" # 13:08 未시
|
||||
# 경도 135 (보정 0) 에서 23:30: 자정 기준이면 날은 그대로 甲辰, 시주는 다음 자시 丙子
|
||||
late = make_chart(date(1995, 3, 14), time(23, 30), longitude=135)
|
||||
assert (late.day.name, late.hour.name) == ("甲辰", "丙子")
|
||||
# 23시 기준이면 날이 乙巳 로 넘어가고 시주는 같다
|
||||
late23 = make_chart(date(1995, 3, 14), time(23, 30), longitude=135, zi_rule="23h")
|
||||
assert (late23.day.name, late23.hour.name) == ("乙巳", "丙子")
|
||||
# 서울 23:30 은 지방평균시 22:58 이라 아직 亥시
|
||||
assert make_chart(date(1995, 3, 14), time(23, 30)).hour.name == "乙亥"
|
||||
# 서울 00:10 은 지방평균시로 전날 23:38 → 전날 癸卯일, 시주 甲子
|
||||
early = make_chart(date(1995, 3, 14), time(0, 10))
|
||||
assert (early.day.name, early.hour.name) == ("癸卯", "甲子")
|
||||
|
||||
|
||||
def test_dst_is_removed():
|
||||
# 1988-05-08 02:00 ~ 10-09 03:00 서머타임. 시계 10:00 = 표준시 09:00 → 서울 지방평균시 08:28 辰시
|
||||
s = to_solar_time(date(1988, 7, 1), time(10, 0))
|
||||
assert s.dst and s.utc_offset_min == 600 and round(s.correction_min) == -92
|
||||
assert make_chart(date(1988, 7, 1), time(10, 0)).hour.branch == "辰"
|
||||
assert not to_solar_time(date(1988, 11, 1), time(10, 0)).dst
|
||||
assert not to_solar_time(date(1987, 5, 10), time(1, 59)).dst and to_solar_time(date(1987, 5, 10), time(3, 0)).dst
|
||||
# 1954-03-21 ~ 1961-08-09 표준시는 UTC+8:30, 그 위에 서머타임
|
||||
s58 = to_solar_time(date(1958, 6, 15), time(12, 0))
|
||||
assert s58.dst and s58.utc_offset_min == 570 and round(s58.correction_min) == -62
|
||||
assert to_solar_time(date(1958, 12, 1), time(12, 0)).utc_offset_min == 510
|
||||
|
||||
|
||||
def test_out_of_range_dates_are_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
make_chart(date(1899, 12, 31))
|
||||
with pytest.raises(ValueError):
|
||||
make_chart(date(2101, 1, 1))
|
||||
|
||||
|
||||
def test_ten_gods():
|
||||
expected = {"甲": "비견", "乙": "겁재", "丙": "식신", "丁": "상관", "戊": "편재", "己": "정재", "庚": "편관", "辛": "정관", "壬": "편인", "癸": "정인"}
|
||||
assert {s: ten_god("甲", s) for s in expected} == expected
|
||||
assert branch_ten_god("甲", "亥") == "편인" # 정기 壬
|
||||
assert branch_ten_god("甲", "子") == "정인" # 정기 癸
|
||||
assert chart_ten_gods("甲", EXAMPLE.pillars())["month"] == {"stem": "정재", "branch": "겁재"}
|
||||
|
||||
|
||||
def _kinds(rels):
|
||||
return {r.kind for r in rels}
|
||||
|
||||
|
||||
def test_stem_and_branch_relations():
|
||||
assert stem_relations("甲", "己")[0].element == "土"
|
||||
assert _kinds(stem_relations("庚", "甲")) == {"천간충"}
|
||||
assert _kinds(stem_relations("甲", "乙")) == set()
|
||||
assert branch_relations("子", "丑")[0].kind == "육합"
|
||||
assert _kinds(branch_relations("亥", "卯")) == {"반합"}
|
||||
assert _kinds(branch_relations("卯", "未")) == {"반합"}
|
||||
assert _kinds(branch_relations("亥", "未")) == set() # 생지+묘지는 반합으로 보지 않음
|
||||
assert _kinds(branch_relations("午", "子")) == {"충"}
|
||||
assert _kinds(branch_relations("寅", "巳")) == {"형", "해"}
|
||||
assert _kinds(branch_relations("巳", "申")) == {"육합", "형", "파"}
|
||||
assert branch_relations("子", "卯")[0].group == "子卯"
|
||||
assert _kinds(branch_relations("午", "午")) == {"자형"}
|
||||
assert _kinds(branch_relations("子", "子")) == set()
|
||||
assert _kinds(branch_relations("子", "未")) == {"해", "원진"}
|
||||
assert _kinds(branch_relations("辰", "亥")) == {"원진"}
|
||||
assert _kinds(branch_relations("子", "酉")) == {"파"}
|
||||
assert _kinds(triple_relations(["申", "子", "辰"])) == {"삼합"}
|
||||
assert _kinds(triple_relations(["丑", "戌", "未"])) == {"삼형"}
|
||||
|
||||
|
||||
def test_dohwa_and_hongyeom_tables():
|
||||
assert dohwa_of("亥") == "子" and dohwa_of("辰") == "酉" and dohwa_of("午") == "卯" and dohwa_of("丑") == "午"
|
||||
assert hongyeom_of("甲") == hongyeom_of("乙") == "午"
|
||||
assert hongyeom_of("丁") == "未" and hongyeom_of("癸") == "申"
|
||||
|
||||
|
||||
def test_daily_facts_for_example_chart():
|
||||
f = daily_facts(EXAMPLE, date(2026, 10, 28))
|
||||
assert f.pillar.name == "乙亥"
|
||||
assert f.stem_ten_god == "겁재"
|
||||
assert f.branch_main_stem == "壬" and f.branch_ten_god == "편인"
|
||||
found = {(i.position, i.relation.kind, i.relation.chars) for i in f.interactions}
|
||||
assert found == {("month", "반합", "亥卯"), ("day", "원진", "亥辰"), ("year", "자형", "亥亥")}
|
||||
assert {i.palace for i in f.interactions} == {"부모·직장", "나·배우자", "조상·사회"}
|
||||
assert f.dohwa == () and not f.hongyeom
|
||||
# 성별을 모르면 일지 관계만 연애 사실로
|
||||
assert f.love.relevant and f.love.reasons == ({"kind": "일지", "relation": "원진", "chars": "亥辰"},)
|
||||
assert f.score == round(SCORE_WEIGHTS["base"] + sum(c.points for c in f.contributions))
|
||||
assert {c.fact for c in f.contributions} == {"겁재", "편인", "반합", "원진", "자형"}
|
||||
|
||||
|
||||
def test_daily_dohwa_hongyeom_and_love_by_gender():
|
||||
dohwa_day = daily_facts(EXAMPLE, date(2026, 10, 29)) # 丙子: 연지 亥 의 도화
|
||||
assert dohwa_day.pillar.name == "丙子" and dohwa_day.dohwa == ({"basis": "year", "branch": "子"},)
|
||||
assert any(c.fact == "도화" for c in dohwa_day.contributions)
|
||||
hongyeom_day = daily_facts(EXAMPLE, date(2026, 11, 4)) # 壬午: 甲 일간의 홍염
|
||||
assert hongyeom_day.pillar.name == "壬午" and hongyeom_day.hongyeom
|
||||
wealth_day = date(2026, 10, 31) # 戊寅: 甲 에게 편재
|
||||
assert daily_facts(EXAMPLE, wealth_day).pillar.name == "戊寅"
|
||||
male = daily_facts(EXAMPLE, wealth_day, gender="male").love
|
||||
assert male.relevant and male.reasons[0] == {"kind": "재성", "part": "stem", "ten_god": "편재"}
|
||||
assert not daily_facts(EXAMPLE, wealth_day, gender="female").love.relevant
|
||||
assert not daily_facts(EXAMPLE, wealth_day).love.relevant
|
||||
officer = daily_facts(EXAMPLE, date(2026, 11, 2), gender="female") # 庚辰: 편관, 일지 辰辰
|
||||
assert officer.pillar.name == "庚辰" and {"kind": "관성", "part": "stem", "ten_god": "편관"} in officer.love.reasons
|
||||
|
||||
|
||||
def test_daily_samhap_completed_by_today():
|
||||
# 원국 庚申 甲申 丙辰 에 오늘 丙子 가 오면 申子辰 삼합. 같은 묶음 반합은 사실로는 남기고 점수에서는 겹쳐 세지 않는다
|
||||
c = make_chart(date(1980, 8, 11))
|
||||
assert (c.year.name, c.month.name, c.day.name) == ("庚申", "甲申", "丙辰")
|
||||
f = daily_facts(c, date(2026, 10, 29))
|
||||
samhap = [i for i in f.interactions if i.relation.kind == "삼합"]
|
||||
assert len(samhap) == 1 and samhap[0].relation.group == "申子辰" and samhap[0].positions == ("year", "month", "day")
|
||||
assert sum(i.relation.kind == "반합" for i in f.interactions) == 3
|
||||
assert [c.fact for c in f.contributions] == ["비견", "정관", "삼합"]
|
||||
|
||||
|
||||
def test_example_chart_climate_and_best_window():
|
||||
climate = chart_climate(EXAMPLE)
|
||||
assert climate.label == "서늘·촉촉" and climate.season == "봄"
|
||||
assert climate.need == {"temp": "warm", "moist": "dry"}
|
||||
feels = [0, 0, -1, -1, 0, 1, 2, 3, 5, 7, 9, 11, 12, 13, 13, 13, 11, 9, 7, 5, 4, 3, 2, 1]
|
||||
weather = [HourWeather(h, feels[h], 45 if h < 13 else 40 if h <= 15 else 50, False) for h in range(24)]
|
||||
m = climate_match(EXAMPLE, weather)
|
||||
assert m.best_hours == (13, 14, 15)
|
||||
scores = {h.hour: h.score for h in m.hours}
|
||||
assert scores[14] > scores[6]
|
||||
assert 0 <= m.score <= 100
|
||||
temp, moist = m.reasons
|
||||
assert temp["axis"] == "temp" and temp["need"] == "warm"
|
||||
assert moist == {"axis": "moist", "need": "dry", "effect": "dries", "helps": True, "points": moist["points"], "weather": "체감 13°, 습도 40%"}
|
||||
|
||||
|
||||
def test_balanced_axis_prefers_mild_weather_and_rain_moistens():
|
||||
assert axis_effect(0.0, 0.0) > axis_effect(0.0, 0.6) and axis_effect(0.0, 0.0) > axis_effect(0.0, -0.6)
|
||||
assert axis_effect(-0.4, 0.8) > axis_effect(-0.4, 0.0) > axis_effect(-0.4, -0.8)
|
||||
dry = climate_match(EXAMPLE, [HourWeather(12, 18, 40, False)])
|
||||
wet = climate_match(EXAMPLE, [HourWeather(12, 18, 40, True)])
|
||||
assert wet.hours[0].weather["moist"] >= 0.8 and wet.score < dry.score
|
||||
Reference in new issue
Block a user