Files
o2o-weather/backend/services/saju_service.py
T

508 lines
25 KiB
Python

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.user_crud import UserCRUD
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, best_window, chart_climate, climate_match
from services.saju.daily import SCORE_WEIGHTS, DailyFacts, Interaction, daily_facts, interactions, score as pillar_score
from services.saju.ganji import ko, main_stem
from services.saju.pillars import Chart, Pillar, make_chart
from services.saju.rules import WEALTH, 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 # 일간을 뺀 원국 글자 중 비겁이 이만큼 이상이고 재성이 있으면 비겁 날 돈 조심 (군겁쟁재)
PICK_MIN = 60 # 앞으로 7일 중 '좋은 날'로 고르려면 그날 점수가 이 이상
COMFY_C = (5, 30) # 외출 시간으로 권할 체감 온도 범위 (조후로는 맞아도 너무 춥거나 더운 때는 뺀다)
NOTES_MAX = 2 # 이달·올해 근거 줄 수
_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[list[str]] = None
work: Optional[list[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
chars = [p.stem for pos, p in _pillars(chart).items() if pos != "day"] + [main_stem(p.branch) for p in _pillars(chart).values()]
gods = [ten_god(me, c) for c in chars]
return sum(g in RIVALS for g in gods) >= CROWDED and any(g in WEALTH for g in gods)
def why_words(facts: DailyFacts) -> list[str]:
"""점수를 가장 크게 움직인 사실 셋을 쉬운 말로, 올렸는지(↑) 내렸는지(↓)"""
rels = {(i.relation.kind, i.relation.chars, i.position): i for i in facts.interactions}
out = []
for c in sorted(facts.contributions, key=lambda c: -abs(c.points))[:3]:
arrow = "↑" if c.points >= 0 else "↓"
if c.fact in T.GOD_PLAIN:
line = f"오늘 들어오는 기운: {T.GOD_PLAIN[c.fact]}({c.fact})"
elif c.fact == "도화":
line = "사람들 눈에 띄는 날(도화)"
elif c.fact == "홍염":
line = "매력이 드러나는 날(홍염)"
else:
i = rels.get((c.fact, c.chars, c.position))
line = _rel(i) if i else c.fact
out.append(f"{line} {arrow}")
return out
def _rel(i: Interaction) -> str:
"""'태어난 날과 오늘이 부딪혀요(일지 사·해 충)'. 일간과의 관계는 '나와 오늘이 …'"""
chars = "·".join(ko(ch) for ch in i.relation.chars)
if i.part == "stem" and i.position == "day":
who, term = "나와", "일간"
else:
positions = i.positions or (i.position,)
who = "·".join(T.PLACE_WORD[p].removeprefix("태어난 ") for p in positions)
who = f"태어난 {who}과" if who[-1] in "날달" else f"태어난 {who}와"
term = "".join(T.PLACE_TERM[p] for p in positions) + ("간" if i.part == "stem" else "지")
return f"{who} 오늘이 {T.REL_WORD[i.relation.kind]}({term} {chars} {i.relation.kind})"
def _weight(i: Interaction) -> float:
"""관계 하나가 점수에 주는 무게 (자리 비중까지)"""
share = 1.0 if i.positions else SCORE_WEIGHTS["position_share"][i.position]
return SCORE_WEIGHTS["relation"][i.relation.kind] * share
def _bad(facts: DailyFacts) -> list[Interaction]:
"""조심할 관계, 점수를 많이 깎는 것부터"""
kinds = {k for k, _ in T.AVOID_TEXT}
return sorted((i for i in facts.interactions if i.relation.kind in kinds), key=_weight)
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(T.CROWDED_WHY.format(god=facts.stem_ten_god))
for i in _bad(facts):
key = (i.relation.kind, i.position if i.part == "branch" else "")
body = T.AVOID_TEXT.get(key) 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]:
"""가장 무거운 합 하나. 같은 자리에 조심할 관계도 있으면 그 자리는 뺀다"""
bad_at = {i.position for i in _bad(facts)}
good = sorted((i for i in facts.interactions if i.relation.kind in T.GOOD_RELATIONS and i.position not in bad_at), key=lambda i: -_weight(i))
if not good:
return None
i = good[0]
body = T.STEM_GOOD if i.part == "stem" and i.position == "day" else T.GOOD_TEXT[i.position]
return Card(kind="good", title="오늘 좋은 흐름", body=body, sub=_rel(i))
def when_card(r: DayReading, needs: list[tuple[str, str]]) -> 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))
walk = "산책·외출은 이때 하세요."
body = f"내 기운엔 {T.need_phrase(needs)}가 좋아요. 오늘 중엔 이때가 가장 알맞아요. {walk}" if needs else f"오늘 중 날씨가 가장 편안한 때예요. {walk}"
sub = f"{T.hour_word(h)} {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)
body = f"가장 쌀쌀할 때 체감 {round(feels)}°예요. {T.josa(T.clothes(feels), '을를')} 챙기세요."
if needs:
body += f"\n포인트 색은 {T.NEED_COLOR[needs[0]]} 해 보세요."
return Card(kind="wear", title="오늘 입을 옷", body=body, sub=f"오늘 가기 좋은 곳: {place}" if place else None)
def _wet(r: DayReading) -> bool:
return r.weather is not None and r.weather.icon in ("rain", "snow")
def love_week(chart: Chart, week: list[DayReading], gender: Optional[Gender]) -> dict:
"""앞으로 7일 중 연애 기운이 좋은 날과 조심할 날. 연인 자리(일지)가 부딪히는 날은 좋은 날에서 빼고, 비·눈 오는 날은 뒤로"""
goods, bads = [], []
for r in week:
kinds, clash = set(), None
for x in r.facts.love.reasons:
k = x["kind"]
if k == "일지":
rel = x.get("relation")
if rel in ("육합", "반합", "삼합"):
kinds.add("일지합")
else:
clash = rel
else:
kinds.add(k)
if clash:
bads.append((r, clash))
continue
good = [k for k in ("도화", "홍염", "일지합", "재성", "관성") if k in kinds]
if good:
goods.append((r, good))
goods.sort(key=lambda g: (_wet(g[0]), -g[0].score))
out: dict = {"gender": gender}
if goods:
r, kinds = goods[0]
body = T.LOVE_GOOD[kinds[0]][0] + (" " + T.LOVE_WET.format(word=r.weather.word) if _wet(r) else "")
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": body, "why": " · ".join(T.LOVE_GOOD[k][1] for k in kinds)}
if bads:
r, rel = min(bads, key=lambda b: b[0].score)
out["caution"] = {"day": r.day, "weekday": _WEEKDAY[r.day.weekday()], "body": T.LOVE_BAD[rel], "why": T.LOVE_BAD_WHY[rel]}
return out
MONEY_GOOD, MONEY_BAD, WORK_GOOD = ("편재", "정재"), ("비견", "겁재"), ("정관", "정인", "상관")
def day_word(d: date, today: Optional[date] = None) -> str:
"""'10/31(토)', 오늘이면 '오늘(10/28)'"""
return f"오늘({d.month}/{d.day})" if d == today else f"{d.month}/{d.day}({_WEEKDAY[d.weekday()]})"
def money_work(week: list[DayReading]) -> tuple[list[str], list[str]]:
"""금전·일: 앞으로 7일 중 그 십성이 드는 날에서 점수로 고른다. 좋은 날은 점수가 PICK_MIN 이상일 때만"""
def best(gods: tuple[str, ...]) -> Optional[DayReading]:
days = [r for r in week if r.facts.stem_ten_god in gods and r.score >= PICK_MIN]
return max(days, key=lambda r: r.score) if days else None
worst = min((r for r in week if r.facts.stem_ten_god in MONEY_BAD), key=lambda r: r.score, default=None)
money = [T.MONEY_GOOD.format(day=day_word(g.day, week[0].day))] if (g := best(MONEY_GOOD)) else [T.MONEY_NONE]
if worst is not None:
money.append(T.MONEY_BAD.format(day=day_word(worst.day, week[0].day)))
work = [T.WORK_GOOD.format(day=day_word(w.day, week[0].day))] if (w := best(WORK_GOOD)) else [T.WORK_NONE]
return money, work
def year_months(chart: Chart, year: int, start: int = 1) -> list[int]:
"""그해 start 월부터 남은 달(절 기준) 중 내 사주와 잘 맞는 달. 셋, 남은 달이 적으면 그 절반 (달 번호는 그 절이 드는 양력 달)"""
scored = []
for m in range(start, 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)[: min(3, max(1, len(scored) // 2))])
def period(chart: Chart, p: Pillar, unit: str, subject: str) -> dict:
"""이달·올해: 그 간지 천간 십성 + 원국과의 관계. subject 는 근거 줄의 주어 ('이번 달이', '올해가')"""
god = ten_god(chart.day.stem, p.stem)
title, body = (T.MONTH_TEXT if unit == "달" else T.YEAR_TEXT)[god]
found = sorted(interactions(chart, p), key=lambda i: -abs(_weight(i)))[:NOTES_MAX]
return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i).replace("오늘이", subject) for i in found]}
@dataclass
class Match:
score: int
title: str
lines: list[str]
day: Optional[DayReading] # 앞으로 7일 중 둘 다 점수가 괜찮고 비·눈이 없는 날
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": 5}
_GROUPS = (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource"))
def _group(god: str) -> str:
return next(g for k, g in _GROUPS if god in k)
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)
back = ten_god(friend.day.stem, me.day.stem)
score, lines = MATCH_SCORE["base"] + (MATCH_SCORE[_group(god)] + MATCH_SCORE[_group(back)]) / 2, [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 and T.MATCH_BRANCH[r.kind] not in lines:
score += MATCH_SCORE["branch_hap"] if r.kind in ("육합", "반합") else MATCH_SCORE["branch_bad"]
lines.append(T.MATCH_BRANCH[r.kind])
a, b = chart_climate(me), chart_climate(friend)
opposite = {"temp": {"warm": "cool", "cool": "warm"}, "moist": {"dry": "moist", "moist": "dry"}}
fills = [ax for ax in ("temp", "moist") if opposite[ax].get(a.need[ax]) == b.need[ax]]
shared = [(ax, a.need[ax]) for ax in ("temp", "moist") if a.need[ax] != "mild" and a.need[ax] == b.need[ax]]
if fills:
score += MATCH_SCORE["climate_ok"] * len(fills)
lines.append(T.MATCH_CLIMATE_OK.format(axis=T.MATCH_CLIMATE_AXIS[fills[0]]))
elif shared:
lines.append(T.MATCH_CLIMATE_SAME.format(need=T.need_phrase(shared)))
both = [(x, y) for x, y in zip(my_days, friend_days) if not _wet(x) and min(x.score, y.score) >= PICK_MIN]
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, round(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), users: UserCRUD = Depends(UserCRUD),
) -> None:
self.regions, self.weather, self.week_crud, self.weather_service, self.week, self.users = regions, weather, week_crud, weather_service, week, users
async def save_birth(self, user: User, birth_date: date, birth_time: Optional[time], place: Optional[str], gender: Optional[Gender]) -> tuple[ErrorType, Optional[User]]:
"""내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)"""
if not date(1900, 1, 1) <= birth_date <= now_kst().date():
return ErrorType.INVALID_INPUT, None
values = {"birth_date": birth_date, "birth_time": birth_time, "birth_place": place, "gender": gender}
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.users.update(s, user.user_id, values))
async def clear_birth(self, user: User) -> tuple[ErrorType, Optional[User]]:
values = {"birth_date": None, "birth_time": None, "birth_place": None, "gender": None}
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.users.update(s, user.user_id, values))
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=total_score(facts.score, None))
m = climate_match(chart, w.hours)
feels = {x.hour: x.feels_c for x in w.hours}
comfy = {x.hour: x.score for x in m.hours if COMFY_C[0] <= feels.get(x.hour, COMFY_C[0]) <= COMFY_C[1]}
best = best_window(comfy) or m.best_hours
return DayReading(day=d, facts=facts, weather=w, climate_score=m.score, best_hours=best, 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, "해", "올해가" if y == today.year else f"{y}년이"), "year": y, "preview": y != today.year, "months": year_months(chart, y, today.month if y == today.year else 1)}
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]
god = r0.facts.stem_ten_god
do = Card(kind="do", title="오늘 할 것", body=todo, sub=f"오늘 들어오는 기운: {T.GOD_PLAIN[god]}({god})")
cards = [c for c in (when_card(r0, needs), do, 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_phrase(needs)] if needs else [], 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,
)