feat: 구름 합치기 GA4 이벤트 — game_start(첫 그림)·game_round(라운드 깸)·game_over(넘침)
This commit is contained in:
1 parent
63b4fa74fe
commit
df3fba720c
26 files changed
+330
-900
No files matched your search
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
from datetime import date, datetime, time
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, Time, func
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
@@ -364,10 +364,6 @@ class User(Base):
|
||||
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
points: Mapped[int] = mapped_column(Integer, default=0)
|
||||
birth_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
birth_time: Mapped[Optional[time]] = mapped_column(Time, nullable=True)
|
||||
birth_place: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
gender: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
@@ -51,9 +51,10 @@ class Settings(BaseSettings):
|
||||
azure_blob_base_url: str = ""
|
||||
azure_blob_sas_token: str = ""
|
||||
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 Data API 로(공개·퍼가기 허용·3분 이하), 없으면 채널 쇼츠 RSS 로 받는다
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
|
||||
youtube_api_key: str = ""
|
||||
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
|
||||
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
@@ -330,11 +330,6 @@ CREATE TABLE IF NOT EXISTS public.point_log (
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_point_log ON public.point_log (user_id, day, action, ref);
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS points INTEGER NOT NULL DEFAULT 0; -- 모은 각 총량 (point_log 합)
|
||||
-- 날씨 사주에 넣은 생년월일. 로그인한 사람만, 저장하면 어느 기기에서든 바로 본다. 탈퇴하면 계정과 함께 지워진다
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_date DATE NULL;
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_time TIME NULL; -- 모르면 NULL
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS birth_place VARCHAR(20) NULL; -- 태어난 곳 키 (frontend sajuBirth.ts BIRTH_PLACES)
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS gender VARCHAR(10) NULL; -- male·female. 연애운에서 이성 인연을 볼 때만 쓴다
|
||||
|
||||
-- 오늘 한 장: 로그인한 사람이 그날 뽑은 카드 (하루 한 장, 로그인 안 하면 기기에만 남는다)
|
||||
CREATE TABLE IF NOT EXISTS public.fortune_draw (
|
||||
|
||||
@@ -14,21 +14,6 @@ class Req_Saju(Req_WebPacketProtocol):
|
||||
gender: Optional[Literal["male", "female"]] = Field(None, description="연애운에서 이성 기운을 볼 때만")
|
||||
|
||||
|
||||
class SajuSavedBirth(WebPacketProtocol):
|
||||
birth_date: date
|
||||
birth_time: Optional[str] = Field(None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$", description="HH:MM (모르면 없음)")
|
||||
place: Optional[str] = Field(None, pattern=r"^[a-z]{2,20}$", description="태어난 곳 키 (seoul 등)")
|
||||
gender: Optional[Literal["male", "female"]] = None
|
||||
|
||||
|
||||
class Req_SajuBirth(Req_WebPacketProtocol, SajuSavedBirth):
|
||||
pass
|
||||
|
||||
|
||||
class Res_SajuBirth(Res_WebPacketProtocol):
|
||||
birth: Optional[SajuSavedBirth] = None
|
||||
|
||||
|
||||
class SajuPillar(WebPacketProtocol):
|
||||
position: str = Field(description="year·month·day·hour")
|
||||
stem: str
|
||||
|
||||
@@ -3,11 +3,11 @@ from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
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_SajuBirth, Req_SajuMatch, Res_Saju, Res_SajuBirth, SajuSavedBirth, Res_SajuMatch, SajuBirth, SajuCard, SajuDay, SajuLock, SajuLove, SajuLoveDay, SajuMe, SajuPeriod, SajuPillar, SajuToday
|
||||
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
|
||||
@@ -55,31 +55,6 @@ async def reading(req: Req_Saju, user: Optional[User] = Depends(optional_user),
|
||||
return Res_Saju(result=error_info(err)) if err is not ErrorType.SUCCESS or r is None else _res(r)
|
||||
|
||||
|
||||
def _saved(u: Optional[User]) -> Res_SajuBirth:
|
||||
if u is None or u.birth_date is None:
|
||||
return Res_SajuBirth()
|
||||
t = f"{u.birth_time:%H:%M}" if u.birth_time else None
|
||||
return Res_SajuBirth(birth=SajuSavedBirth(birth_date=u.birth_date, birth_time=t, place=u.birth_place, gender=u.gender))
|
||||
|
||||
|
||||
@router.get("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="계정에 저장한 내 생년월일 (없으면 birth 없음)")
|
||||
async def get_birth(user: User = Depends(current_user)) -> Res_SajuBirth:
|
||||
return _saved(user)
|
||||
|
||||
|
||||
@router.put("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="내 생년월일을 계정에 저장 (날씨 사주를 어느 기기에서든 바로 본다)")
|
||||
async def put_birth(req: Req_SajuBirth, user: User = Depends(current_user), service: SajuService = Depends()) -> Res_SajuBirth:
|
||||
t = time(*map(int, req.birth_time.split(":"))) if req.birth_time else None
|
||||
err, u = await service.save_birth(user, req.birth_date, t, req.place, req.gender)
|
||||
return Res_SajuBirth(result=error_info(err)) if err is not ErrorType.SUCCESS or u is None else _saved(u)
|
||||
|
||||
|
||||
@router.delete("/birth", response_model=Res_SajuBirth, response_model_exclude_none=True, summary="계정에 저장한 내 생년월일 지우기")
|
||||
async def delete_birth(user: User = Depends(current_user), service: SajuService = Depends()) -> Res_SajuBirth:
|
||||
err, _ = await service.clear_birth(user)
|
||||
return Res_SajuBirth(result=error_info(err))
|
||||
|
||||
|
||||
def _birth(b: SajuBirth) -> tuple:
|
||||
return b.birth_date, time(*map(int, b.birth_time.split(":"))) if b.birth_time else None, b.longitude
|
||||
|
||||
|
||||
Vendored
-19
@@ -1,6 +1,4 @@
|
||||
import asyncio
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
@@ -9,9 +7,6 @@ import httpx
|
||||
API_URL = "https://www.googleapis.com/youtube/v3"
|
||||
# 키 없이 영상 제목만 받을 때
|
||||
OEMBED_URL = "https://www.youtube.com/oembed"
|
||||
# 키 없이 채널 쇼츠 목록을 받을 때: 채널 ID의 UC 를 UUSH 로 바꾼 재생목록이 그 채널의 쇼츠만 모은 목록이다
|
||||
FEED_URL = "https://www.youtube.com/feeds/videos.xml"
|
||||
_NS = {"a": "http://www.w3.org/2005/Atom", "yt": "http://www.youtube.com/xml/schemas/2015"}
|
||||
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
|
||||
|
||||
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
|
||||
@@ -58,17 +53,3 @@ async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]
|
||||
return None
|
||||
res.raise_for_status()
|
||||
return res.json().get("title")
|
||||
|
||||
|
||||
async def feed_shorts(client: httpx.AsyncClient, channel_id: str, limit: int) -> list[dict]:
|
||||
"""키 없이 채널의 공개 쇼츠 [{id, title, published}], 최신순. 퍼가기를 막은 영상은 뺀다."""
|
||||
res = await client.get(FEED_URL, params={"playlist_id": "UUSH" + channel_id.removeprefix("UC")})
|
||||
res.raise_for_status()
|
||||
root = ET.fromstring(res.text)
|
||||
entries = [
|
||||
{"id": e.findtext("yt:videoId", namespaces=_NS), "title": e.findtext("a:title", namespaces=_NS), "published": e.findtext("a:published", namespaces=_NS)}
|
||||
for e in root.findall("a:entry", _NS)
|
||||
]
|
||||
entries = sorted((e for e in entries if e["id"] and e["title"]), key=lambda e: e["published"] or "", reverse=True)[:limit]
|
||||
embeddable = await asyncio.gather(*(video_title(client, e["id"]) for e in entries))
|
||||
return [e for e, ok in zip(entries, embeddable) if ok]
|
||||
@@ -23,7 +23,7 @@ LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바
|
||||
ACTIONS: dict[str, tuple[int, int, str]] = {
|
||||
"attend": (10, 10, "출석"),
|
||||
"tarot": (10, 10, "오늘 타로 뽑기"),
|
||||
"saju": (10, 10, "날씨 사주 보기"),
|
||||
"saju": (10, 10, "날씨 사주 오늘 기운"),
|
||||
"react": (5, 10, "좋아요·댓글"),
|
||||
"talk": (20, 20, "동네 이야기 글쓰기"),
|
||||
"checkin": (10, 10, "저녁 체크인"),
|
||||
@@ -40,7 +40,7 @@ STREAK_LOOKBACK = 60
|
||||
|
||||
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
|
||||
UNLOCKS: dict[int, list[tuple[str, str]]] = {
|
||||
2: [("saju_week", "날씨 사주 7일 흐름")],
|
||||
2: [("saju_week", "날씨 사주 이번 주 흐름")],
|
||||
3: [("saju_money", "금전운 · 일운")],
|
||||
4: [("saju_love", "연애운")],
|
||||
5: [("saju_match", "궁합")],
|
||||
|
||||
@@ -9,16 +9,15 @@ 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.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 WEALTH, branch_relations, stem_relations, ten_god
|
||||
from services.saju.rules import branch_relations, stem_relations, ten_god
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import WeekService
|
||||
|
||||
@@ -28,10 +27,7 @@ WEEK_DAYS = 7
|
||||
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 # 이달·올해 근거 줄 수
|
||||
CROWDED = 3 # 원국에 비겁이 이만큼 이상이면 비겁 날 돈 조심 (군겁쟁재)
|
||||
_WEEKDAY = "월화수목금토일"
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
|
||||
@@ -77,8 +73,8 @@ class Reading:
|
||||
level: int
|
||||
logged_in: bool
|
||||
week: Optional[list[DayReading]] = None
|
||||
money: Optional[list[str]] = None
|
||||
work: Optional[list[str]] = None
|
||||
money: Optional[str] = None
|
||||
work: Optional[str] = None
|
||||
love: Optional[dict] = None
|
||||
month: Optional[dict] = None
|
||||
year: Optional[dict] = None
|
||||
@@ -157,66 +153,37 @@ def _pillars(chart: Chart) -> dict[str, Pillar]:
|
||||
|
||||
|
||||
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)
|
||||
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]:
|
||||
"""점수를 가장 크게 움직인 사실 셋을 쉬운 말로, 올렸는지(↑) 내렸는지(↓)"""
|
||||
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}")
|
||||
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: 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 _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(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, ""))
|
||||
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))
|
||||
@@ -227,24 +194,21 @@ def avoid_card(chart: Chart, facts: DailyFacts) -> Optional[Card]:
|
||||
|
||||
|
||||
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))
|
||||
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]
|
||||
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))
|
||||
return Card(kind="good", title="오늘 좋은 흐름", body=T.GOOD_TEXT[i.position], sub=_rel(i))
|
||||
|
||||
|
||||
def when_card(r: DayReading, needs: list[tuple[str, str]]) -> Optional[Card]:
|
||||
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))
|
||||
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
|
||||
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)
|
||||
|
||||
|
||||
@@ -257,88 +221,80 @@ def wear_card(r: DayReading, needs: list[tuple[str, str]], place: Optional[str])
|
||||
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")
|
||||
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:
|
||||
"""앞으로 7일 중 연애 기운이 좋은 날과 조심할 날. 연인 자리(일지)가 부딪히는 날은 좋은 날에서 빼고, 비·눈 오는 날은 뒤로"""
|
||||
"""이번 주 연애 기운이 좋은 날과 조심할 날. 비 오는 날은 좋은 날에서 뒤로"""
|
||||
goods, bads = [], []
|
||||
for r in week:
|
||||
kinds, clash = set(), None
|
||||
kinds = set()
|
||||
for x in r.facts.love.reasons:
|
||||
k = x["kind"]
|
||||
if k == "일지":
|
||||
rel = x.get("relation")
|
||||
if rel in ("육합", "반합", "삼합"):
|
||||
kinds.add("일지합")
|
||||
else:
|
||||
clash = rel
|
||||
(kinds.add("일지합") if rel in ("육합", "반합", "삼합") else bads.append((r, 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))
|
||||
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]
|
||||
body = T.LOVE_GOOD[kinds[0]][0] + (" " + T.LOVE_WET.format(word=r.weather.word) if _wet(r) else "")
|
||||
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": body, "why": " · ".join(T.LOVE_GOOD[k][1] for k in kinds)}
|
||||
"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 = 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]}
|
||||
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 = ("편재", "정재"), ("비견", "겁재"), ("정관", "정인", "상관")
|
||||
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 _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]]:
|
||||
"""금전·일: 앞으로 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
|
||||
"""금전·일: 이번 주에 정할 날과 피할 날 (오늘 카드를 되풀이하지 않는다)"""
|
||||
def pick(gods: tuple[str, ...]) -> Optional[DayReading]:
|
||||
return next((r for r in week if r.facts.stem_ten_god in gods), 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]
|
||||
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, start: int = 1) -> list[int]:
|
||||
"""그해 start 월부터 남은 달(절 기준) 중 내 사주와 잘 맞는 달. 셋, 남은 달이 적으면 그 절반 (달 번호는 그 절이 드는 양력 달)"""
|
||||
def year_months(chart: Chart, year: int) -> list[int]:
|
||||
"""그해 열두 달(절 기준) 중 내 사주와 잘 맞는 달 셋 (달 번호는 그 절이 드는 양력 달)"""
|
||||
scored = []
|
||||
for m in range(start, 13):
|
||||
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)[: min(3, max(1, len(scored) // 2))])
|
||||
return sorted(m for _, m in sorted(scored, reverse=True)[:3])
|
||||
|
||||
|
||||
def period(chart: Chart, p: Pillar, unit: str, subject: str) -> dict:
|
||||
"""이달·올해: 그 간지 천간 십성 + 원국과의 관계. subject 는 근거 줄의 주어 ('이번 달이', '올해가')"""
|
||||
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]
|
||||
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]}
|
||||
return {"pillar": ko(p.stem + p.branch), "ten_god": god, "title": title, "body": body, "notes": [_rel(i) for i in interactions(chart, p)]}
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -346,62 +302,45 @@ class Match:
|
||||
score: int
|
||||
title: str
|
||||
lines: list[str]
|
||||
day: Optional[DayReading] # 앞으로 7일 중 둘 다 점수가 괜찮고 비·눈이 없는 날
|
||||
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": 5}
|
||||
_GROUPS = (("비견겁재", "rival"), ("식신상관", "output"), ("편재정재", "wealth"), ("편관정관", "officer"), ("편인정인", "resource"))
|
||||
|
||||
|
||||
def _group(god: str) -> str:
|
||||
return next(g for k, g in _GROUPS if god in k)
|
||||
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)
|
||||
back = ten_god(friend.day.stem, me.day.stem)
|
||||
score, lines = MATCH_SCORE["base"] + (MATCH_SCORE[_group(god)] + MATCH_SCORE[_group(back)]) / 2, [body]
|
||||
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 and T.MATCH_BRANCH[r.kind] not in lines:
|
||||
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)
|
||||
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]
|
||||
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, round(score))), title=title, lines=lines, day=best, friend_scene=T.SCENES[(b.season, b.label)][0])
|
||||
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), users: UserCRUD = Depends(UserCRUD),
|
||||
weather_service: WeatherService = Depends(WeatherService), week: WeekService = Depends(WeekService),
|
||||
) -> 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))
|
||||
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))
|
||||
@@ -431,18 +370,15 @@ class SajuService:
|
||||
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))
|
||||
return DayReading(day=d, facts=facts, weather=None, climate_score=None, best_hours=(), reasons=(), score=facts.score)
|
||||
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))
|
||||
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, "해", "올해가" 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)}
|
||||
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],
|
||||
@@ -481,9 +417,7 @@ class SajuService:
|
||||
_, 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]
|
||||
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:
|
||||
@@ -496,12 +430,12 @@ class SajuService:
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
)
|
||||
|
||||
+106
-118
@@ -1,101 +1,104 @@
|
||||
"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다. 쉬운 말을 앞에, 명리 용어는 괄호에."""
|
||||
"""날씨 사주 화면 문장. 엔진(services/saju)이 낸 사실을 사람이 바로 쓸 수 있는 말로 바꾼다 (초안, 사용자 검토 대상)."""
|
||||
|
||||
# 오늘 천간 십성 → (제목, 오늘 할 것)
|
||||
TEN_GOD_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("내 페이스대로 가는 날", "남한테 맞추기보다 내가 정한 일 하나를 끝까지 해 보세요."),
|
||||
"겁재": ("내 몫을 챙겨야 하는 날", "같이 하는 일은 누가 무엇을 맡을지 먼저 정해 두세요."),
|
||||
"식신": ("여유가 생기는 날", "맛있는 걸 먹거나 좋아하는 일에 시간을 내 보세요."),
|
||||
"상관": ("말솜씨가 살아나는 날", "생각해 둔 아이디어를 말이나 글로 꺼내 보세요."),
|
||||
"편재": ("새 기회가 보이는 날", "새로 들어온 제안은 조건부터 차근차근 들어 보세요."),
|
||||
"정재": ("알뜰하게 챙기는 날", "가계부를 정리하거나 미뤄 둔 정산을 끝내 보세요."),
|
||||
"편관": ("책임이 무거운 날", "미뤄 둔 어려운 일을 작게 나눠 첫 단계만 끝내 보세요."),
|
||||
"정관": ("약속과 규칙을 챙기는 날", "약속 시간과 마감부터 확인하세요."),
|
||||
"편인": ("혼자 생각할 시간이 필요한 날", "떠오른 생각을 메모해 두세요."),
|
||||
"정인": ("배우기 좋은 날", "궁금했던 걸 찾아보거나 아는 사람에게 물어보세요."),
|
||||
}
|
||||
# 십성 → 쉬운 말 ('오늘 들어오는 기운: 압박·책임(편관)')
|
||||
GOD_PLAIN = {
|
||||
"비견": "나와 닮은 힘", "겁재": "경쟁", "식신": "여유·즐거움", "상관": "표현", "편재": "새 돈·새 기회",
|
||||
"정재": "모으는 돈", "편관": "압박·책임", "정관": "규칙·평판", "편인": "생각·직감", "정인": "배움·도움",
|
||||
"비견": ("내 힘으로 밀고 가는 날", "혼자 끝낼 수 있는 일을 오늘 끝내세요."),
|
||||
"겁재": ("내 몫을 지키는 날", "남 눈치 보지 말고 내가 정한 일을 밀고 가세요."),
|
||||
"식신": ("즐기고 먹는 날", "맛있는 걸 먹고 좋아하는 일에 시간을 쓰세요."),
|
||||
"상관": ("말과 재주가 빛나는 날", "발표·제안·글쓰기처럼 밖으로 꺼내는 일을 하세요."),
|
||||
"편재": ("기회가 들어오는 날", "들어오는 제안은 들어 보고, 큰돈은 하루 생각한 뒤 정하세요."),
|
||||
"정재": ("차곡차곡 모으는 날", "정리·가계부·저축처럼 꼼꼼한 일을 하세요."),
|
||||
"편관": ("버티면 크는 날", "미뤄 둔 어려운 일에 먼저 손대 보세요."),
|
||||
"정관": ("믿음을 얻는 날", "약속 시간과 규칙을 지키면 평가가 올라가요."),
|
||||
"편인": ("혼자 생각하는 날", "혼자 있는 시간에 떠오른 생각을 적어 두세요."),
|
||||
"정인": ("배우고 도움받는 날", "공부·자격증·조언 구하기에 좋아요."),
|
||||
}
|
||||
|
||||
# 원국 자리 → 쉬운 말. 일간은 '나', 나머지는 태어난 해·달·날·시
|
||||
PLACE_WORD = {"year": "태어난 해", "month": "태어난 달", "day": "태어난 날", "hour": "태어난 시"}
|
||||
PLACE_TERM = {"year": "연", "month": "월", "day": "일", "hour": "시"}
|
||||
# 관계 → 쉬운 말
|
||||
REL_WORD = {
|
||||
"천간합": "어울려요", "육합": "어울려요", "반합": "어울려요", "삼합": "한데 묶여요",
|
||||
"천간충": "부딪혀요", "충": "부딪혀요", "형": "엇갈려요", "삼형": "엇갈려요", "자형": "겹쳐 부담돼요",
|
||||
"파": "틀어져요", "해": "어긋나요", "원진": "서로 꺼려요",
|
||||
}
|
||||
# 원국 자리 → 화면에 쓰는 짧은 이름
|
||||
PLACE_WORD = {"year": "윗사람·바깥 일", "month": "직장·집안", "day": "나·연인", "hour": "아랫사람·앞날"}
|
||||
|
||||
# (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로. 지지 관계의 일(日) 자리는 연인·배우자 자리(일지)
|
||||
# (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로
|
||||
AVOID_TEXT: dict[tuple[str, str], str] = {
|
||||
("원진", "day"): "연인·가까운 사람의 말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.",
|
||||
("충", "day"): "가까운 사람과 의견이 부딪히기 쉬워요. 서로 원하는 걸 먼저 확인하세요.",
|
||||
("충", "month"): "회사·집안 일정이 바뀌기 쉬워요. 이직·이사처럼 큰 결정은 오늘 확정하지 마세요.",
|
||||
("충", "year"): "밖에서 잡힌 일정이 바뀌기 쉬워요. 약속 시간과 장소를 다시 확인하세요.",
|
||||
("충", "hour"): "계획대로 안 풀리기 쉬워요. 일정 사이에 여유를 두세요.",
|
||||
("원진", ""): "말이 서운하게 들리기 쉬워요. 메시지는 보내기 전에 한 번 더 읽어 보세요.",
|
||||
("원진", "day"): "연인·배우자에게 사소한 서운함이 생기기 쉬워요. 큰 이야기는 내일로 미루세요.",
|
||||
("충", "day"): "가까운 사람과 부딪히기 쉬워요. 다툼이 될 만한 이야기는 피하세요.",
|
||||
("충", "month"): "직장·집안 일정이 흔들리기 쉬워요. 이직·이사 같은 큰 결정은 미루세요.",
|
||||
("충", "year"): "윗사람·바깥 일에서 변수가 생기기 쉬워요. 약속은 한 번 더 확인하세요.",
|
||||
("충", "hour"): "앞날 계획이 흔들리기 쉬워요. 일정은 여유 있게 잡으세요.",
|
||||
("원진", ""): "사소한 오해가 생기기 쉬워요. 말투를 한 번 더 고르세요.",
|
||||
("형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("자형", ""): "같은 고민을 계속 붙잡기 쉬워요. 적어 두고 일찍 쉬세요.",
|
||||
("파", ""): "약속이 틀어지기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("해", ""): "좋은 뜻으로 한 일이 오해를 사기 쉬워요. 부탁받은 일은 범위부터 정하세요.",
|
||||
("천간충", ""): "마음이 오락가락하기 쉬워요. 결정할 일은 하나씩 정리하세요.",
|
||||
("자형", ""): "생각이 많아 혼자 지치기 쉬워요. 오늘은 일찍 쉬세요.",
|
||||
("파", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("해", ""): "작은 약속이 어긋나기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("천간충", ""): "마음이 이리저리 흔들리기 쉬워요. 결정은 하나씩 하세요.",
|
||||
}
|
||||
# 비겁이 많고 재성이 있는 원국에 비겁 날 (군겁쟁재)
|
||||
CROWDED_RIVALS = "돈을 빌려주거나 같이 투자하는 건 오늘 미루세요."
|
||||
CROWDED_WHY = "내 사주에 나와 같은 기운이 많은데 오늘도 같은 기운이 들어와요({god})"
|
||||
# 비겁이 많은 원국에 비겁 날 (군겁쟁재)
|
||||
CROWDED_RIVALS = "같이 쓰는 돈·더치페이·빌려주는 돈은 오늘 정하지 마세요."
|
||||
|
||||
# 지지 합이 든 자리 → 좋은 흐름. 일간과 천간합이면 STEM_GOOD
|
||||
# 자리 → 좋은 흐름 (합이 들 때)
|
||||
GOOD_TEXT = {
|
||||
"day": "연인·가까운 사람과 사이가 부드러운 날이에요. 함께할 시간을 잡아 보세요.",
|
||||
"month": "회사·집안 일이 순조로운 날이에요. 미뤄 둔 협업 이야기를 꺼내 보세요.",
|
||||
"year": "밖에서 도움을 받기 좋은 날이에요. 부탁할 일이 있으면 오늘 꺼내 보세요.",
|
||||
"hour": "후배·아이와 잘 통하는 날이에요. 먼저 말을 걸어 보세요.",
|
||||
"day": "연인·배우자와 가까워지는 날이에요. 같이 보낼 시간을 잡아 보세요.",
|
||||
"month": "직장·팀 일이 잘 맞물려요. 협업 제안을 꺼내기 좋아요.",
|
||||
"year": "윗사람·바깥 사람에게 도움을 받기 쉬워요. 부탁할 일을 꺼내 보세요.",
|
||||
"hour": "아랫사람·후배와 사이가 좋아지는 날이에요.",
|
||||
}
|
||||
STEM_GOOD = "마음 맞는 사람을 만나기 좋은 날이에요. 미뤄 둔 연락을 해 보세요."
|
||||
GOOD_RELATIONS = ("천간합", "육합", "삼합", "반합")
|
||||
|
||||
# 금전·일: 앞으로 7일 중 고른 날 → 한 줄 ({day}는 '10/31(토)')
|
||||
MONEY_GOOD = "큰돈 쓰거나 계약할 일은 {day}에 하세요."
|
||||
MONEY_BAD = "돈 빌려주기·같이 투자하기는 {day}엔 미루세요."
|
||||
WORK_GOOD = "보고·발표·면접은 {day}에 잡아 보세요."
|
||||
MONEY_NONE = "앞으로 7일 중엔 큰돈 쓰기 좋은 날이 따로 없어요."
|
||||
WORK_NONE = "앞으로 7일 중엔 발표·면접 잡기 좋은 날이 따로 없어요."
|
||||
# 금전운 · 일운: 오늘 천간 십성 → 한 줄
|
||||
MONEY_TEXT = {
|
||||
"비견": "같이 쓰는 돈은 각자 내는 게 편한 날이에요.",
|
||||
"겁재": "빌려주거나 함께 투자하는 돈은 오늘 정하지 마세요.",
|
||||
"식신": "즐기는 데 쓰는 돈이 늘기 쉬워요. 한도를 먼저 정하세요.",
|
||||
"상관": "충동 구매가 생기기 쉬워요. 장바구니에 하루 두었다 사세요.",
|
||||
"편재": "뜻밖의 수입이나 할인 기회가 와요. 들어올 돈부터 챙기세요.",
|
||||
"정재": "가계부·적금처럼 돈을 정리하기 좋아요.",
|
||||
"편관": "갑자기 나갈 돈이 생기기 쉬워요. 여윳돈을 남겨 두세요.",
|
||||
"정관": "공과금·세금처럼 정해진 돈을 처리하기 좋아요.",
|
||||
"편인": "돈보다 정보가 남는 날이에요. 가격 비교를 해 두세요.",
|
||||
"정인": "배우는 데 쓰는 돈은 아깝지 않은 날이에요.",
|
||||
}
|
||||
WORK_TEXT = {
|
||||
"비견": "혼자 끝낼 수 있는 일에 집중하세요.",
|
||||
"겁재": "공동 작업은 역할과 몫을 먼저 나누세요.",
|
||||
"식신": "편하게 꺼낸 아이디어가 반응이 좋아요.",
|
||||
"상관": "발표·제안에 좋아요. 윗사람 앞에선 말을 한 번 고르세요.",
|
||||
"편재": "새 거래·새 사람과 일을 시작하기 좋아요.",
|
||||
"정재": "숫자를 맞추고 결과를 정리하는 일에 좋아요.",
|
||||
"편관": "어려운 일을 맡으면 인정받아요.",
|
||||
"정관": "보고·결재처럼 정해진 일을 처리하기 좋아요.",
|
||||
"편인": "자료 조사·기획처럼 준비하는 일에 좋아요.",
|
||||
"정인": "배우거나 도움을 청하면 일이 풀려요.",
|
||||
}
|
||||
|
||||
# 연애 기운이 드는 이유 → (한 줄, 이유 말)
|
||||
# 연애 기운이 드는 이유 → 한 줄
|
||||
LOVE_GOOD = {
|
||||
"도화": ("눈에 잘 띄는 날이에요. 모임이나 소개팅에 나가 보세요.", "눈에 띄는 기운(도화)"),
|
||||
"홍염": ("매력이 잘 드러나는 날이에요. 관심 있는 사람에게 먼저 연락해 보세요.", "매력의 기운(홍염)"),
|
||||
"일지합": ("연인과 마음이 잘 맞는 날이에요. 데이트 약속을 잡아 보세요.", "연인 자리와 어울림(일지 합)"),
|
||||
"재성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(재성)"),
|
||||
"관성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(관성)"),
|
||||
"도화": "사람들 눈에 잘 띄는 날이에요. 새 만남에 좋아요.",
|
||||
"홍염": "매력이 드러나는 날이에요.",
|
||||
"일지합": "연인과 가까워지는 날이에요.",
|
||||
"재성": "이성 기운이 들어오는 날이에요.",
|
||||
"관성": "이성 기운이 들어오는 날이에요.",
|
||||
}
|
||||
LOVE_BAD = {
|
||||
"원진": "말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.",
|
||||
"충": "의견이 부딪히기 쉬워요. 중요한 이야기는 다른 날로 미루세요.",
|
||||
"형": "오해가 생기기 쉬워요. 메시지보다 직접 말하세요.",
|
||||
"자형": "혼자 속앓이하기 쉬워요. 서운한 건 담아 두지 말고 말하세요.",
|
||||
"원진": "서운한 말이 오가기 쉬워요.",
|
||||
"충": "다투기 쉬워요.",
|
||||
"형": "오해가 생기기 쉬워요.",
|
||||
"자형": "혼자 속앓이하기 쉬워요.",
|
||||
}
|
||||
LOVE_BAD_WHY = {"원진": "연인 자리와 서로 꺼림(일지 원진)", "충": "연인 자리와 부딪힘(일지 충)", "형": "연인 자리와 엇갈림(일지 형)", "자형": "연인 자리에 같은 글자가 겹침(일지 자형)"}
|
||||
LOVE_WET = "{word} 예보가 있으니 실내 데이트로 잡으세요."
|
||||
|
||||
# 내 기운: 태어난 계절 × 원국의 결
|
||||
SCENES: dict[tuple[str, str], tuple[str, str]] = {
|
||||
("봄", "따뜻·마름"): ("봄햇살 기운", "새싹을 키우는 맑은 봄볕"),
|
||||
("봄", "따뜻·촉촉"): ("봄 아지랑이 기운", "따뜻하고 포근한 봄 오후"),
|
||||
("봄", "서늘·마름"): ("꽃샘바람 기운", "꽃봉오리를 스치는 쌀쌀한 봄바람"),
|
||||
("봄", "서늘·마름"): ("꽃샘바람 기운", "쌀쌀해도 꽃을 피우는 봄바람"),
|
||||
("봄", "서늘·촉촉"): ("봄비 기운", "새싹을 깨우는 촉촉한 이른 봄비"),
|
||||
("여름", "따뜻·마름"): ("한낮 땡볕 기운", "뜨겁고 환한 여름 한낮"),
|
||||
("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근한 오후에 쏟아지는 소나기"),
|
||||
("여름", "따뜻·촉촉"): ("소나기 기운", "후텁지근하다 시원하게 쏟아지는 여름비"),
|
||||
("여름", "서늘·마름"): ("여름밤 바람 기운", "열기를 식혀 주는 여름밤 바람"),
|
||||
("여름", "서늘·촉촉"): ("장맛비 기운", "며칠씩 이어지는 여름 장맛비"),
|
||||
("여름", "서늘·촉촉"): ("장맛비 기운", "오래 촉촉하게 내리는 장맛비"),
|
||||
("가을", "따뜻·마름"): ("가을 햇살 기운", "곡식을 익히는 가을볕"),
|
||||
("가을", "따뜻·촉촉"): ("가을비 기운", "단풍을 적시는 포근한 가을비"),
|
||||
("가을", "서늘·마름"): ("가을바람 기운", "선선하고 맑은 가을바람"),
|
||||
("가을", "서늘·촉촉"): ("새벽 서리 기운", "풀잎에 서리가 내린 늦가을 새벽"),
|
||||
("가을", "서늘·마름"): ("소슬바람 기운", "선선하고 맑은 가을바람"),
|
||||
("가을", "서늘·촉촉"): ("새벽 서리 기운", "찬 이슬이 맺히는 늦가을 새벽"),
|
||||
("겨울", "따뜻·마름"): ("겨울 햇살 기운", "추위 속에 비치는 겨울볕"),
|
||||
("겨울", "따뜻·촉촉"): ("함박눈 기운", "포근하게 쌓이는 함박눈"),
|
||||
("겨울", "서늘·마름"): ("칼바람 기운", "맑고 매서운 겨울바람"),
|
||||
@@ -103,18 +106,10 @@ SCENES: dict[tuple[str, str], tuple[str, str]] = {
|
||||
}
|
||||
SCENE_ICON = {"따뜻·마름": "sun", "따뜻·촉촉": "sun_cloud", "서늘·마름": "coldwind", "서늘·촉촉": "rain"}
|
||||
|
||||
# 조후에서 필요한 것 → (이어 쓰는 꼴, 끝맺는 꼴): '따뜻하고 건조한 날씨'
|
||||
NEED_ADJ = {("temp", "warm"): ("따뜻하고", "따뜻한"), ("temp", "cool"): ("선선하고", "선선한"), ("moist", "dry"): ("건조하고", "건조한"), ("moist", "moist"): ("촉촉하고", "촉촉한")}
|
||||
# 옷 포인트 색 (오방색에서 착안)
|
||||
NEED_COLOR = {("temp", "warm"): "빨강·주황으로", ("temp", "cool"): "검정·남색으로", ("moist", "dry"): "노랑·베이지로", ("moist", "moist"): "초록·하늘색으로"}
|
||||
|
||||
|
||||
def need_phrase(needs: list[tuple[str, str]]) -> str:
|
||||
"""[('temp','warm'), ('moist','dry')] → '따뜻하고 건조한 날씨'"""
|
||||
if not needs:
|
||||
return ""
|
||||
words = [NEED_ADJ[n] for n in needs]
|
||||
return " ".join([w[0] for w in words[:-1]] + [words[-1][1]]) + " 날씨"
|
||||
# 조후에서 필요한 것 → 말
|
||||
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:
|
||||
@@ -144,49 +139,42 @@ def josa(word: str, pair: str) -> str:
|
||||
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_AXIS = {"temp": "한 사람은 따뜻하고 한 사람은 서늘한 기운이라", "moist": "한 사람은 촉촉하고 한 사람은 건조한 기운이라"}
|
||||
MATCH_CLIMATE_OK = "{axis} 서로 모자란 걸 채워 줘요."
|
||||
MATCH_CLIMATE_SAME = "둘 다 {need}가 맞는 기운이라, 그런 날 함께 나가면 좋아요."
|
||||
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 = "비가 오니 실내 약속으로 잡으세요."
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
@@ -29,11 +29,11 @@ class ShortsService:
|
||||
return await self.refresh()
|
||||
|
||||
async def refresh(self) -> tuple[ErrorType, list[dict]]:
|
||||
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로."""
|
||||
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
items = await self._fetch(client)
|
||||
except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) as e:
|
||||
except (httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.error(f"[shorts] fetch: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
try:
|
||||
@@ -45,6 +45,7 @@ class ShortsService:
|
||||
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
|
||||
if settings.youtube_api_key:
|
||||
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
|
||||
else:
|
||||
found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS)
|
||||
return [{"id": v["id"], "title": v["title"]} for v in found]
|
||||
return [{"id": v["id"], "title": v["title"]} for v in found]
|
||||
ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
|
||||
titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
|
||||
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
|
||||
@@ -37,8 +37,6 @@ async def test_reading_for_anyone_gives_me_today_and_cards(offline):
|
||||
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["today"]["why"] and not any(ch.isdigit() for w in r["today"]["why"] for ch in w)
|
||||
# 로그인 안 하면 레벨로 여는 것은 모두 잠김, 내용도 안 옴
|
||||
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
|
||||
@@ -70,7 +68,7 @@ async def test_level_unlocks_sections_and_awards_once(offline):
|
||||
|
||||
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 1 <= len(r["year"]["months"]) <= 3
|
||||
assert r["month"]["title"].endswith("달") and "년" in r["year"]["label"] and len(r["year"]["months"]) == 3
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -83,27 +81,3 @@ async def test_match_needs_level_five(offline):
|
||||
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("기운")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_match_score_is_same_whoever_goes_first(offline):
|
||||
a, b = {"birth_date": "1995-03-14"}, {"birth_date": "1996-11-02"}
|
||||
async with client() as c:
|
||||
h = await _login(c, "match_sym", points=400)
|
||||
ab = (await c.post("/v1/saju/match", json={"region_code": REGION, "me": a, "friend": b}, headers=h)).json()
|
||||
ba = (await c.post("/v1/saju/match", json={"region_code": REGION, "me": b, "friend": a}, headers=h)).json()
|
||||
assert ab["score"] == ba["score"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_birth_is_saved_to_account(offline):
|
||||
body = {"birth_date": "1995-03-14", "birth_time": "07:30", "place": "busan", "gender": "female"}
|
||||
async with client() as c:
|
||||
assert (await c.get("/v1/saju/birth")).status_code == 401
|
||||
h = await _login(c, "birth_01")
|
||||
assert "birth" not in (await c.get("/v1/saju/birth", headers=h)).json()
|
||||
assert (await c.put("/v1/saju/birth", json=body, headers=h)).json()["birth"] == body
|
||||
assert (await c.get("/v1/saju/birth", headers=h)).json()["birth"] == body
|
||||
assert (await c.put("/v1/saju/birth", json={**body, "birth_date": "1899-12-31"}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
await c.delete("/v1/saju/birth", headers=h)
|
||||
assert "birth" not in (await c.get("/v1/saju/birth", headers=h)).json()
|
||||
@@ -6,7 +6,7 @@ import pytest
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from services import shorts_service
|
||||
from services.external.youtube import channel_shorts, feed_shorts, seconds, video_title
|
||||
from services.external.youtube import channel_shorts, seconds, video_title
|
||||
from services.shorts_service import CACHE_KEY, ShortsService
|
||||
|
||||
|
||||
@@ -58,32 +58,6 @@ async def test_video_title_none_when_embedding_blocked():
|
||||
assert await video_title(client, "blocked") is None
|
||||
|
||||
|
||||
def _feed(entries: list[tuple[str, str]]) -> str:
|
||||
items = "".join(
|
||||
f"<entry><yt:videoId>{vid}</yt:videoId><title>제목 {vid}</title><published>{published}</published></entry>" for vid, published in entries
|
||||
)
|
||||
return f'<feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://www.youtube.com/xml/schemas/2015">{items}</feed>'
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_shorts_reads_channel_shorts_feed_newest_first_without_blocked():
|
||||
seen = {}
|
||||
|
||||
def handle(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("/feeds/videos.xml"):
|
||||
seen["playlist"] = req.url.params["playlist_id"]
|
||||
return httpx.Response(200, text=_feed([("old", "2026-10-20T00:00:00+00:00"), ("new", "2026-10-28T00:00:00+00:00"), ("blocked", "2026-10-27T00:00:00+00:00")]))
|
||||
if "blocked" in req.url.params["url"]:
|
||||
return httpx.Response(401)
|
||||
return httpx.Response(200, content=json.dumps({"title": "x"}))
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
|
||||
found = await feed_shorts(client, "UCtest", 10)
|
||||
assert seen["playlist"] == "UUSHtest"
|
||||
assert [v["id"] for v in found] == ["new", "old"]
|
||||
assert found[0]["title"] == "제목 new"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
|
||||
calls = []
|
||||
|
||||
Reference in new issue
Block a user