Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
becd26d1da | ||
|
|
dac9f7b8e0 | ||
|
|
8ca1d12822 | ||
|
|
239a22ee06 | ||
|
|
1e9ddb4719 | ||
|
|
c61d488794 | ||
|
|
41b09664eb | ||
|
|
4d79ec839c | ||
|
|
c8df1f5ef6 | ||
|
|
9e7bd54c7e | ||
|
|
3df3e0113b | ||
|
|
3da946382c | ||
|
|
cb013fcc9a | ||
|
|
e4834fd24e | ||
|
|
4cfcbcf7ea | ||
|
|
4ef99e5f73 | ||
|
|
0399942fb1 | ||
|
|
7d097a05de | ||
|
|
03ad57bcaa | ||
|
|
8a18ddc515 | ||
|
|
ab6959ee0f | ||
|
|
71974dcf42 | ||
|
|
b2c46086a3 | ||
|
|
92206d82f0 | ||
|
|
045d8d6cf0 | ||
|
|
44146888d3 | ||
|
|
13bb3d9a02 | ||
|
|
0a46fd71c2 | ||
|
|
cbee7cd807 | ||
|
|
c37773f48f | ||
|
|
52a4830b08 | ||
|
|
e154242c32 | ||
|
|
728b24a0c9 | ||
|
|
1489030c5f | ||
|
|
430f97131b | ||
|
|
1d6bb1e630 | ||
|
|
001e163b2a | ||
|
|
1ec87a82c1 | ||
|
|
5a1d464196 | ||
|
|
571ff84b0c | ||
|
|
ab9674eaa2 | ||
|
|
685a65faa5 | ||
|
|
6ed6c14adc | ||
|
|
ac16b098ba | ||
|
|
5ee25551ea | ||
|
|
1ae81ac25c | ||
|
|
1ca680f006 | ||
|
|
9544674e7f | ||
|
|
3c81976998 | ||
|
|
8709bfba2a | ||
|
|
cc5ecd7bbf | ||
|
|
7f5441a512 | ||
|
|
694ea85ed3 | ||
|
|
597017bd37 | ||
|
|
ef61a5bf73 | ||
|
|
74805aa829 | ||
|
|
89221535ba | ||
|
|
5f79df1973 | ||
|
|
942b652e56 | ||
|
|
8ccdf22882 | ||
|
|
e962304107 | ||
|
|
f24e790bd7 | ||
|
|
d38cfc7229 | ||
|
|
8191881f6a | ||
|
|
7ffeecbb4f | ||
|
|
4875ea4333 | ||
|
|
b346af7fef | ||
|
|
340b30cc8b | ||
|
|
fd67c2b45f | ||
|
|
ffe6153148 | ||
|
|
3a249c509d | ||
|
|
55edc037fb | ||
|
|
a17cef201d | ||
|
|
0414160520 | ||
|
|
0bc8ca02a4 | ||
|
|
1557ba42c4 | ||
|
|
9af3407546 | ||
|
|
117de90c3e | ||
|
|
be60551f49 | ||
|
|
dcf2fe5a53 | ||
|
|
132301dc28 | ||
|
|
dd133c9d52 | ||
|
|
5459b97ba0 | ||
|
|
1908433e46 | ||
|
|
7dcd6c6a4c | ||
|
|
7d84226105 | ||
|
|
c45940c358 | ||
|
|
09e8b4734a | ||
|
|
a87f245547 | ||
|
|
197fafdc02 | ||
|
|
65fd9b8fb1 | ||
|
|
668377660c | ||
|
|
98b5c0cbe3 | ||
|
|
d32e24a5ab | ||
|
|
fcc4163e15 | ||
|
|
882c7f06dc | ||
|
|
694757b2fb | ||
|
|
019b018bfa | ||
|
|
746aa4ba92 | ||
|
|
f4cb2217ed | ||
|
|
0f6c8c4bc9 | ||
|
|
8bc4678f40 | ||
|
|
0e4455fdc8 | ||
|
|
df7cf01835 | ||
|
|
baa4324ea0 | ||
|
|
1bfa224c62 | ||
|
|
b73bc650c4 | ||
|
|
b8117f190d | ||
|
|
d8c406b8b8 | ||
|
|
ceacd5615b | ||
|
|
7144084d8c | ||
|
|
2caa4d2832 | ||
|
|
d3d6d1a109 | ||
|
|
09feb3cd9e | ||
|
|
77cfb04808 | ||
|
|
9dc7a52383 | ||
|
|
130f14e96a | ||
|
|
b240ecb180 | ||
|
|
21bfa2a3ff | ||
|
|
61023d090e | ||
|
|
2fd6fcbd06 | ||
|
|
acb6c4d717 | ||
|
|
81b17f057f | ||
|
|
51e0c06f2d | ||
|
|
0a84f34729 | ||
|
|
2627dd2685 |
No files matched your search
@@ -6,6 +6,17 @@ argument-hint: "<스타일> minimal(꾸안꾸)·casual·semi(오피스)·formal
|
||||
오늘의 코디 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 코디 스타일 하나(minimal=꾸안꾸, casual=캐주얼, semi=세미정장·오피스, formal=정장, street=스트릿). 비어 있으면 minimal. 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||
|
||||
## 꼭 지킬 것 (2026-10-27 사용자 피드백)
|
||||
- 에이블리는 공개 API 가 없어 쓸 수 없다. 요청에 있어도 처음에 그 사실을 말하고 무신사로만 만든다.
|
||||
- 옷은 스냅에 태그된 무신사 상품만 쓴다. 사진에만 보이는 옷·가방은 넣지 않는다(`admin/scripts/outfit.mjs`).
|
||||
- 계절감(가장 중요): 검수 때 아침·저녁 체감기온으로 '오늘 이 옷이면 춥지 않은가'를 사람마다 본다. 쌀쌀한 날(아침 체감과 낮 최고 평균 12도 미만, 스크립트 구간 chilly 이하)은 네 사람 모두 겉옷이 있어야 하고, 반팔 단독·미니 원피스/스커트·뮬·슬링백·샌들은 안 된다. 하나라도 걸리면 그 사람 스냅을 다시 고른다.
|
||||
- 여자 코디는 남성적·고프코어(카고 바지·백팩·등산화·바람막이)를 피하고 여성스러운 스냅을 고른다. 스트릿처럼 남성적인 스타일이 네 사람에게 안 어울리면 다른 스타일로 바꾼다.
|
||||
- 이름표는 한 줄에 들어가게 짧게(색 이름 접두어 빼기).
|
||||
- 인스타 API 가 `Application request limit reached` 를 돌려줘도 실제로는 올라갔을 수 있다. 다시 올리기 전에 `GET https://graph.instagram.com/v24.0/me/media?fields=permalink,caption,timestamp&limit=1` 로 최신 글 캡션을 확인하고, 없을 때만 다시 올린다(중복 게시 금지).
|
||||
- 캡션 해시태그가 이 포스트 내용(주제·카드·스타일·계절)과 맞는지 본다. 고정 태그만 있으면 올리지 않는다(`admin/src/cards/templates.tsx` `post`).
|
||||
- 무엇을 왜 바꿨는지·되돌렸는지는 한 번에 구체적으로 설명한다(파일 이름만 말하지 않는다).
|
||||
|
||||
## 순서
|
||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||
2. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||
무신사 인기 스냅 중 그 스타일 태그가 붙은 것에서 사람 4명 코디를 고르고(최근 14일에 쓴 스냅 제외), Claude 가 옷 목록을 뽑고, Codex 가 스냅 사진·상품 썸네일을 참고해 플랫레이 그림을 그린다(사람당 2~4분, 총 10~15분). 고른 스냅 주소·옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요"·"Codex 실행이 실패" 가 나오면 멈추고 보고한다. 로그의 `rmcp … AuthRequired` 는 Codex 내부 경고라 무시한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||
|
||||
@@ -6,6 +6,16 @@ argument-hint: "<타로 주제> 예) 건강 운동 · 연애 썸 · 경제 주
|
||||
오늘의 날씨 타로 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 타로 주제(대주제 소주제). 비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다.
|
||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||
|
||||
## 꼭 지킬 것 (2026-10-27 사용자 피드백)
|
||||
- 카드는 주제와 직접 엮여야 한다. 경제(주식·재테크) 주제는 경제 전용 카드(`admin/money-deck.json`: 불장·존버·분할매수·익절·손절·관망·물타기·배당·적금·텅장)에서만 고르고, 리딩은 돈·주식 이야기로 쓴다. 산책·꽃구경 같은 활동 이야기로 새면 다시 기획한다.
|
||||
- 주식 주제의 제목·질문은 "오늘 내 주식"(계좌·지갑처럼 돌려 말하지 않는다).
|
||||
- 예보 데이터에 없는 사실(바람 세기 등)은 쓰지 않는다. 행운 포인트의 시각·기온은 그 시각 slot 값 그대로(예: 해 질 녘 18시 10도를 8도로 쓰지 않는다).
|
||||
- 카드 그림을 계절에 맞출 필요는 없다(가을에 벚꽃 그림이어도 다시 그리지 않는다).
|
||||
- 인스타 API 가 `Application request limit reached` 를 돌려줘도 실제로는 올라갔을 수 있다. 다시 올리기 전에 `GET https://graph.instagram.com/v24.0/me/media?fields=permalink,caption,timestamp&limit=1` 로 최신 글 캡션을 확인하고, 없을 때만 다시 올린다(중복 게시 금지).
|
||||
- 캡션 해시태그가 이 포스트 내용(주제·카드·스타일·계절)과 맞는지 본다. 고정 태그만 있으면 올리지 않는다(`admin/src/cards/templates.tsx` `post`).
|
||||
- 무엇을 왜 바꿨는지·되돌렸는지는 한 번에 구체적으로 설명한다(파일 이름만 말하지 않는다).
|
||||
|
||||
## 순서
|
||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
||||
3. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait` (주제가 없으면 `--topic` 없이). 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||
|
||||
@@ -14,10 +14,9 @@ INSTAGRAM_USER_ID=
|
||||
PUBLIC_BASE_URL=https://weather.o2o.kr
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
|
||||
# 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용).
|
||||
# 비우면 채널 쇼츠를 자동으로 못 받고 YOUTUBE_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개)
|
||||
# 비우면 채널 쇼츠 RSS(키 없음, 최신 15개)로 받는다
|
||||
YOUTUBE_API_KEY=
|
||||
YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w
|
||||
YOUTUBE_SHORTS=
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
|
||||
@@ -59,10 +59,18 @@
|
||||
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
|
||||
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
|
||||
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
|
||||
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
|
||||
| [x] | 오늘 화면 쇼츠 줄 — 영상 ID 고정 목록(`youtube_shorts`) 없앰. API 키가 없으면 채널 쇼츠 RSS(`UUSH…` 재생목록, 키 없음)로 자동으로 받음. 키(`YOUTUBE_API_KEY`)를 운영 .env 에 넣으면 Data API 로 바뀌어 퍼가기·길이까지 거름 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 10/28 운영에 키가 없어 고정 목록만 나와 새 쇼츠가 안 붙음. 채널 RSS가 다시 200 | `backend/services/external/youtube.py`, `backend/services/shorts_service.py` |
|
||||
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
|
||||
| [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | **[결정 필요]** 쇼츠 폰에서 유튜브 멈춤(\|\|) 버튼이 계속 남음 — 유튜브 플레이어 자체 버튼이라 코드로 못 지움. 우리 쇼츠 원본 mp4를 저장소에 올려 <video>로 틀지, 폰 연결해 유튜브로 더 시도할지 | 10/27 실기기 보고, 크롬·WebKit 흉내에선 재현 안 됨 | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | 토스 ait 는 `feat/apps-in-toss` 브랜치(~/orca/workspaces/o2o-weather/main-3)에서 만들기 — main 에는 토스 로그인·웹뷰 자동재생·쇼츠 토스 처리가 없음. 최신 ait 20:03 콘솔 업로드 필요 | 10/27 main 에서 만든 ait 로 쇼츠가 멈춰 보임 | `~/orca/workspaces/o2o-weather/main-3/frontend/nalssigak.ait` |
|
||||
| [ ] | 운영 행사 주소(event.address) 채우기 — 팝가가 연속 요청을 막아(429) 로컬도 206개 중 80개만. 간격 두고 다시 | 10/27 주소 수집 추가 | `backend/scheduler/jobs.py` `refresh_popups` |
|
||||
| [ ] | `test_watch_summary_flags_thunder_within_2_hours` 가 전체로 돌릴 때만 실패(따로 돌리면 통과) — 순서 의존 원인 찾기 | 10/27 전체 테스트 | `backend/tests/test_watch.py` |
|
||||
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
|
||||
| [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` |
|
||||
| [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` |
|
||||
| [x] | 빈 댓글 보완 — 포스트마다 날씨각 캐릭터(해님·구름·달님) 댓글 1~2개, '날씨각' 표시. 사람인 척하는 가짜 계정·부풀린 숫자는 안 함 | 10/27 결정 | `backend/services/bot_comment.py`, `backend/services/bot_comment.json` |
|
||||
| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
|
||||
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
|
||||
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
|
||||
@@ -76,6 +84,21 @@
|
||||
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
|
||||
|
||||
## 10/28 시장성 진단 (보고서는 채팅 첨부, 근거: 운영 DB 집계·첫 화면 캡처·회의록)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | **[결정 필요]** 타깃을 2030 직장인으로 좁히기 — 기능은 지우지 않고 첫 화면·각 순서만 이 사람 기준으로. 9/29 '타깃 정하지 않음'을 바꾸는 일이라 대표 결정 | 콘텐츠가 2030·4050·반려인·동네 주민으로 흩어져 누구에게도 1순위가 아님 | `frontend/src/b/TodayPage.tsx`, `backend/services/feed_service.py` |
|
||||
| [ ] | 오늘 타로(오늘 한 장) — main 병합(10/28): 오늘 탭 아이콘 줄 → 오늘 타로 창. 타로 22장 하루 1장 + 행운(시간·장소·색·1위 각) + 연속 도장 + 저녁 체크인. 남은 것: 배포(운영 init.sql 로 표 fortune_draw·day_log·point_log, users.points 생김), 토스 ait(`feat/apps-in-toss`에 main 합친 뒤) | 10/28 사용자 결정 | `frontend/src/b/fortune.tsx`, `frontend/src/b/todayIcons.tsx` |
|
||||
| [ ] | **[결정 필요]** 아침 7시 웹 푸시 — 안드로이드 크롬은 바로, 아이폰은 홈 화면에 추가한 사람만(iOS 16.4+). 앱 위젯(10/21 결정)은 계속 | 다시 부르는 장치가 없음(코드에 웹 푸시 없음) → DAU가 쌓이지 않음 | `frontend/public/sw.js`, `frontend/src/b/install.ts` |
|
||||
| [ ] | **[결정 필요]** 좋아요·댓글 0이면 숫자 숨기기, 동네 이야기는 그날 글이 몇 개 넘을 때만 위에 | 첫 화면 '좋아요 0개'·동네 글 1개가 "아무도 안 쓴다"는 신호 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/talk.tsx` |
|
||||
| [ ] | **[결정 필요]** 4주 새 기능 동결 목록 — 후보: 나만의 각 피드 올리기, 동네 이야기 사진, 캐시워크·통신사 위젯, 새 각 추가, 지역 페이지 추가 확장(10/21 '모든 지역 추가'와 충돌) | 2명이 기능 폭을 넓히는 중, 바깥 사용자 반응은 거의 없음(계정 7개 대부분 팀 추정) | |
|
||||
| [ ] | 첫 화면에 '지금 10°'(시간대 줄)와 '오전 10시 5°'(히어로 문장·오늘의 각)가 함께 보임 — 원인 확인(체감온도인지). 오늘의 각 5줄 설명도 모두 같은 문장 | 10/28 11시 운영 캡처(마포구), 숫자 어긋나면 첫 방문자 신뢰 잃음 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | GA4 사내 IP 제외 필터 + 주간 지표 4개(신규 방문, 1일·7일 재방문, 공유→방문, 홈 화면 추가→알림 허용) | 바깥 사용자 수를 아무도 모름, 이게 없으면 진단이 가설로 남음 | `docs/이벤트_추적.md` |
|
||||
| [ ] | 계정 레벨 — main 병합(10/28, 배포 남음). 사용자 결정 10/28: **레벨 제도**(포인트 소비형 아님). 단위는 '각'(출석 +10각 등 서비스 전체 행동으로 적립), 레벨은 모은 총량 기준이라 나중에 각을 쓰는 기능을 붙여도 안 내려감. 지금 있는 기능·캐릭터·색·기분은 잠그지 않고, 새로 생기는 것(날씨 사주 연애운·궁합 등, 새 캐릭터·테두리, 댓글 레벨 배지)만 레벨로 열림. 내 정보는 기존 화면에 레벨·각만 더함. 정할 것: 레벨 이름·단계·필요 각, 행동별 각·하루 한도, 해금 목록 | 기획서 '계정 레벨(각)·날씨 사주 UI 기획'(10/28 채팅 첨부) | `frontend/src/b/Sheets.tsx` `MeSheet` |
|
||||
| [ ] | 날씨 사주 해석 기준 — 사용자가 맡김(10/28 "니 알아서 하라"), 바꿀 수 있게 기록: 날씨 접목은 조후(한난조습) · 연애운은 열 때 성별 선택 입력(남/여/선택 안 함, 안 하면 도화·배우자궁만으로 본다고 표시) · 도화는 연지·일지 삼합 둘 다 · 홍염은 일간표(甲乙午 丙寅 丁未 戊己辰 庚戌 辛酉 壬子 癸申, 이견 있음 표시) · 합충형파해원진은 원국 네 지지 모두, 일지에 걸리면 연애 가중 · 절입 시각은 천문 계산식으로 1900~2100 표를 만들고 천문연 값으로 검증(패키지 안 씀) · 진태양시(출생지 경도)·서머타임 반영, 자시는 자정 기준(설정으로 변경) · 음력은 다음 단계(천문연 API) | 사용자 위임 10/28 | |
|
||||
| [ ] | **[결정 필요]** 날씨 사주 화면·문구 — '내 기운'(계절·날씨 장면 16종), 점수 → 사주 풀이 → 계절·날씨 한 스푼, 하루 풀이를 '오늘의 결정 카드'(언제·미룰 것·입을 것/갈 곳·이번 주 날짜)로 줄지, 규칙별 의미 사전·문구 검토, 기운 장면 그림 | 사용자 피드백 10/28 | 기획서 '날씨 사주 기획 v2', '계정 레벨·날씨 사주 UI 기획' |
|
||||
|
||||
## 진행 순서
|
||||
|
||||
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
|
||||
@@ -237,6 +260,7 @@
|
||||
| [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리), 로그인 창 '날씨각 로그인'·'로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요', 인트로 '오늘 날씨에 맞는 일을 점수로 알려 줘요'·'세차·빨래·러닝 각 점수'·'오늘 노을이 예쁜 시간'·'이번 주말 가까운 행사'·'시작하기'(10/24) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` |
|
||||
| [ ] | 토스판 첫 실행에 인트로와 위치 권한 창이 같이 뜸 — 위치 권한은 앱이 뜨자마자 물어서 인트로 위에 겹칠 수 있음. '시작하기' 뒤로 미룰지 토스 앱에서 확인 | 인트로 추가 (10/24) | `frontend/src/b/region.tsx`, `frontend/src/b/tossIntro.tsx` |
|
||||
| [ ] | 메뉴의 '로그인하면 좋아요·댓글을 쓸 수 있어요' — 좋아요·댓글은 로그인 없이 됨(10/21 결정)이라 문구가 틀림 | 인트로 추가 중 발견 (10/24) | `frontend/src/b/Sheets.tsx:1117` |
|
||||
| [ ] | 토스 웹뷰에서 유튜브 플레이어가 보내는 재생 상태(postMessage)가 페이지에 오지 않음 — 원인 미확인(origin 불일치? 토스 브리지?). 그래서 토스판 쇼츠는 숨기기·명령 없이 유튜브 기본 플레이어 사용. 원인 찾으면 웹과 같은 UI로 합칠 수 있음 | 토스판 쇼츠 재생 안 됨 (10/26) | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | |
|
||||
| [x] | 각 늘리기 53→68 — 리서치로 고른 8개(한강·놀이공원·데이트·곱슬머리·보일러·선크림·모기·테니스) + 감성 7개(효도·감사·선물·파티·게임·셀카·센치), 아이콘 15개(Codex) | 사용자 요청 (10/20, 리서치 https://claude.ai/artifact/3ZQbtGKRLVZViRRC5voBzY) | `backend/seed/index_definition.json`, `frontend/public/icons/`, `frontend/src/b/lib.ts` |
|
||||
| [ ] | **[결정 필요]** 한강각·놀이공원각이 강·놀이공원 없는 동네에도 나옴 — 각을 지역별로 가려 보여 주는 기능이 없음(한강밤바람각도 같음). 서울·한강 인접 구만 보일지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
|
||||
@@ -292,6 +316,15 @@
|
||||
| [x] | 코디 카드 매일 다르게 — 고정 옷 데이터 대신 무신사 스냅 공개 API에서 오늘 구간 인기 코디를 사람별(40대~ 단정 태그 우선)로 골라 Claude가 옷 목록 추출, Codex가 참고 사진 첨부로 플랫레이 생성(`npm run card -- ootd --daily`, `/daily-cards`). 10/26 4장 검수 통과. 에이블리는 공개 API 없음(앱 전용)이라 미사용 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs`, `snap.mjs`, `outfit.mjs`, `codex-image.mjs` |
|
||||
| [x] | 10/26 세미정장 코디(그날 코디 첫 게시) — 킹서버 카드 12→포스트 4275, 인스타 https://www.instagram.com/p/De8O2kqATrl/. 무신사 스냅 4개 참고, 4장 1:1 검수 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs` |
|
||||
| [x] | 10/26 몸 컨디션 타로(건강: 등산각·자전거각·산책각) — 킹서버 카드 13→포스트 4276, 인스타 https://www.instagram.com/p/De8Zw7MIEVW/. 기획에서 3번 산책각 비 시점 틀린 것 피드백으로 고침. card.mjs --post-wait 가 ECONNRESET 으로 두 번 실패해 post-king.py 로 저장 | 사용자 요청 (10/26) | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/27 계좌 타로(철회: 경제와 무관한 각이라는 피드백, 포스트 4587 숨김 필요·인스타 앱에서 삭제 필요 / 경제 주식: 멍뭉산책각·꽃구경각·사진산책각) — 킹서버 카드 14→포스트 4587, 인스타 https://www.instagram.com/p/De-eiqPgZ7K/. 검수에서 2번 예보에 없는 바람 문구 빼고, 3번 '해 질 녘 8도'를 '저녁 6시 10도'로 고침, 5번 장식 점이 아래 문구를 가려 위로 옮김. card.mjs --post-wait 는 또 ECONNRESET 이라 post-king.py 로 저장 | 사용자 요청 (10/27) | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/27 계좌 타로 다시(철회: 제목을 '오늘 내 주식'으로, 포스트 4590 숨김 필요·인스타 앱에서 삭제 필요 / 경제 전용 카드: 분할매수각·적금각·배당각) — 킹서버 카드 20→포스트 4590, 인스타 https://www.instagram.com/p/De-p3dygf1K/. 경제 전용 카드 10장(`admin/money-deck.json`, 그림 `gak-card/money_*.webp`) 새로 만듦, 경제 주제는 이 카드에서 오늘 날씨에 맞는 3장을 고름 | 사용자 요청 (10/27) | `admin/money-deck.json`, `admin/scripts/plan.mjs` |
|
||||
| [x] | 10/27 주식 타로(경제 전용 카드: 분할매수각·적금각·배당각) — 킹서버 카드 21→포스트 4591, 인스타 https://www.instagram.com/p/De-qodJAXp9/ | 사용자 요청 (10/27) | `admin/topics.json` |
|
||||
| [x] | 10/27 스트릿 코디(철회: 겉옷 없는 사람 2명·남성적이라는 피드백, 포스트 4588 숨김 필요·인스타 앱에서 삭제 필요) — 킹서버 카드 16→포스트 4588, 인스타 https://www.instagram.com/p/De-hDoVge1N/. 참고 스냅 f20 https://www.musinsa.com/snap/1554718501896708736 · m20 https://www.musinsa.com/snap/1561558258020785611 · f40 https://www.musinsa.com/snap/1552178778683619999 · m40 https://www.musinsa.com/snap/1549383828670555308. 사용자 요청으로 옷은 스냅에 태그된 무신사 상품만(사진에만 보이는 f20 레드 니트집업·m40 백팩 뺌). 에이블리는 공개 API 없음. 카드 15(고치기 전)는 승인 대기로 남음. 인스타 게시 API가 'Application request limit reached'를 돌려줬지만 실제 게시는 됨 | 사용자 요청 (10/27) | `admin/scripts/outfit.mjs`, `snap.mjs` |
|
||||
| [x] | 10/27 캐주얼 코디(스트릿 대체) — 킹서버 카드 19→포스트 4589, 인스타 https://www.instagram.com/p/De-oLGagZRB/. 참고 스냅 f20 https://www.musinsa.com/snap/1555508873710779888 · m20 https://www.musinsa.com/snap/1555156725005269012 · f40 https://www.musinsa.com/snap/1555157672544679299 · m40 https://www.musinsa.com/snap/1552193811640384198. 구간을 아침 체감·낮 최고 평균으로 정해 chilly, 쌀쌀한 날 겉옷 필수·미니·뮬/슬링백 제외, 여자 코디는 고프코어 감점. 카드 15·16·17·18은 버린 판 | 사용자 요청 (10/27) | `admin/scripts/snap.mjs`, `daily-ootd.mjs` |
|
||||
| [x] | 10/27 서울 근교 단풍 TOP 10 카드뉴스(매주 목요일 시리즈 첫 회) — 킹서버 카드 22→포스트 4592, 인스타 https://www.instagram.com/p/De-1vM_gVN8/. 캡션 첫 줄에 제목이 두 번 나옴(서버가 제목을 붙이는데 캡션도 제목으로 시작), 인스타 API가 request limit을 돌려줘 ig_media_id 미기록 | 사용자 요청 (10/27) | `admin/src/cards/templates.tsx` |
|
||||
| [x] | 10/28 세미정장 코디(철회: 20-30대 남자에 나팔바지라는 피드백, 포스트 4903 10/28 삭제함(deleted=true)·인스타 앱에서 삭제 필요) — 킹서버 카드 23→포스트 4903, 인스타 https://www.instagram.com/p/DfBIhUdAbbV/. 참고 스냅 f20 https://www.musinsa.com/snap/1560205304641814679 · m20 https://www.musinsa.com/snap/1551785083122597386 · f40 https://www.musinsa.com/snap/1551572173880406114 · m40 https://www.musinsa.com/snap/1556284432455808475. 4장 1:1 검수. 크롬이 2번째 장 렌더에서 멈춰 장마다 프로필을 따로 써서 다시 찍음, 인스타 API는 request limit을 돌려줬지만 실제 게시됨(ig_media_id 미기록) | 사용자 요청 (10/28) | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/28 세미정장 코디 다시(20-30대 남자만 교체: 오피서 코트·헨리넥 니트·다크 브라운 와이드 팬츠·헤비 부츠·토트백, 코디 구성을 먼저 확인받고 그림) — 킹서버 카드 24→포스트 4904, 인스타 https://www.instagram.com/p/DfBJ4SlAaok/. 참고 스냅 m20 https://www.musinsa.com/snap/1562338908609136514 (나머지 3명은 카드 23과 같음). 첫 그림은 상품 썸네일을 따라 바지가 베이지로 나와 스냅 색(브라운)으로 다시 그림 | 사용자 요청 (10/28) | `admin/scripts/daily-ootd.mjs` |
|
||||
| [x] | 10/28 연애 타로(단풍각·데이트각·별보기각, 새 표지: 주제 배지 + 큰 질문) — 킹서버 카드 26→포스트 4906, 인스타 https://www.instagram.com/p/DfBQCW0ARgL/ (ig_media_id 17953447719320497). 처음 올린 카드 25→포스트 4905(인스타 DfBPIHJAR0m)는 행운 포인트가 날씨 정보뿐이라는 피드백으로 철회: 포스트 4905 deleted=true, 인스타 글은 앱에서 삭제됨. 행운 포인트를 "시각 · 행운 아이템"(리딩 속 행동에 쓰는 물건)으로 바꿔 다시 게시. 문구를 먼저 확인받음: 첫 기획의 행운 포인트(6시 1도·10시 바람)를 예보 slot 값으로 고치고, 연애와 관련 없는 카드(해돋이각·테니스각)를 데이트각·별보기각으로 바꿈. 5장 1:1 검수. 인스타 API는 두 번 다 request limit을 돌려줬지만 실제 게시됨(최신 글 확인 후 재시도 안 함) | 사용자 요청 (10/28) | `admin/src/cards/templates.tsx`, `admin/scripts/plan.mjs` |
|
||||
| [x] | 각 카드 그림 미리 생성 — 가을에 나올 만한 28장(피크닉·캠핑·놀이공원·빨래·단풍·억새·테니스·골프·군고구마·붕어빵·군밤·사진산책·별보기·환기·세차·이불빨래·데이트·치맥·막걸리·파전·우산·넷플릭스·집콕·한강밤바람·멍뭉산책·센치·감성노래·낚시) + 기존 8 = 36/68. 여름·한겨울 전용 32장은 철 되면 생성 | 사용자 요청 (10/26) | `admin/src/assets/gak-card/` |
|
||||
| [ ] | 카드 자동화 다음 단계 — ① 생성 직후 자동 검사(Claude 비전: 옷 개수·사람·글자·추가 옷, 불합격 1회 재생성) ② 승인 대기 카드 메일/Teams 알림 + 서명 토큰 승인 링크(`GET /v1/card/{id}/approve`) ③ 맥 launchd 매일 06:30 `claude -p "/daily-cards"` ④ 그림 세트가 차면 킹서버로 이전 | 사용자 요청 (10/26) | `backend/router/v1/card/card.py`, `admin/scripts/` |
|
||||
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
|
||||
@@ -342,3 +375,14 @@
|
||||
| [x] | `mobile/` 템플릿 예제 화면·`.vscode`·`LICENSE`·README 지움, `AGENTS.md`·`.claude`는 둠 | 사용자 결정 | `mobile/` |
|
||||
| [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` |
|
||||
| [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` |
|
||||
|
||||
## 날씨게임 — 구름 합치기 (10/28)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | 바람 방향 — API에 풍향이 없어 날짜 홀짝으로 왼쪽/오른쪽을 정함. 실제 풍향(기상청 VEC)을 내려줄지 결정 | 첫 구현 (10/28) | `frontend/src/b/cloudMerge.ts` `windDir`, `backend/router/v1/weather/protocol.py` |
|
||||
| [ ] | 오늘의 판(모두 같은 순서)·구별 순위·구 대항전·공유 카드·판 깨면 각 카드 열기 — 백엔드 필요, 재미 확인 뒤 | 기획 v2 DAU 장치 | — |
|
||||
| [ ] | **[결정 필요]** 앱인토스에 넣으면 게임물 등급분류·게임 카테고리 재등록 대상인지 토스에 확인 | 앱인토스 8월 공지 | — |
|
||||
| [ ] | 들어가는 길 — 지금은 `/game` 주소로만 열림. 피드 카드·메뉴 노출 여부 결정 | 사용자 선택 (10/28) | `frontend/src/App.tsx` |
|
||||
| [ ] | 라운드 목표 점수(200 + 라운드마다 80) — 시간 제한은 없앰(사용자 10/28). 1초에 1번 아무 데나 떨어뜨리면 4~13라운드에서 넘침. 실제 사람 플레이 보고 조정 | 라운드 추가 (10/28) | `frontend/src/b/cloudMerge.ts` `roundTarget` |
|
||||
| [x] | 라운드 각 — 라운드를 깰 때마다 2각, 하루 20각(사용자 결정 10/28). 로그인한 사람만, 판 시작 표(서명)로 남의 판·위조 거절, 라운드당 15초 안 지나면 거절. 레벨업 창은 판이 끝난 뒤에 | 계정 레벨과 연결 (10/28) | `backend/services/level_service.py` `game_token`, `frontend/src/b/CloudMergePage.tsx` `claimRound` |
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"about": "경제(주식·재테크) 타로 전용 카드. topics.json 에서 deck 이 money 인 대주제는 날씨각 각 대신 이 카드에서 오늘 날씨(when)에 맞는 3장을 고른다. 그림은 src/assets/gak-card/<code>.webp (npm run gen-image -- gak-card <code>).",
|
||||
"cards": [
|
||||
{ "code": "money_bull", "name": "불장각", "icon": "sun", "description": "맑고 따뜻해 마음이 들뜨는 날, 덩달아 사고 싶어지는 정도", "when": "하루 종일 맑고 낮이 따뜻한 날(낮 최고 20도 안팎 이상)", "scene": "the rabbit and bear cheering on top of a big glossy RED upward arrow shaped like a hill, bright sunny sky, a few gold coins bouncing around" },
|
||||
{ "code": "money_hold", "name": "존버각", "icon": "umbrella", "description": "흐리거나 비 오는 날, 팔지 않고 버티기 좋은 정도", "when": "흐리거나 비 소식이 있는 날", "scene": "the bear sitting firmly on a small pile of gold coins holding an umbrella in gentle rain, calm and determined, the rabbit hugging the bear's arm" },
|
||||
{ "code": "money_split", "name": "분할매수각", "icon": "sun_cloud", "description": "아침저녁과 낮 기온 차가 큰 날, 한 번에 말고 나눠 사기 좋은 정도", "when": "아침·저녁과 낮의 기온 차가 큰 날(7도 이상)", "scene": "the rabbit carefully dropping one gold coin at a time into three small glass jars lined up in a row, morning light on one side and noon light on the other" },
|
||||
{ "code": "money_takeprofit", "name": "익절각", "icon": "gold", "description": "맑은 낮, 오른 만큼 챙겨 두기 좋은 정도", "when": "낮이 맑은 날(가장 따뜻한 시간대)", "scene": "the rabbit picking shiny golden coin-fruits from a small tree at bright noon and handing them to the bear who holds a basket" },
|
||||
{ "code": "money_stoploss", "name": "손절각", "icon": "coldwind", "description": "기온이 뚝 떨어지거나 바람이 찬 날, 미련을 끊기 좋은 정도", "when": "어제보다 기온이 크게 떨어지거나 바람이 차가운 날", "scene": "the bear calmly snipping the string of a drooping balloon with small scissors while the rabbit waves goodbye, cool wind with a few falling leaves" },
|
||||
{ "code": "money_watch", "name": "관망각", "icon": "jipkok", "description": "나가기 싫은 날, 사고팔기보다 지켜보기 좋은 정도", "when": "춥거나 흐려서 집에 있고 싶은 날", "scene": "the rabbit and bear wrapped in a blanket on a sofa, looking out the window through a toy binocular at rolling hills shaped like a gentle zigzag line" },
|
||||
{ "code": "money_avgdown", "name": "물타기각", "icon": "rain", "description": "비 오는 날, 평단 낮추기를 신중히 따져 볼 정도", "when": "비가 오는 날", "scene": "the bear carefully watering a small potted plant whose leaves are gold coins with a little watering can while light rain falls outside, the rabbit holding a tiny umbrella over the pot" },
|
||||
{ "code": "money_dividend", "name": "배당각", "icon": "sunset", "description": "해가 일찍 지는 가을·겨울 저녁, 따박따박 쌓이는 돈이 반가운 정도", "when": "가을·겨울의 맑은 저녁(해 질 녘)", "scene": "at sunset the rabbit and bear holding a basket under a tree that gently drops gold coins like acorns, warm orange sky" },
|
||||
{ "code": "money_savings", "name": "적금각", "icon": "bronze", "description": "쌀쌀하고 맑은 아침, 꾸준히 넣기 좋은 정도", "when": "아침이 쌀쌀하고(체감 10도 안팎 이하) 맑은 날", "scene": "in a crisp clear morning the rabbit wearing a small scarf dropping a plain gold coin (no symbols or marks) into a cute pastel piggy bank while the bear watches with a mug" },
|
||||
{ "code": "money_broke", "name": "텅장각", "icon": "delivery", "description": "비나 추위에 배달이 몰리는 날, 지출을 조심할 정도", "when": "비가 오거나 아주 추워 배달 주문이 몰리는 날", "scene": "the bear sitting among a stack of delivery food boxes holding an empty open wallet upside down, the rabbit peeking in surprised" }
|
||||
]
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
|
||||
const SLIDES = { tarot: 5, ootd: 4, intro: 8, foliage: 5 }
|
||||
// 기본 문구가 서비스 데이터 그대로라 Claude 기획이 꼭 필요한 템플릿 (src/cards/templates.tsx autoPlan)
|
||||
const AUTO_PLAN = ['tarot']
|
||||
// src/cards/themes.ts THEMES 의 id
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
|
||||
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { drawWithCodex } from './codex-image.mjs'
|
||||
import { extractOutfit } from './outfit.mjs'
|
||||
@@ -22,8 +22,11 @@ export async function weatherToday() {
|
||||
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
|
||||
const t = day.length ? day : withTemp
|
||||
const maxC = Math.round(Math.max(...t.map((s) => s.temp_c)))
|
||||
const morningC = Math.round((t.find((s) => hour(s) === 6) ?? t[0]).temp_c)
|
||||
const band = spec.bands.find((b) => maxC >= b.from) ?? spec.bands[spec.bands.length - 1]
|
||||
const morning = t.find((s) => hour(s) === 6) ?? t[0]
|
||||
const morningC = Math.round(morning.temp_c)
|
||||
// 낮 최고만 보면 아침·저녁 추위를 놓친다: 아침 체감과 낮 최고의 평균으로 구간을 정한다
|
||||
const feelC = ((morning.feels_c ?? morning.temp_c) + maxC) / 2
|
||||
const band = spec.bands.find((b) => feelC >= b.from) ?? spec.bands[spec.bands.length - 1]
|
||||
return { day: d.day, morningC, maxC, band: band.id, layering: band.layering ?? '' }
|
||||
}
|
||||
|
||||
@@ -38,7 +41,7 @@ function layoutFor(slots) {
|
||||
return `top row: ${topRow}; bottom row: ${bottomRow}. Clearly separate spots, nothing else in between.`
|
||||
}
|
||||
|
||||
function buildPrompt(persona, outfit, weather) {
|
||||
export function buildPrompt(persona, outfit, weather) {
|
||||
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
|
||||
const drawn = DRAW_ORDER.filter((s) => by[s])
|
||||
const items = drawn.map((s, i) => `(${i + 1}) ${by[s].prompt}${s === 'outer' ? ' as the outer layer' : ''}`).join(', ')
|
||||
@@ -60,7 +63,9 @@ export async function runDailyOotd({ outDir, style = 'minimal', log = console.lo
|
||||
const weather = await weatherToday()
|
||||
log(`오늘 ${weather.day}: 아침 ${weather.morningC}° · 낮 ${weather.maxC}° → 구간 ${weather.band} · 스타일 ${styleLabel}`)
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const picks = await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
|
||||
// 사용자가 먼저 확인한 코디(snap.mjs 가 쓴 picks.json)가 있으면 다시 고르지 않고 그대로 그린다
|
||||
const picksFile = join(outDir, 'snaps', 'picks.json')
|
||||
const picks = existsSync(picksFile) ? JSON.parse(readFileSync(picksFile, 'utf8')) : await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
|
||||
const dailyDir = resolve('public/daily')
|
||||
mkdirSync(dailyDir, { recursive: true })
|
||||
const outfits = []
|
||||
|
||||
@@ -21,7 +21,8 @@ const spec = JSON.parse(readFileSync(promptFile, 'utf8'))
|
||||
// 각 카드는 그림 목록을 따로 적지 않고 서비스의 각 목록에서 만든다
|
||||
if (spec.deck === 'gak') {
|
||||
const defs = JSON.parse(readFileSync(resolve('../backend/seed/index_definition.json'), 'utf8'))
|
||||
spec.items = defs.map((g) => ({ id: g.code, motif: spec.scene.replaceAll('{name}', g.name).replaceAll('{meaning}', g.description), name: g.name, meaning: g.description }))
|
||||
const money = JSON.parse(readFileSync(resolve('money-deck.json'), 'utf8')).cards
|
||||
spec.items = [...defs, ...money].map((g) => ({ id: g.code, motif: (g.scene ?? spec.scene).replaceAll('{name}', g.name).replaceAll('{meaning}', g.description), name: g.name, meaning: g.description }))
|
||||
}
|
||||
const outDir = resolve(`src/assets/${kind}`)
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
|
||||
@@ -43,9 +43,10 @@ function buildPrompt(pick, persona, weather) {
|
||||
goods,
|
||||
'',
|
||||
'규칙:',
|
||||
'- 자리(slot)는 top·bottom·shoes 는 반드시, 사진에서 겉옷(outer)을 입거나 걸쳤으면 outer 도, 가방이 있으면 bag 도 넣는다. 최대 5개, 자리마다 하나.',
|
||||
'- 태그된 상품에 있는 옷만 넣는다. 사진에 보여도 상품 목록에 없는 옷·가방은 넣지 않는다.',
|
||||
'- 자리(slot)는 top·bottom·shoes 는 반드시, 상품 목록에 겉옷이 있으면 outer 도, 가방이 있으면 bag 도 넣는다. 최대 5개, 자리마다 하나.',
|
||||
'- 원피스면 top 으로 넣고 bottom 은 생략하지 말고 같은 원피스를 bottom 에 다시 넣지 않는다 → 원피스는 top, bottom 자리에는 사진의 다른 하의가 없으면 shoes·bag 으로 4개를 채운다.',
|
||||
'- 상품 목록에 있는 옷은 그 상품명 기준으로, 없는 옷은 사진에서 보이는 대로. 색은 사진 기준.',
|
||||
'- 옷 이름은 상품명 기준, 색은 사진 기준.',
|
||||
'- label 은 카드 이름표라 짧고 쉬운 한글(브랜드·영어 금지). prompt 는 영어 한 구절, 색은 대문자.',
|
||||
'- style 은 코디 분위기 한 단어.',
|
||||
'JSON 으로만 답한다.',
|
||||
|
||||
@@ -20,6 +20,10 @@ const questionOf = (topic) => {
|
||||
}
|
||||
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
|
||||
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||
// 경제 전용 카드: topics.json 에서 deck 이 money 인 대주제는 이 카드에서만 고른다
|
||||
const MONEY_DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../money-deck.json'), 'utf8')).cards.map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description, when: g.when }))
|
||||
const ALL_CARDS = [...DECK, ...MONEY_DECK]
|
||||
const deckOf = (topic) => (categoryOf(topic ?? '')?.deck === 'money' ? MONEY_DECK : DECK)
|
||||
// 최근에 쓴 각은 빼서 매일 같은 카드가 나오지 않게 한다 (card.mjs 가 기획할 때마다 적는다)
|
||||
const HISTORY_FILE = resolve(import.meta.dirname, '../out/tarot-history.json')
|
||||
const HISTORY_DAYS = 7
|
||||
@@ -43,7 +47,7 @@ const RULES = [
|
||||
'카드에 들어가야 하니 칸마다 지금 문구와 비슷한 길이(최대 1.3배)로 쓴다(날씨 타로 리딩은 아래 길이 규칙을 따른다). 줄바꿈은 " ⏎ "로 표시하고, 개수를 지금 문구와 맞춘다.',
|
||||
'강조할 말은 *별표*로 감싼다. 지금 문구에 별표가 있으면 같은 자리에 둔다.',
|
||||
`아이콘 칸(i1·i2·i3)은 다음 중 하나의 파일 이름만 쓴다: ${ICONS.join(', ')}`,
|
||||
'쓰지 않는 것: 투자 권유(종목, 매수·매도, 수익·손실 단정), 건강·의료 단정, 사고·재난·정치, 특정 집단 비하, 욕설.',
|
||||
'쓰지 않는 것: 투자 권유(종목 추천, 수익·손실 단정), 건강·의료 단정, 사고·재난·정치, 특정 집단 비하, 욕설.',
|
||||
'"재미로"라는 말이 지금 문구에 있으면 남긴다.',
|
||||
'주제가 있으면 제목·카드 이름·문장을 모두 그 주제의 말로 바꾼다. 오늘 날씨 사실은 주제에 빗대는 근거로만 쓴다.',
|
||||
'날씨각의 각 요약 문장("오전 10시 14°, 바람 조금")을 그대로 옮기지 않는다. 날씨 사실은 쉬운 말로 다시 쓴다.',
|
||||
@@ -69,15 +73,18 @@ const TAROT_TONE = [
|
||||
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
|
||||
]
|
||||
|
||||
/** 오늘 고를 수 있는 각: 최근 7일에 쓴 각은 뺀다 (관리자가 고정한 카드는 남긴다) */
|
||||
function availableDeck(fixed = {}) {
|
||||
/** 오늘 고를 수 있는 각: 최근 7일에 쓴 각은 뺀다 (관리자가 고정한 카드는 남긴다). 경제 카드는 10장뿐이라 날씨로만 고른다 */
|
||||
function availableDeck(fixed = {}, topic = '') {
|
||||
const deck = deckOf(topic)
|
||||
if (deck === MONEY_DECK) return deck
|
||||
const recent = new Set(recentCodes())
|
||||
const keep = new Set(fixed.cards ?? [])
|
||||
return DECK.filter((c) => !recent.has(c.id) || keep.has(c.id))
|
||||
return deck.filter((c) => !recent.has(c.id) || keep.has(c.id))
|
||||
}
|
||||
|
||||
function tarotSection(topic, fixed = {}) {
|
||||
const deck = availableDeck(fixed)
|
||||
const deck = availableDeck(fixed, topic)
|
||||
if (deck === MONEY_DECK) return moneySection(topic)
|
||||
const excluded = DECK.filter((c) => !deck.includes(c)).map((c) => c.name)
|
||||
return [
|
||||
'',
|
||||
@@ -91,6 +98,20 @@ function tarotSection(topic, fixed = {}) {
|
||||
]
|
||||
}
|
||||
|
||||
function moneySection(topic) {
|
||||
return [
|
||||
'',
|
||||
'## 경제 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
|
||||
`표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}`,
|
||||
'제목(title) 첫 줄은 질문의 쉼표 앞부분을 그대로 쓴다(예: "오늘 내 주식"). 계좌·지갑처럼 돌려 말하지 않는다.',
|
||||
'각 카드의 "어울리는 날씨"가 오늘 날씨 데이터와 맞는 카드만 고른다. 맞는 카드가 많으면 더 잘 맞는 것, 아침·낮·저녁으로 이어지는 것을 고른다. 날씨와 안 맞는 카드는 고르지 않는다.',
|
||||
'리딩은 카드 이름(불장·존버·분할매수·익절·손절·관망·물타기·배당·적금·텅장)의 뜻을 주식·돈 관리 이야기로 직접 풀고, 오늘 날씨를 그 근거로 든다. 산책·꽃구경 같은 날씨 활동 이야기로 새지 않는다. 종목 추천·수익 단정은 하지 않는다.',
|
||||
...TAROT_TONE,
|
||||
'',
|
||||
...MONEY_DECK.map((c) => `- ${c.id}: ${c.name} — ${c.meaning} / 어울리는 날씨: ${c.when}`),
|
||||
]
|
||||
}
|
||||
|
||||
function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
|
||||
// 줄바꿈은 ⏎ 로 보여 주고 받을 때 되돌린다 (JSON 안의 \\n 을 글자로 따라 쓰는 일을 막는다)
|
||||
const fields = ctx.fields.map((f) => `- ${f.key} (${f.label}): ${String(ctx.current[f.key] ?? '').replaceAll('\n', ' ⏎ ')}`).join('\n')
|
||||
@@ -116,16 +137,16 @@ function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function schema(ctx, fixed = {}) {
|
||||
function schema(ctx, fixed = {}, topic = '') {
|
||||
const properties = { topic: { type: 'string' } }
|
||||
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
|
||||
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: availableDeck(fixed).map((c) => c.id) }
|
||||
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: availableDeck(fixed, topic).map((c) => c.id) }
|
||||
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
|
||||
}
|
||||
|
||||
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
|
||||
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
|
||||
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
||||
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed, topic)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
||||
return new Promise((done, fail) => {
|
||||
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
||||
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
||||
@@ -142,7 +163,7 @@ export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
|
||||
if (fixed.question) result.question = fixed.question
|
||||
fixed.cards?.forEach((code, i) => (result[`card${i + 1}`] = code))
|
||||
;['card1', 'card2', 'card3'].forEach((k, i) => {
|
||||
const card = DECK.find((c) => c.id === result[k])
|
||||
const card = ALL_CARDS.find((c) => c.id === result[k])
|
||||
if (card) Object.assign(result, { [`c${i + 1}`]: card.id, [`n${i + 1}`]: card.name, [`i${i + 1}`]: card.icon })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -36,15 +36,17 @@ export const PERSONAS = {
|
||||
const HEAVY = /패딩|푸퍼|다운|롱코트|울코트|무스탕|플리스|기모|헤비|퍼 /i
|
||||
const MID = /코트|자켓|재킷|점퍼|블루종|집업/i
|
||||
const SHORTS = /쇼츠|반바지|shorts|숏팬츠|버뮤다/i
|
||||
const OPEN_SHOES = /뮬|슬링백|샌들|슬리퍼|mule|slingback|sandal/i
|
||||
const MINI = /미니 ?(스커트|드레스|원피스)|mini (skirt|dress)/i
|
||||
const SHORT_SLEEVE = /반팔|하프 슬리브|half sleeve|슬리브리스|민소매|sleeveless/i
|
||||
const BAND = {
|
||||
hot: { tags: ['여름코디', '간절기코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||
warm: { tags: ['간절기코디', '가을코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||
mild: { tags: ['가을코디', '간절기코디'], rejectGoods: [HEAVY, SHORTS], rejectTags: [/겨울|패딩/] },
|
||||
cool: { tags: ['가을코디', '가을아우터'], rejectGoods: [HEAVY, SHORTS, SHORT_SLEEVE], rejectTags: [/겨울/] },
|
||||
chilly: { tags: ['가을코디', '겨울코디'], rejectGoods: [/롱패딩|헤비/, SHORTS, SHORT_SLEEVE], rejectTags: [] },
|
||||
cold: { tags: ['겨울코디'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔/] },
|
||||
freezing: { tags: ['겨울코디', '롱패딩'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔|가을/] },
|
||||
cool: { needOuter: true, tags: ['가을코디', '가을아우터'], rejectGoods: [HEAVY, SHORTS, SHORT_SLEEVE], rejectTags: [/겨울/] },
|
||||
chilly: { needOuter: true, tags: ['가을코디', '겨울코디'], rejectGoods: [MINI, OPEN_SHOES, /롱패딩|헤비/, SHORTS, SHORT_SLEEVE], rejectTags: [] },
|
||||
cold: { needOuter: true, tags: ['겨울코디'], rejectGoods: [MINI, OPEN_SHOES, SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔/] },
|
||||
freezing: { needOuter: true, tags: ['겨울코디', '롱패딩'], rejectGoods: [MINI, OPEN_SHOES, SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔|가을/] },
|
||||
}
|
||||
// 철 지난 스냅은 뺀다
|
||||
const MAX_AGE_DAYS = 45
|
||||
@@ -141,6 +143,7 @@ function fits(snap, band) {
|
||||
const slots = new Set(snap.goods.map((g) => g.slot))
|
||||
const hasTop = slots.has('top') || slots.has('onepiece')
|
||||
const hasBottom = slots.has('bottom') || slots.has('onepiece')
|
||||
if (rule.needOuter && !slots.has('outer')) return false
|
||||
return hasTop && hasBottom && slots.has('shoes') && !!snap.image
|
||||
}
|
||||
|
||||
@@ -154,6 +157,12 @@ function score(snap, persona) {
|
||||
if (goods.some((g) => /슬랙스|로퍼|니트|블라우스|코트|자켓|재킷|셔츠/.test(g.name + g.category2))) s += 0.5
|
||||
if (goods.some((g) => /카고|후드|조거|스웨트/.test(g.name + g.category2))) s -= 1
|
||||
} else if (MATURE_TAG.test(tagBlob) && !/꾸안꾸|데일리/.test(tagBlob)) s -= 0.3
|
||||
// 여자 코디는 남성적인 고프코어보다 여성스러운 쪽을 고른다
|
||||
if (PERSONAS[persona].gender === 'WOMEN') {
|
||||
if (/페미닌|러블리|걸리시|여리여리|하객룩|오피스룩/.test(tagBlob)) s += 1
|
||||
if (goods.some((g) => /블라우스|가디건|스커트|원피스|로퍼|플랫|메리제인|니트/.test(g.name + g.category2))) s += 0.7
|
||||
if (goods.some((g) => /카고|백팩|트레일|고프코어|바람막이/.test(g.name + g.category2)) || /고프코어/.test(tagBlob)) s -= 1.5
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -170,7 +179,7 @@ export async function pickSnaps({ band, style, outDir, pages = 2, log = console.
|
||||
const styleTags = STYLE_TAGS[style] ?? []
|
||||
const pool = new Map()
|
||||
const add = (list) => list.forEach((s) => s.goodsNos.length >= 3 && !pool.has(s.id) && pool.set(s.id, s))
|
||||
for (const tag of styleTags) add(await listSnaps({ tags: tag }, pages))
|
||||
for (const tag of styleTags) add(await listSnaps({ tags: tag }, pages * 3))
|
||||
for (const tag of rule.tags) add(await listSnaps({ tags: tag }, pages))
|
||||
for (const gender of ['WOMEN', 'MEN']) for (const kw of MATURE_KEYWORDS[gender]) add(await listSnaps({ keyword: kw }, 1))
|
||||
const hasStyle = (s) => styleTags.length === 0 || s.tags.some((t) => styleTags.some((st) => t.includes(st)))
|
||||
@@ -186,7 +195,7 @@ export async function pickSnaps({ band, style, outDir, pages = 2, log = console.
|
||||
const candidates = [...pool.values()]
|
||||
.filter((s) => s.gender === gender && !used.has(s.id))
|
||||
.sort((a, b) => Number(hasStyle(b)) - Number(hasStyle(a)) || score(b, persona) - score(a, persona))
|
||||
.slice(0, 25)
|
||||
.slice(0, 60)
|
||||
let best = null
|
||||
for (const c of candidates) {
|
||||
const full = c.goods ? c : await withGoods(c)
|
||||
|
||||
|
After Width: | Height: | Size: 135 KiB |
|
After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 299 KiB |
|
After Width: | Height: | Size: 248 KiB |
|
After Width: | Height: | Size: 469 KiB |
|
After Width: | Height: | Size: 318 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 263 KiB |
|
After Width: | Height: | Size: 305 KiB |
|
After Width: | Height: | Size: 302 KiB |
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"source": "한국관광공사 관광사진(공공누리 제1유형, 출처표시)",
|
||||
"spots": [
|
||||
{
|
||||
"file": "yongmunsa",
|
||||
"name": "용문사 은행나무",
|
||||
"region": "경기 양평",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-10-29",
|
||||
"photo": {
|
||||
"title": "양평 용문사",
|
||||
"by": "한국관광공사 김지호",
|
||||
"shot": "2012.10"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "namiseom",
|
||||
"name": "남이섬",
|
||||
"region": "강원 춘천",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-10-27",
|
||||
"photo": {
|
||||
"title": "남이섬",
|
||||
"by": "김효서",
|
||||
"shot": "2023.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "myeongnyundang",
|
||||
"name": "성균관 명륜당",
|
||||
"region": "서울 종로",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-10-31",
|
||||
"photo": {
|
||||
"title": "성균관",
|
||||
"by": "한국관광공사 박성근",
|
||||
"shot": "2011.10"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "gyeongbokgung",
|
||||
"name": "경복궁",
|
||||
"region": "서울 종로",
|
||||
"kind": "maple",
|
||||
"peak": "2026-11-02",
|
||||
"photo": {
|
||||
"title": "경복궁",
|
||||
"by": "라이브스튜디오",
|
||||
"shot": "2020.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "namsan",
|
||||
"name": "남산공원",
|
||||
"region": "서울 중구",
|
||||
"kind": "maple",
|
||||
"peak": "2026-11-02",
|
||||
"photo": {
|
||||
"title": "남산성곽길",
|
||||
"by": "한국관광공사 이범수",
|
||||
"shot": "2011.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "childrenpark",
|
||||
"name": "어린이대공원",
|
||||
"region": "서울 광진",
|
||||
"kind": "maple",
|
||||
"peak": "2026-11-02",
|
||||
"photo": {
|
||||
"title": "서울 어린이대공원",
|
||||
"by": "최민희",
|
||||
"shot": "2023.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "changdeokgung",
|
||||
"name": "창덕궁",
|
||||
"region": "서울 종로",
|
||||
"kind": "maple",
|
||||
"peak": "2026-11-02",
|
||||
"photo": {
|
||||
"title": "창덕궁",
|
||||
"by": "최린",
|
||||
"shot": "2023.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "deoksugung",
|
||||
"name": "덕수궁 돌담길",
|
||||
"region": "서울 중구",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-11-04",
|
||||
"photo": {
|
||||
"title": "덕수궁",
|
||||
"by": "한국관광공사 이범수",
|
||||
"shot": "2019.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "seoulforest",
|
||||
"name": "서울숲",
|
||||
"region": "서울 성동",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-11-04",
|
||||
"photo": {
|
||||
"title": "서울숲",
|
||||
"by": "임태원",
|
||||
"shot": "2023.11"
|
||||
}
|
||||
},
|
||||
{
|
||||
"file": "mulhyanggi",
|
||||
"name": "물향기수목원",
|
||||
"region": "경기 오산",
|
||||
"kind": "ginkgo",
|
||||
"peak": "2026-11-06",
|
||||
"photo": {
|
||||
"title": "물향기수목원",
|
||||
"by": "박아름",
|
||||
"shot": "2025.10"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 438 KiB |
|
After Width: | Height: | Size: 430 KiB |
|
After Width: | Height: | Size: 313 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 173 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 199 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 239 KiB |
|
After Width: | Height: | Size: 231 KiB |
|
After Width: | Height: | Size: 203 KiB |
@@ -334,7 +334,7 @@
|
||||
.slide .deco.d3 { left: 58px; top: 905px; width: 26px; height: 26px; background: var(--blue); }
|
||||
.slide .deco.d4 { right: 64px; top: 880px; width: 32px; height: 32px; }
|
||||
.slide .deco.d5 { left: 330px; top: 1160px; width: 24px; height: 24px; background: var(--blue); }
|
||||
.slide .deco.d6 { right: 330px; top: 1175px; width: 28px; height: 28px; }
|
||||
.slide .deco.d6 { right: 330px; top: 1148px; width: 28px; height: 28px; }
|
||||
|
||||
.slide[data-skin='heart'] :is(.sparkle, .deco) {
|
||||
clip-path: none;
|
||||
@@ -668,3 +668,51 @@
|
||||
.intro-cta .intro-sub { top: 470px; font-size: 48px; color: var(--rust); }
|
||||
.intro-cta .intro-note { left: 240px; right: 240px; text-align: center; }
|
||||
.intro-cta .intro-note { top: 1250px; font-size: 36px; text-align: center; }
|
||||
|
||||
/* 서울 근교 단풍 TOP 10 */
|
||||
.slide.foliage { background: #fff8eb; color: #322d32; }
|
||||
.foliage .foliage-meta { position: absolute; top: 174px; left: 80px; color: #94694e; font-size: 32px; font-weight: 700; }
|
||||
.foliage .foliage-title,
|
||||
.foliage .foliage-list-title,
|
||||
.foliage .foliage-cta-title { position: absolute; left: 80px; right: 80px; font-family: Jua, sans-serif; letter-spacing: -2px; }
|
||||
.foliage .foliage-title { top: 222px; max-width: 920px; color: #b43e29; font-size: 96px; line-height: 1.04; }
|
||||
.foliage .foliage-subtitle { position: absolute; top: 330px; left: 84px; right: 80px; color: #69584d; font-size: 38px; font-weight: 700; letter-spacing: -1px; }
|
||||
.foliage-cover-panel,
|
||||
.foliage-cta-panel { position: absolute; background: linear-gradient(140deg, #fbd0a0, #f5a96d 54%, #dd7657); border-radius: 64px; }
|
||||
.foliage-cover-panel { left: 80px; right: 80px; top: 410px; bottom: 70px; }
|
||||
.foliage .foliage-phone { position: absolute; overflow: hidden; box-sizing: content-box; width: 338px; aspect-ratio: 47 / 100; border: 15px solid #242327; border-radius: 53px; background: #fff; box-shadow: 0 28px 52px #59331c61, inset 0 0 0 2px #555; z-index: 2; }
|
||||
.foliage .foliage-phone img { display: block; width: 100%; height: 100%; object-fit: contain; }
|
||||
.foliage-cover .foliage-phone { top: 436px; left: 340px; width: 370px; transform: rotate(-4deg); }
|
||||
.foliage .foliage-leaf { position: absolute; width: 110px; height: 110px; object-fit: contain; z-index: 1; filter: drop-shadow(0 12px 10px #963c2929); }
|
||||
.foliage .foliage-leaf-a { top: 585px; left: 145px; transform: rotate(-21deg); }
|
||||
.foliage .foliage-leaf-b { top: 725px; right: 150px; transform: rotate(18deg); }
|
||||
.foliage .foliage-leaf-c { bottom: 132px; left: 165px; transform: rotate(15deg); }
|
||||
.foliage .foliage-list-title { top: 229px; font-size: 80px; line-height: 1.05; }
|
||||
.foliage .foliage-list-title em { font-style: normal; color: #c6462b; }
|
||||
.foliage .foliage-board { position: absolute; left: 80px; right: 80px; top: 350px; bottom: 160px; display: grid; gap: 22px; }
|
||||
.foliage-duo .foliage-board { grid-template-rows: repeat(2, minmax(0, 1fr)); }
|
||||
.foliage-grid .foliage-board { grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-rows: repeat(2, minmax(0, 1fr)); }
|
||||
.foliage .foliage-tile { position: relative; overflow: hidden; min-width: 0; border-radius: 38px; background: #aa7254; box-shadow: 0 12px 28px #5c382b26; }
|
||||
.foliage .foliage-tile::after { content: ''; position: absolute; inset: 20% 0 0; background: linear-gradient(transparent 18%, #1c1719c4 76%, #120f11e8); }
|
||||
.foliage .foliage-photo { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||
.foliage .foliage-rank { position: absolute; top: 22px; left: 23px; z-index: 2; display: grid; place-items: center; width: 72px; height: 72px; border-radius: 22px; background: #fff9ec; color: #b43e29; font: 64px/1 Jua, sans-serif; box-shadow: 0 5px 15px #0003; }
|
||||
.foliage .foliage-tile-copy { position: absolute; left: 28px; right: 20px; bottom: 24px; z-index: 2; color: #fff; }
|
||||
.foliage .foliage-name { display: block; overflow: hidden; color: #fff; font: 72px/1.08 Jua, sans-serif; letter-spacing: -1.7px; white-space: nowrap; text-overflow: clip; }
|
||||
.foliage-grid .foliage-name { font-size: 49px; letter-spacing: -2px; }
|
||||
.foliage .foliage-facts { display: flex; align-items: center; gap: 12px; margin-top: 10px; color: #fff; font-size: 29px; font-weight: 750; white-space: nowrap; }
|
||||
.foliage-grid .foliage-facts { gap: 7px; font-size: 22px; letter-spacing: -1px; }
|
||||
.foliage .foliage-facts > span:not(:first-child)::before { content: '·'; margin-right: 12px; opacity: .8; }
|
||||
.foliage-grid .foliage-facts > span:not(:first-child)::before { margin-right: 7px; }
|
||||
.foliage .foliage-kind { display: inline-flex; align-items: center; gap: 3px; }
|
||||
.foliage .foliage-kind img { width: 30px; height: 30px; object-fit: contain; }
|
||||
.foliage-grid .foliage-kind img { width: 23px; height: 23px; }
|
||||
.foliage .foliage-line { margin-top: 6px; color: #fff8ed; font-size: 30px; font-weight: 650; white-space: nowrap; }
|
||||
.foliage .foliage-credit { position: absolute; left: 80px; right: 80px; bottom: 70px; color: #795e4d; font-size: 23px; font-weight: 600; line-height: 1.3; }
|
||||
.foliage .foliage-cta-title { top: 220px; color: #b43e29; font-size: 82px; line-height: 1.1; }
|
||||
.foliage .foliage-cta-body { position: absolute; left: 84px; right: 80px; top: 330px; color: #69584d; font-size: 36px; font-weight: 700; }
|
||||
.foliage-cta-panel { left: 80px; right: 80px; top: 410px; bottom: 105px; }
|
||||
.foliage-cta .foliage-phone { top: 440px; left: 124px; width: 330px; transform: rotate(-4deg); }
|
||||
.foliage .foliage-actions { position: absolute; top: 790px; left: 460px; right: 112px; z-index: 3; display: flex; flex-direction: column; gap: 20px; }
|
||||
.foliage .foliage-actions span { display: block; padding: 24px 18px; border-radius: 25px; background: #fffaf0; color: #a8402d; font-size: 31px; font-weight: 800; text-align: center; box-shadow: 0 8px 18px #703c252b; white-space: nowrap; }
|
||||
.foliage .foliage-actions span + span { background: #a8402d; color: #fff; }
|
||||
.foliage .foliage-source { position: absolute; left: 80px; right: 80px; bottom: 51px; color: #795e4d; font-size: 21px; font-weight: 600; }
|
||||
@@ -1,8 +1,9 @@
|
||||
import defs from '../../../backend/seed/index_definition.json'
|
||||
import money from '../../money-deck.json'
|
||||
|
||||
/** 날씨 타로 카드 덱 = 날씨각 각 카드 (서비스와 같은 목록) */
|
||||
/** 날씨 타로 카드 덱 = 날씨각 각 카드 (서비스와 같은 목록) + 경제 전용 카드(money-deck.json) */
|
||||
export type GakCard = { code: string; name: string; icon: string; meaning: string }
|
||||
export const GAK_DECK: GakCard[] = defs.map((g) => ({ code: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||
export const GAK_DECK: GakCard[] = [...defs, ...money.cards].map((g) => ({ code: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||
export const gakByCode = (code?: string) => GAK_DECK.find((g) => g.code === code)
|
||||
|
||||
// 각 카드 앞면 그림 (Codex, npm run gen-image -- gak-card <code>). 없으면 각 아이콘
|
||||
|
||||
@@ -10,14 +10,47 @@ import { Frame, Lines } from './Frame'
|
||||
import { tidy } from './text'
|
||||
import { DEFAULT_STYLE, dailyOutfits, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
||||
import { gakArt, gakByCode } from './gaks'
|
||||
import foliageData from '../assets/foliage/seoul-2026-10-29.json'
|
||||
|
||||
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
||||
const TAROT_BG = import.meta.glob<string>('../assets/tarot-bg/*.webp', { eager: true, import: 'default' })
|
||||
// 인스타 해시태그: 고정 태그 앞에 그 포스트의 주제·카드·스타일 태그를 붙인다
|
||||
const SKIN_TAGS: Record<string, string[]> = {
|
||||
coin: ['#주식', '#주식타로', '#재테크', '#투자', '#경제', '#돈관리'],
|
||||
heart: ['#연애', '#연애타로', '#썸', '#데이트'],
|
||||
clover: ['#건강', '#건강타로', '#운동', '#다이어트'],
|
||||
star: ['#공부', '#직장인', '#취업', '#일타로'],
|
||||
sparkle: ['#관계', '#친구', '#가족', '#관계타로'],
|
||||
}
|
||||
const STYLE_TAGS: Record<string, string[]> = {
|
||||
minimal: ['#꾸안꾸', '#꾸안꾸룩', '#꾸안꾸코디'],
|
||||
casual: ['#캐주얼룩', '#캐주얼코디', '#데일리코디'],
|
||||
semi: ['#오피스룩', '#출근룩', '#세미정장'],
|
||||
formal: ['#정장코디', '#포멀룩', '#하객룩'],
|
||||
street: ['#스트릿룩', '#스트릿패션', '#스트릿코디'],
|
||||
}
|
||||
const seasonTag = () => {
|
||||
const m = new Date(Date.now() + 9 * 3600_000).getUTCMonth() + 1
|
||||
return m >= 3 && m <= 5 ? '#봄코디' : m <= 8 && m >= 6 ? '#여름코디' : m >= 9 && m <= 11 ? '#가을코디' : '#겨울코디'
|
||||
}
|
||||
const tags = (...lists: (string | undefined)[][]) => [...new Set(lists.flat().filter((t): t is string => !!t))].join(' ')
|
||||
|
||||
const tarotBg = (skin?: string) => (skin ? TAROT_BG[`../assets/tarot-bg/${skin}.webp`] : undefined)
|
||||
export const hasTarotBg = (skin?: string) => !!tarotBg(skin)
|
||||
import { iconUrl } from './icons'
|
||||
import { toneVars } from './themes'
|
||||
|
||||
const FOLIAGE_IMAGES = import.meta.glob<string>('../assets/foliage/*.webp', { eager: true, import: 'default' })
|
||||
const foliageImage = (file: string) => FOLIAGE_IMAGES[`../assets/foliage/${file}.webp`]
|
||||
// 카드에 날짜 숫자는 쓰지 않는다: 오늘이 든 주(월~일) 안이면 '이번 주 절정', 그 뒤면 '다음 주 절정'
|
||||
const foliagePeak = (date: string) => {
|
||||
const today = new Date()
|
||||
const sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() + ((7 - today.getDay()) % 7))
|
||||
return new Date(`${date}T00:00:00`) <= sunday ? '이번 주 절정' : '다음 주 절정'
|
||||
}
|
||||
const foliageCredit = (spots: typeof foliageData.spots, firstRank: number) =>
|
||||
`사진: 한국관광공사 · ${spots.map((spot, i) => `${firstRank + i}위 ${spot.photo.by.replace(/^한국관광공사\s*/, '')}`).join(' · ')}`
|
||||
|
||||
|
||||
export type Copy = Record<string, string>
|
||||
export type Field = { key: string; label: string }
|
||||
@@ -62,7 +95,7 @@ const ootd: Template = {
|
||||
post: (d, c) => ({
|
||||
title: `오늘의 코디 · ${styleLabel(c.style)}`,
|
||||
caption: `낮 최고 ${d.maxC}도, 20대부터 40대~까지 오늘 입을 옷을 넘겨 보세요`,
|
||||
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
|
||||
hashtags: tags(STYLE_TAGS[c.style ?? DEFAULT_STYLE] ?? [], [seasonTag(), '#여자코디', '#남자코디', '#20대코디', '#40대코디'], ['#날씨각', '#오늘의코디', '#OOTD', '#데일리룩', '#코디추천', '#오늘날씨']),
|
||||
}),
|
||||
warnings: (d, c) => {
|
||||
if (dailyOutfits(c)) return []
|
||||
@@ -113,7 +146,7 @@ const tarot: Template = {
|
||||
post: (_d, c) => ({
|
||||
title: c.title.replaceAll('\n', ' ').replaceAll('*', ''),
|
||||
caption: `Q. ${c.question} 1·2·3 중 한 장을 골라 보세요`,
|
||||
hashtags: '#날씨각 #날씨타로 #타로 #오늘의타로 #오늘의운세 #날씨 #오늘날씨 #서울날씨 #오늘뭐하지 #일상',
|
||||
hashtags: tags(SKIN_TAGS[c.skin ?? ''] ?? [], [c.n1, c.n2, c.n3].map((n) => (n ? `#${n.replace(/각$/, '').replace(/\s/g, '')}` : undefined)), ['#날씨각', '#날씨타로', '#타로', '#오늘의타로', '#오늘의운세', '#오늘날씨']),
|
||||
}),
|
||||
name: '날씨 타로',
|
||||
autoPlan: true,
|
||||
@@ -245,6 +278,116 @@ const tarot: Template = {
|
||||
|
||||
const INTRO_GAK_CODES = ['walk', 'camping', 'fishing', 'chimaek', 'jjamppong', 'carwash', 'laundry', 'vent', 'stars', 'hiking', 'date', 'golf']
|
||||
|
||||
const foliage: Template = {
|
||||
id: 'foliage',
|
||||
name: '서울 근교 단풍 TOP 10',
|
||||
about: '2026.10.29 기준 서울 근교 단풍 명소 10곳 · 사진 순위 5장',
|
||||
how: [
|
||||
'src/assets/foliage/seoul-2026-10-29.json의 순서가 1~10위다. 이름·지역·단풍 종류·절정 날짜와 사진 촬영자도 그 파일에서 가져온다.',
|
||||
'1장은 앱 단풍 지도, 2~4장은 명소 사진 10장(1~2위는 크게, 3~10위는 4곳씩), 5장은 앱 명소 화면을 쓴다. 날씨 예보나 Claude 기획은 쓰지 않는다.',
|
||||
'절정 날짜는 산림청 2026 단풍절정 예측 기준이다. 명소 사진은 한국관광공사 관광사진 공공누리 제1유형이므로 2~4장 아래에 촬영자와 함께 출처를 적는다.',
|
||||
'모든 문구는 관리자 화면에서 직접 고칠 수 있다. 앱 안내는 토스 검색과 weather.o2o.kr을 함께 보여 준다.',
|
||||
],
|
||||
fields: [
|
||||
{ key: 'date', label: '1장 날짜 줄' },
|
||||
{ key: 'title', label: '1장 제목' },
|
||||
{ key: 'subtitle', label: '1장 부제' },
|
||||
{ key: 'heading2', label: '2장 제목' },
|
||||
{ key: 'heading3', label: '3장 제목' },
|
||||
{ key: 'heading4', label: '4장 제목' },
|
||||
...foliageData.spots.flatMap((_, i) => {
|
||||
const n = i + 1
|
||||
return [
|
||||
{ key: `name${n}`, label: `${n}위 이름` },
|
||||
{ key: `region${n}`, label: `${n}위 지역` },
|
||||
{ key: `kind${n}`, label: `${n}위 단풍/은행` },
|
||||
{ key: `peak${n}`, label: `${n}위 절정 시기` },
|
||||
]
|
||||
}),
|
||||
{ key: 'line1', label: '1위 한 줄' },
|
||||
{ key: 'line2', label: '2위 한 줄' },
|
||||
{ key: 'credit2', label: '2장 사진 출처' },
|
||||
{ key: 'credit3', label: '3장 사진 출처' },
|
||||
{ key: 'credit4', label: '4장 사진 출처' },
|
||||
{ key: 'ctaTitle', label: '5장 제목' },
|
||||
{ key: 'ctaBody', label: '5장 본문' },
|
||||
{ key: 'button1', label: '5장 버튼 1' },
|
||||
{ key: 'button2', label: '5장 버튼 2' },
|
||||
{ key: 'source', label: '5장 출처' },
|
||||
],
|
||||
defaults: () => ({
|
||||
date: '이번 주 단풍',
|
||||
title: '서울 근교 단풍 TOP 10',
|
||||
subtitle: '멀리 안 가도 돼요, 이번 주말 가볍게',
|
||||
heading2: '1~2위', heading3: '3~6위', heading4: '7~10위',
|
||||
...Object.fromEntries(foliageData.spots.flatMap((spot, i) => {
|
||||
const n = i + 1
|
||||
return [[`name${n}`, spot.name], [`region${n}`, spot.region], [`kind${n}`, spot.kind === 'ginkgo' ? '은행' : '단풍'], [`peak${n}`, foliagePeak(spot.peak)]]
|
||||
})),
|
||||
line1: '절 마당을 덮는 천연기념물 은행나무',
|
||||
line2: '노란 잎이 깔린 메타세쿼이아·은행나무길',
|
||||
credit2: foliageCredit(foliageData.spots.slice(0, 2), 1),
|
||||
credit3: foliageCredit(foliageData.spots.slice(2, 6), 3),
|
||||
credit4: foliageCredit(foliageData.spots.slice(6, 10), 7),
|
||||
ctaTitle: '우리 동네 단풍은 지금 어디쯤?',
|
||||
ctaBody: '전국 단풍 명소 68곳, 절정 날짜를 지도로 한눈에',
|
||||
button1: "토스에서 '날씨각' 검색",
|
||||
button2: 'weather.o2o.kr',
|
||||
source: '절정 날짜: 산림청 2026 단풍절정 예측 · 사진: 한국관광공사',
|
||||
}),
|
||||
post: (_d, c) => ({
|
||||
title: c.title,
|
||||
caption: `${c.title} 🍁\n멀리 안 가도 돼요. 이번 주말 가볍게 다녀올 곳, 절정 시기 보고 골라요.\n\n전국 68곳 단풍 지도는 토스에서 '날씨각' 검색, 또는 weather.o2o.kr\n\n${c.source}\n${c.credit2}\n${c.credit3}\n${c.credit4}`,
|
||||
hashtags: '#날씨각 #서울단풍 #단풍명소 #서울근교 #가을나들이 #단풍절정 #은행나무 #주말나들이',
|
||||
}),
|
||||
slides: (_d, c) => {
|
||||
const frame = (page: number, className: string, children: ReactNode) =>
|
||||
<Frame page={page} total={5} theme="sunset" className={`foliage foliage-${className}`} key={page}>{children}</Frame>
|
||||
const phone = (file: string) => <div className="foliage-phone"><img src={foliageImage(file)} alt="날씨각 앱 단풍 지도 화면" /></div>
|
||||
const tile = (i: number) => {
|
||||
const spot = foliageData.spots[i]
|
||||
const n = i + 1
|
||||
const kind = c[`kind${n}`]
|
||||
return <div className="foliage-tile" key={spot.file}>
|
||||
<img className="foliage-photo" src={foliageImage(spot.file)} alt={c[`name${n}`]} />
|
||||
<span className="foliage-rank">{n}</span>
|
||||
<div className="foliage-tile-copy">
|
||||
<strong className="foliage-name">{c[`name${n}`]}</strong>
|
||||
<div className="foliage-facts"><span>{c[`region${n}`]}</span><span className="foliage-kind"><img src={iconUrl(kind === '은행' ? 'ginkgo' : 'maple')} alt="" />{kind}</span><span>{c[`peak${n}`]}</span></div>
|
||||
{i < 2 && <p className="foliage-line">{c[`line${n}`]}</p>}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
return [
|
||||
frame(0, 'cover', <>
|
||||
<p className="foliage-meta">{c.date}</p>
|
||||
<h1 className="foliage-title">{c.title}</h1>
|
||||
<p className="foliage-subtitle">{c.subtitle}</p>
|
||||
<div className="foliage-cover-panel" />
|
||||
{phone('app-map')}
|
||||
<img className="foliage-leaf foliage-leaf-a" src={iconUrl('maple')} alt="" />
|
||||
<img className="foliage-leaf foliage-leaf-b" src={iconUrl('ginkgo')} alt="" />
|
||||
<img className="foliage-leaf foliage-leaf-c" src={iconUrl('fallen_leaf')} alt="" />
|
||||
</>),
|
||||
...[[0, 1], [2, 3, 4, 5], [6, 7, 8, 9]].map((indices, j) => frame(j + 1, j === 0 ? 'duo' : 'grid', <>
|
||||
<p className="foliage-meta">{c.date}</p>
|
||||
<h1 className="foliage-list-title">서울 근교 단풍 <em>{c[`heading${j + 2}`]}</em></h1>
|
||||
<div className="foliage-board">{indices.map(tile)}</div>
|
||||
<p className="foliage-credit">{c[`credit${j + 2}`]}</p>
|
||||
</>)),
|
||||
frame(4, 'cta', <>
|
||||
<p className="foliage-meta">{c.date}</p>
|
||||
<h1 className="foliage-cta-title">{c.ctaTitle}</h1>
|
||||
<p className="foliage-cta-body">{c.ctaBody}</p>
|
||||
<div className="foliage-cta-panel" />
|
||||
{phone('app-spot')}
|
||||
<div className="foliage-actions"><span>{c.button1}</span><span>{c.button2}</span></div>
|
||||
<p className="foliage-source">{c.source}</p>
|
||||
</>),
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
const intro: Template = {
|
||||
id: 'intro',
|
||||
name: '날씨각 소개',
|
||||
@@ -360,6 +503,6 @@ const intro: Template = {
|
||||
},
|
||||
}
|
||||
|
||||
export const TEMPLATES: Template[] = [tarot, ootd, intro]
|
||||
export const TEMPLATES: Template[] = [tarot, ootd, intro, foliage]
|
||||
|
||||
export const templateById = (id: string) => TEMPLATES.find((t) => t.id === id)
|
||||
@@ -25,6 +25,7 @@
|
||||
"id": "money",
|
||||
"name": "경제",
|
||||
"skin": "coin",
|
||||
"deck": "money",
|
||||
"subtopics": [
|
||||
"주식",
|
||||
"재테크",
|
||||
@@ -33,7 +34,7 @@
|
||||
],
|
||||
"questions": {
|
||||
"": "오늘 내 지갑 사정은 어떨까요?",
|
||||
"주식": "오늘 내 계좌, 어떤 마음으로 바라보면 좋을까요?",
|
||||
"주식": "오늘 내 주식, 어떤 마음으로 바라보면 좋을까요?",
|
||||
"재테크": "오늘 돈 관리, 무엇부터 챙기면 좋을까요?",
|
||||
"취미": "오늘 취미에 돈 써도 괜찮을까요?",
|
||||
"여행": "이번에 떠나는 여행, 잘 풀릴까요?"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, time
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, func
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, LargeBinary, Numeric, SmallInteger, String, Text, Time, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
@@ -246,6 +246,7 @@ class Event(Base):
|
||||
area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
name: Mapped[str] = mapped_column(String(60))
|
||||
place_name: Mapped[str] = mapped_column(String(60))
|
||||
address: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
icon: Mapped[str] = mapped_column(String(30), default="fireworks")
|
||||
start_date: Mapped[date] = mapped_column(Date)
|
||||
end_date: Mapped[date] = mapped_column(Date)
|
||||
@@ -362,6 +363,11 @@ class User(Base):
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
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)
|
||||
@@ -399,6 +405,7 @@ class Comment(Base):
|
||||
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)
|
||||
ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
bot: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
@@ -446,10 +453,46 @@ class MyGak(Base):
|
||||
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
name: Mapped[str] = mapped_column(String(12))
|
||||
icon: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
rule: Mapped[dict] = mapped_column(JSONB)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PointLog(Base):
|
||||
__tablename__ = "point_log"
|
||||
|
||||
point_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
day: Mapped[date] = mapped_column(Date)
|
||||
action: Mapped[str] = mapped_column(String(20))
|
||||
ref: Mapped[str] = mapped_column(String(40), default="")
|
||||
points: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class FortuneDraw(Base):
|
||||
__tablename__ = "fortune_draw"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
day: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
card_code: Mapped[str] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class DayLog(Base):
|
||||
__tablename__ = "day_log"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
day: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||
mood: Mapped[int] = mapped_column(SmallInteger)
|
||||
went_out: Mapped[bool] = mapped_column(Boolean)
|
||||
place_name: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
place_ref: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
card_hit: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Talk(Base):
|
||||
__tablename__ = "talk"
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ class ErrorType(Enum):
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
TERMS_REQUIRED = 4005
|
||||
LEVEL_REQUIRED = 4006 # 계정 레벨이 모자라 아직 열리지 않음
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
|
||||
@@ -51,10 +51,9 @@ class Settings(BaseSettings):
|
||||
azure_blob_base_url: str = ""
|
||||
azure_blob_sas_token: str = ""
|
||||
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 Data API 로(공개·퍼가기 허용·3분 이하), 없으면 채널 쇼츠 RSS 로 받는다
|
||||
youtube_api_key: str = ""
|
||||
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
|
||||
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import exists, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Post
|
||||
from common.database.model.models import Comment, Post
|
||||
|
||||
|
||||
class FeedCRUD:
|
||||
@@ -21,6 +21,22 @@ class FeedCRUD:
|
||||
if rows:
|
||||
await s.execute(insert(Post).values(rows).on_conflict_do_nothing())
|
||||
|
||||
async def without_bot(self, s: AsyncSession, day: date) -> list[Post]:
|
||||
"""그날 포스트 중 캐릭터 댓글이 아직 없는 것."""
|
||||
has_bot = exists().where(Comment.post_id == Post.post_id, Comment.bot.is_not(None))
|
||||
return list((await s.scalars(select(Post).where(Post.feed_date == day, Post.deleted.is_(False), ~has_bot))).all())
|
||||
|
||||
async def add_bot_comments(self, s: AsyncSession, lines: dict[int, list[tuple[str, str]]]) -> None:
|
||||
"""캐릭터 댓글을 넣고 포스트 댓글 수를 늘린다. 같은 포스트·캐릭터는 한 번만 (동시에 불려도 겹치지 않게)."""
|
||||
rows = [{"post_id": post_id, "bot": bot, "body": body} for post_id, x in lines.items() for bot, body in x]
|
||||
if not rows:
|
||||
return
|
||||
added = (await s.execute(insert(Comment).values(rows).on_conflict_do_nothing().returning(Comment.post_id))).scalars().all()
|
||||
for n in (1, 2):
|
||||
ids = [post_id for post_id in set(added) if added.count(post_id) == n]
|
||||
if ids:
|
||||
await s.execute(update(Post).where(Post.post_id.in_(ids)).values(comment_count=Post.comment_count + n))
|
||||
|
||||
async def get(self, s: AsyncSession, post_id: int) -> Optional[Post]:
|
||||
post = await s.get(Post, post_id)
|
||||
return post if post is not None and not post.deleted else None
|
||||
@@ -0,0 +1,52 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import DayLog, Event, FortuneDraw, Place, SunsetSpot
|
||||
|
||||
|
||||
def _near(region_col, sido: str):
|
||||
return case((region_col.startswith(sido), 0), else_=1)
|
||||
|
||||
|
||||
class FortuneCRUD:
|
||||
async def draw_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[FortuneDraw]:
|
||||
return await s.get(FortuneDraw, (user_id, day))
|
||||
|
||||
async def add_draw(self, s: AsyncSession, user_id: uuid.UUID, day: date, card_code: str) -> FortuneDraw:
|
||||
"""그날 이미 뽑았으면 그 카드를 그대로 돌려준다 (폰과 PC 에서 동시에 뽑아도 처음 카드 하나로)"""
|
||||
await s.execute(insert(FortuneDraw).values(user_id=user_id, day=day, card_code=card_code).on_conflict_do_nothing())
|
||||
return await s.scalar(select(FortuneDraw).where(FortuneDraw.user_id == user_id, FortuneDraw.day == day))
|
||||
|
||||
async def draw_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
|
||||
return list((await s.scalars(select(FortuneDraw.day).where(FortuneDraw.user_id == user_id, FortuneDraw.day >= since))).all())
|
||||
|
||||
async def log_of(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> Optional[DayLog]:
|
||||
return await s.get(DayLog, (user_id, day))
|
||||
|
||||
async def save_log(self, s: AsyncSession, user_id: uuid.UUID, day: date, values: dict) -> DayLog:
|
||||
stmt = insert(DayLog).values(user_id=user_id, day=day, **values)
|
||||
await s.execute(stmt.on_conflict_do_update(index_elements=[DayLog.user_id, DayLog.day], set_={**values, "updated_at": func.now()}))
|
||||
return await s.scalar(select(DayLog).where(DayLog.user_id == user_id, DayLog.day == day).execution_options(populate_existing=True))
|
||||
|
||||
async def import_rows(self, s: AsyncSession, user_id: uuid.UUID, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> None:
|
||||
"""기기에 있던 기록을 계정으로. 계정에 이미 있는 날은 계정 쪽을 둔다"""
|
||||
if draws:
|
||||
await s.execute(insert(FortuneDraw).values([{"user_id": user_id, "day": d, "card_code": c} for d, c in draws]).on_conflict_do_nothing())
|
||||
if logs:
|
||||
await s.execute(insert(DayLog).values([{"user_id": user_id, "day": d, **v} for d, v in logs]).on_conflict_do_nothing())
|
||||
|
||||
async def search_places(self, s: AsyncSession, q: str, sido: str, today: date, limit: int) -> list[tuple[str, str]]:
|
||||
"""이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사. 같은 시도를 앞에. (place_ref, 이름)"""
|
||||
like = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
places = (await s.execute(select(Place.place_id, Place.name).where(Place.name.ilike(like, escape="\\")).order_by(_near(Place.region_code, sido), Place.name).limit(limit))).all()
|
||||
spots = (await s.execute(select(SunsetSpot.spot_id, SunsetSpot.name).where(SunsetSpot.name.ilike(like, escape="\\")).order_by(_near(SunsetSpot.region_code, sido), SunsetSpot.name).limit(limit))).all()
|
||||
events = (await s.execute(
|
||||
select(Event.event_id, Event.name).where(Event.name.ilike(like, escape="\\"), Event.start_date <= today, Event.end_date >= today)
|
||||
.order_by(case((Event.sido_code == sido, 0), else_=1), Event.name).limit(limit)
|
||||
)).all()
|
||||
return [(f"place:{i}", n) for i, n in places] + [(f"spot:{i}", n) for i, n in spots] + [(f"event:{i}", n) for i, n in events]
|
||||
@@ -0,0 +1,30 @@
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import PointLog, User
|
||||
|
||||
|
||||
class LevelCRUD:
|
||||
async def earned(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str) -> int:
|
||||
return await s.scalar(select(func.coalesce(func.sum(PointLog.points), 0)).where(PointLog.user_id == user_id, PointLog.day == day, PointLog.action == action))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, day: date, action: str, ref: str, points: int) -> int:
|
||||
"""같은 날 같은 일·대상이면 넣지 않는다. 넣었으면 총량에 더하고 새 총량을 돌려준다 (안 넣었으면 0)"""
|
||||
row = await s.scalar(insert(PointLog).values(user_id=user_id, day=day, action=action, ref=ref, points=points).on_conflict_do_nothing().returning(PointLog.point_id))
|
||||
if row is None:
|
||||
return 0
|
||||
return await s.scalar(update(User).where(User.user_id == user_id).values(points=User.points + points).returning(User.points))
|
||||
|
||||
async def today(self, s: AsyncSession, user_id: uuid.UUID, day: date) -> dict[str, int]:
|
||||
rows = (await s.execute(select(PointLog.action, func.sum(PointLog.points)).where(PointLog.user_id == user_id, PointLog.day == day).group_by(PointLog.action))).all()
|
||||
return {a: int(p) for a, p in rows}
|
||||
|
||||
async def attend_days(self, s: AsyncSession, user_id: uuid.UUID, since: date) -> list[date]:
|
||||
return list((await s.scalars(select(PointLog.day).where(PointLog.user_id == user_id, PointLog.action == "attend", PointLog.day >= since))).all())
|
||||
|
||||
async def points(self, s: AsyncSession, user_id: uuid.UUID) -> int:
|
||||
return await s.scalar(select(User.points).where(User.user_id == user_id)) or 0
|
||||
@@ -1,4 +1,5 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -13,8 +14,8 @@ class MyGakCRUD:
|
||||
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak:
|
||||
row = MyGak(user_id=user_id, name=name, rule=rule)
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict, icon: Optional[str] = None) -> MyGak:
|
||||
row = MyGak(user_id=user_id, name=name, rule=rule, icon=icon)
|
||||
s.add(row)
|
||||
await s.flush()
|
||||
return row
|
||||
|
||||
@@ -48,11 +48,12 @@ class WeekCRUD:
|
||||
if not rows:
|
||||
return
|
||||
# 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다
|
||||
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows]
|
||||
# 주소는 출처마다 있거나 없어서, 없는 행도 칸을 맞춰 넣는다
|
||||
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"]), "address": r.get("address")} for r in rows]
|
||||
stmt = insert(Event).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["source_id"],
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "address", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
|
||||
))
|
||||
|
||||
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
|
||||
@@ -266,6 +266,9 @@ ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
||||
-- 날씨각 캐릭터(해님 sun·구름 cloud·달님 moon)가 포스트를 만들 때 단 댓글. user_id·ip_hash 는 비고 화면엔 '날씨각' 표시가 붙는다
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS bot VARCHAR(10) NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_comment_bot ON public.comment (post_id, bot) WHERE bot IS NOT NULL;
|
||||
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -313,6 +316,48 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
|
||||
ALTER TABLE public.my_gak ADD COLUMN IF NOT EXISTS icon VARCHAR(32) NULL; -- 고른 아이콘 (각 아이콘 이름, 없으면 기본)
|
||||
|
||||
-- 계정 레벨: 날씨각에서 한 일로 모은 각 (로그인한 사람만). 레벨은 모은 총량으로 정하고, 같은 날 같은 일·대상은 한 번만 준다
|
||||
CREATE TABLE IF NOT EXISTS public.point_log (
|
||||
point_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
action VARCHAR(20) NOT NULL, -- services/level_service.py ACTIONS
|
||||
ref VARCHAR(40) NOT NULL DEFAULT '', -- 같은 날 같은 대상 중복 막기 (post:12 등)
|
||||
points SMALLINT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
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 (
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
card_code VARCHAR(32) NOT NULL, -- 각 코드 (services/fortune_deck.json)
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, day)
|
||||
);
|
||||
|
||||
-- 저녁 체크인: 그날 기분·다녀온 곳·카드가 맞았는지 (본인만 본다)
|
||||
CREATE TABLE IF NOT EXISTS public.day_log (
|
||||
user_id UUID NOT NULL,
|
||||
day DATE NOT NULL,
|
||||
mood SMALLINT NOT NULL, -- 1(가장 좋음)~5
|
||||
went_out BOOLEAN NOT NULL,
|
||||
place_name VARCHAR(40) NULL, -- 다녀온 곳 이름 (목록에서 고르거나 직접 씀)
|
||||
place_ref VARCHAR(40) NULL, -- 목록에서 고른 곳: place:<id> · spot:<id> · event:<id>
|
||||
card_hit BOOLEAN NULL, -- 오늘 카드 맞았나 (안 고르면 NULL)
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, day)
|
||||
);
|
||||
|
||||
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
|
||||
CREATE TABLE IF NOT EXISTS public.talk (
|
||||
@@ -462,6 +507,7 @@ ALTER TABLE public.event ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS address VARCHAR(120) NULL; -- 도로명 주소 (출처에 있을 때만)
|
||||
|
||||
-- 공휴일 (주말·행사 탭의 "개천절").
|
||||
CREATE TABLE IF NOT EXISTS public.holiday (
|
||||
|
||||
@@ -14,6 +14,9 @@ from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.image.image import router as image_router
|
||||
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
|
||||
@@ -48,6 +51,9 @@ app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
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)
|
||||
|
||||
@@ -13,7 +13,9 @@ from common.logger import LOG
|
||||
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
|
||||
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
|
||||
|
||||
@@ -59,6 +61,7 @@ async def _publish(card_id: int) -> tuple[ErrorType, Res_Card]:
|
||||
return err, Res_Card(result=error_info(err))
|
||||
if card is None:
|
||||
return ErrorType.NOT_FOUND, Res_Card(result=error_info(ErrorType.NOT_FOUND))
|
||||
await fill_bot_comments(day, FeedCRUD())
|
||||
await clear_feed_cache()
|
||||
LOG.info(f"[card] publish {card_id} → post {card.post_id}")
|
||||
return ErrorType.SUCCESS, Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query, Request
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.auth import optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType, PostType
|
||||
from common.enums import ErrorType
|
||||
from common.liker import Liker, liker
|
||||
from common.models.errors import error_info
|
||||
from router.v1.feed.protocol import Res_Feed, Res_Post
|
||||
@@ -13,26 +13,15 @@ from services.reaction_service import ReactionService
|
||||
|
||||
router = APIRouter(prefix="/v1/feed", tags=["feed"])
|
||||
|
||||
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
|
||||
TOSS_KNOWN_MAX = PostType.UV.value
|
||||
|
||||
|
||||
def _from_toss(request: Request) -> bool:
|
||||
ref = request.headers.get("origin") or request.headers.get("referer") or ""
|
||||
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
|
||||
|
||||
|
||||
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
|
||||
async def get_feed(
|
||||
request: Request,
|
||||
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
|
||||
service: FeedService = Depends(), reactions: ReactionService = Depends(),
|
||||
) -> Res_Feed:
|
||||
err, feed = await service.feed(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Feed(result=error_info(err))
|
||||
if _from_toss(request):
|
||||
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
|
||||
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
|
||||
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
|
||||
counts = await reactions.counts(ids)
|
||||
|
||||
@@ -5,6 +5,7 @@ from pydantic import Field
|
||||
|
||||
from common.enums import PostType, SkySituation, SlotTone
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
from router.v1.index.protocol import TrendPoint
|
||||
|
||||
|
||||
class Row(WebPacketProtocol):
|
||||
@@ -38,6 +39,8 @@ class RowsSlide(WebPacketProtocol):
|
||||
rows: list[Row] = []
|
||||
image: Optional[str] = None # 있으면 아이콘 대신 카드 전체에 사진
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달 포스트만: 빛나는 면의 비율 0~100 (아이콘 대신 이 모양으로 달을 그린다)")
|
||||
moon_waxing: Optional[bool] = Field(default=None, description="달 포스트만: 차오르는 달이면 true (오른쪽이 밝음)")
|
||||
|
||||
|
||||
class GakSlide(WebPacketProtocol):
|
||||
@@ -49,8 +52,8 @@ class GakSlide(WebPacketProtocol):
|
||||
score: int
|
||||
line: str
|
||||
summary: str
|
||||
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
|
||||
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
|
||||
trend: list[TrendPoint] = Field(default=[], description="오늘 · 내일 · 이번 주말 점수 (각 상세 날짜 칸과 같은 값)")
|
||||
|
||||
|
||||
class Cut(WebPacketProtocol):
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import DayLog, User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.fortune.protocol import (
|
||||
DayLogData, FortuneCard, FortuneLuck, FortunePlace, Req_DayLog, Req_FortuneDraw, Req_FortuneImport, Res_DayLog, Res_FortunePlaces, Res_FortuneToday,
|
||||
)
|
||||
from services.fortune_service import FortuneService, Today
|
||||
|
||||
router = APIRouter(prefix="/v1/fortune", tags=["fortune"])
|
||||
|
||||
|
||||
def _log(g: Optional[DayLog]) -> Optional[DayLogData]:
|
||||
if g is None:
|
||||
return None
|
||||
return DayLogData(day=g.day, mood=g.mood, went_out=g.went_out, place_name=g.place_name, place_ref=g.place_ref, card_hit=g.card_hit)
|
||||
|
||||
|
||||
def _today(t: Today) -> Res_FortuneToday:
|
||||
return Res_FortuneToday(
|
||||
day=t.day, streak=t.streak, checkin_open=t.checkin_open, log=_log(t.log),
|
||||
card=FortuneCard(**t.card.__dict__) if t.card else None, luck=FortuneLuck(**t.luck.__dict__) if t.luck else None,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/today", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 한 장: 로그인했으면 오늘 뽑은 카드·행운·체크인·연속 기록 (안 뽑았으면 카드 없이)")
|
||||
async def get_fortune_today(region: str = Query(..., min_length=10, max_length=10), user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
|
||||
err, t = await service.today(region, user)
|
||||
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
|
||||
|
||||
|
||||
@router.post("/draw", response_model=Res_FortuneToday, response_model_exclude_none=True, summary="오늘 카드 뽑기 (하루 한 장). 로그인 안 했으면 기기에 있는 오늘 카드를 넘기면 그 카드로 행운만 계산")
|
||||
async def draw_fortune(req: Req_FortuneDraw, user: Optional[User] = Depends(optional_user), service: FortuneService = Depends()) -> Res_FortuneToday:
|
||||
err, t = await service.draw(req.region_code, user, req.card_code, req.days)
|
||||
return Res_FortuneToday(result=error_info(err)) if err is not ErrorType.SUCCESS or t is None else _today(t)
|
||||
|
||||
|
||||
@router.put("/log", response_model=Res_DayLog, response_model_exclude_none=True, summary="오늘 저녁 체크인 저장 (로그인). 다시 보내면 고친다")
|
||||
async def save_day_log(req: Req_DayLog, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_DayLog:
|
||||
err, g = await service.save_log(user, req.region_code, req.mood, req.went_out, req.place_name, req.place_ref, req.card_hit)
|
||||
return Res_DayLog(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_DayLog(log=_log(g))
|
||||
|
||||
|
||||
@router.post("/import", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로 (계정에 있는 날은 계정 쪽을 둔다)")
|
||||
async def import_fortune(req: Req_FortuneImport, user: User = Depends(current_user), service: FortuneService = Depends()) -> Res_WebPacketProtocol:
|
||||
draws = [(d.day, d.card_code) for d in req.draws]
|
||||
logs = [(g.day, g.model_dump(exclude={"day"})) for g in req.logs]
|
||||
return Res_WebPacketProtocol(result=error_info(await service.import_local(user, draws, logs)))
|
||||
|
||||
|
||||
@router.get("/places", response_model=Res_FortunePlaces, response_model_exclude_none=True, summary="체크인에서 다녀온 곳 찾기: 이름에 q 가 들어간 데이트 명소·노을 명소·지금 하는 행사")
|
||||
async def search_fortune_places(region: str = Query(..., min_length=10, max_length=10), q: str = Query(..., max_length=20), service: FortuneService = Depends()) -> Res_FortunePlaces:
|
||||
err, rows = await service.places(region, q)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_FortunePlaces(result=error_info(err))
|
||||
return Res_FortunePlaces(items=[FortunePlace(ref=r, name=n) for r, n in rows])
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class FortuneCard(WebPacketProtocol):
|
||||
code: str = Field(description="각 코드 (카드 그림은 /fortune/<code>.webp)")
|
||||
name: str
|
||||
icon: str
|
||||
reading: str = Field(description="리딩 한 문장")
|
||||
color: str = Field(description="행운 색 이름")
|
||||
hex: str = Field(description="행운 색 #rrggbb")
|
||||
|
||||
|
||||
class FortuneLuck(WebPacketProtocol):
|
||||
time: Optional[str] = Field(None, description="행운 시간: 오늘 남은 구간 중 날씨가 가장 좋은 때 (예: 오후 4~7시)")
|
||||
place: Optional[str] = Field(None, description="행운 장소: 날씨 맞춤 데이트 명소")
|
||||
place_id: Optional[int] = None
|
||||
top_gak: Optional[str] = Field(None, description="지금 1위 각 이름")
|
||||
top_icon: Optional[str] = None
|
||||
|
||||
|
||||
class DayLogData(WebPacketProtocol):
|
||||
day: date
|
||||
mood: int = Field(ge=1, le=5, description="1(가장 좋음)~5")
|
||||
went_out: bool
|
||||
place_name: Optional[str] = None
|
||||
place_ref: Optional[str] = Field(None, description="목록에서 고른 곳: place:<id> · spot:<id> · event:<id>")
|
||||
card_hit: Optional[bool] = Field(None, description="오늘 카드 맞았나")
|
||||
|
||||
|
||||
class Res_FortuneToday(Res_WebPacketProtocol):
|
||||
day: Optional[date] = None
|
||||
card: Optional[FortuneCard] = Field(None, description="오늘 뽑은 카드. 아직 안 뽑았으면 없음")
|
||||
luck: Optional[FortuneLuck] = None
|
||||
streak: int = Field(0, description="이어 뽑은 날 수 (7일에 한 번 쉬는 날은 봐준다)")
|
||||
checkin_open: bool = Field(False, description="저녁(해 지기 2시간 전)부터 체크인")
|
||||
log: Optional[DayLogData] = Field(None, description="오늘 체크인 (로그인했을 때)")
|
||||
|
||||
|
||||
class Req_FortuneDraw(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
card_code: Optional[str] = Field(None, max_length=32, description="로그인 안 했을 때 기기에 있는 오늘 카드 (없으면 새로 뽑음)")
|
||||
days: list[date] = Field(default=[], max_length=60, description="로그인 안 했을 때 기기에 남은 뽑은 날 (연속 기록용)")
|
||||
|
||||
|
||||
class Req_DayLog(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
mood: int = Field(ge=1, le=5)
|
||||
went_out: bool
|
||||
place_name: Optional[str] = Field(None, max_length=40)
|
||||
place_ref: Optional[str] = Field(None, max_length=40)
|
||||
card_hit: Optional[bool] = None
|
||||
|
||||
|
||||
class Res_DayLog(Res_WebPacketProtocol):
|
||||
log: Optional[DayLogData] = None
|
||||
|
||||
|
||||
class LocalDraw(WebPacketProtocol):
|
||||
day: date
|
||||
card_code: str = Field(max_length=32)
|
||||
|
||||
|
||||
class LocalLog(Req_DayLog):
|
||||
day: date
|
||||
|
||||
|
||||
class Req_FortuneImport(Req_WebPacketProtocol):
|
||||
draws: list[LocalDraw] = Field(default=[], max_length=60)
|
||||
logs: list[LocalLog] = Field(default=[], max_length=60)
|
||||
|
||||
|
||||
class FortunePlace(WebPacketProtocol):
|
||||
ref: str = Field(description="place:<id> · spot:<id> · event:<id>")
|
||||
name: str
|
||||
|
||||
|
||||
class Res_FortunePlaces(Res_WebPacketProtocol):
|
||||
items: list[FortunePlace] = []
|
||||
@@ -0,0 +1,45 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.level.protocol import LevelAction, LevelStep, LevelUnlock, Req_GameRound, Res_GameStart, Res_Level
|
||||
from services.level_service import LEVELS, LevelService, Status
|
||||
|
||||
router = APIRouter(prefix="/v1/level", tags=["level"])
|
||||
|
||||
|
||||
def _res(err: ErrorType, st: Status | None) -> Res_Level:
|
||||
if err is not ErrorType.SUCCESS or st is None:
|
||||
return Res_Level(result=error_info(err))
|
||||
return Res_Level(
|
||||
points=st.points, level=st.level, name=st.name, floor=st.floor, next_points=st.next_points, next_name=st.next_name, streak=st.streak,
|
||||
today=[LevelAction(**a.__dict__) for a in st.today], unlocks=[LevelUnlock(level=lv, key=k, name=n) for lv, k, n in st.unlocks],
|
||||
levels=[LevelStep(level=i + 1, name=n, points=p) for i, (p, n) in enumerate(LEVELS)],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=Res_Level, response_model_exclude_none=True, summary="내 레벨: 모은 각, 다음 레벨, 오늘 받은 각, 레벨로 열리는 것")
|
||||
async def my_level(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.status(user))
|
||||
|
||||
|
||||
@router.post("/attend", response_model=Res_Level, response_model_exclude_none=True, summary="출석 (하루 한 번 각). 7일 이어지면 보너스")
|
||||
async def attend(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.attend(user))
|
||||
|
||||
|
||||
@router.post("/share", response_model=Res_Level, response_model_exclude_none=True, summary="공유를 마쳤을 때 (하루 한 번 각)")
|
||||
async def shared(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.share(user))
|
||||
|
||||
|
||||
@router.post("/game/start", response_model=Res_GameStart, response_model_exclude_none=True, summary="날씨게임 한 판 시작 (라운드 각을 받을 표)")
|
||||
async def game_start(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_GameStart:
|
||||
return Res_GameStart(play=service.game_start(user))
|
||||
|
||||
|
||||
@router.post("/game/round", response_model=Res_Level, response_model_exclude_none=True, summary="날씨게임 라운드를 깼을 때 (2각, 하루 20각)")
|
||||
async def game_round(req: Req_GameRound, user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.game_round(user, req.play, req.round))
|
||||
@@ -0,0 +1,47 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class LevelAction(WebPacketProtocol):
|
||||
action: str
|
||||
name: str
|
||||
points: int = Field(description="한 번에 주는 각")
|
||||
cap: int = Field(description="하루 한도")
|
||||
earned: int = Field(description="오늘 받은 각")
|
||||
|
||||
|
||||
class LevelUnlock(WebPacketProtocol):
|
||||
level: int
|
||||
key: str
|
||||
name: str
|
||||
|
||||
|
||||
class LevelStep(WebPacketProtocol):
|
||||
level: int
|
||||
name: str
|
||||
points: int = Field(description="이 레벨이 되는 각 총량")
|
||||
|
||||
|
||||
class Res_Level(Res_WebPacketProtocol):
|
||||
points: int = Field(0, description="모은 각 총량")
|
||||
level: int = 1
|
||||
name: Optional[str] = None
|
||||
floor: int = Field(0, description="지금 레벨이 시작하는 각")
|
||||
next_points: Optional[int] = Field(None, description="다음 레벨에 필요한 총량 (마지막 레벨이면 없음)")
|
||||
next_name: Optional[str] = None
|
||||
streak: int = Field(0, description="이어 출석한 날")
|
||||
today: list[LevelAction] = []
|
||||
unlocks: list[LevelUnlock] = []
|
||||
levels: list[LevelStep] = Field([], description="레벨 전체 (이름·필요한 각)")
|
||||
|
||||
|
||||
class Res_GameStart(Res_WebPacketProtocol):
|
||||
play: Optional[str] = Field(None, description="판 시작 표. 라운드를 깰 때 그대로 보낸다")
|
||||
|
||||
|
||||
class Req_GameRound(Req_WebPacketProtocol):
|
||||
play: str = Field(max_length=40)
|
||||
round: int = Field(description="방금 깬 라운드 (1부터)")
|
||||
@@ -14,7 +14,7 @@ router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
|
||||
|
||||
|
||||
def _data(g: MyGak) -> MyGakData:
|
||||
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, rule=MyGakRule(**g.rule))
|
||||
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, icon=g.icon, rule=MyGakRule(**g.rule))
|
||||
|
||||
|
||||
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
|
||||
@@ -29,7 +29,7 @@ async def list_my_gak(user: Optional[User] = Depends(optional_user), service: My
|
||||
|
||||
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기")
|
||||
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
|
||||
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True))
|
||||
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True), req.icon)
|
||||
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
|
||||
|
||||
|
||||
|
||||
@@ -29,11 +29,13 @@ class MyGakRule(WebPacketProtocol):
|
||||
class MyGakData(WebPacketProtocol):
|
||||
my_gak_id: int
|
||||
name: str
|
||||
icon: Optional[str] = Field(None, description="고른 아이콘 (각 아이콘 이름)")
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
class Req_MyGak(Req_WebPacketProtocol):
|
||||
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
|
||||
icon: Optional[str] = Field(None, pattern=r"^[a-z_]{1,32}$", description="고른 아이콘 (각 아이콘 이름)")
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
@@ -66,6 +68,7 @@ class MyGakScore(WebPacketProtocol):
|
||||
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
|
||||
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
|
||||
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
|
||||
factors: dict[str, int] = Field(default={}, description="조건별 점수 0~100 (temp·rain·wind·air·humidity, reasons 와 같은 순서)")
|
||||
|
||||
|
||||
class Res_MyGakScore(Res_WebPacketProtocol):
|
||||
|
||||
@@ -39,6 +39,7 @@ class CommentData(WebPacketProtocol):
|
||||
like_count: int
|
||||
liked: bool
|
||||
mine: bool
|
||||
official: bool = Field(default=False, description="날씨각 캐릭터(해님·구름·달님)가 단 댓글. 이름 옆에 '날씨각' 표시")
|
||||
created_at: datetime
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ router = APIRouter(prefix="/v1/reaction", tags=["reaction"])
|
||||
|
||||
def _comment(v: CommentView) -> CommentData:
|
||||
c = v.comment
|
||||
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST))
|
||||
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, official=v.official, created_at=c.created_at.astimezone(KST))
|
||||
|
||||
|
||||
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
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 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
|
||||
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,98 @@
|
||||
from datetime import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.auth import current_user, 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 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 _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
|
||||
|
||||
|
||||
@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,
|
||||
)
|
||||
@@ -22,6 +22,7 @@ class TalkData(WebPacketProtocol):
|
||||
liked: bool
|
||||
mine: bool
|
||||
created_at: datetime
|
||||
ago: str = Field(description="쓴 지 얼마나 됐는지 (방금 · 12분 전 · 3시간 전 · 1일 전 · 2주 전)")
|
||||
|
||||
|
||||
class Req_Talk(Req_WebPacketProtocol):
|
||||
|
||||
@@ -11,10 +11,10 @@ from common.enums import ErrorType, TalkTopic
|
||||
from common.liker import Liker, liker
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
|
||||
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
|
||||
from services.talk_service import TalkService, TalkView
|
||||
from services.talk_service import TalkService, TalkView, ago_text
|
||||
|
||||
router = APIRouter(prefix="/v1/talk", tags=["talk"])
|
||||
|
||||
@@ -24,6 +24,7 @@ def _data(v: TalkView) -> TalkData:
|
||||
return TalkData(
|
||||
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
|
||||
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
|
||||
ago=ago_text(t.created_at, now_kst()),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ class WeatherSlot(WebPacketProtocol):
|
||||
rain_type: Optional[RainType] = None
|
||||
rain_prob: Optional[int] = None
|
||||
humidity: Optional[int] = None
|
||||
wind_ms: Optional[float] = None
|
||||
icon: str
|
||||
tone: SlotTone
|
||||
note: str
|
||||
|
||||
@@ -28,6 +28,7 @@ def _to_slot(s: Slot) -> WeatherSlot:
|
||||
if s.row is not None:
|
||||
data.temp_c, data.feels_c = float(s.row.temp_c), float(s.row.feels_c)
|
||||
data.sky, data.rain_type, data.rain_prob, data.humidity = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob, s.row.humidity
|
||||
data.wind_ms = float(s.row.wind_ms) if s.row.wind_ms is not None else None
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""이미 만든 그날 포스트에 캐릭터 댓글을 단다 (기능을 넣은 날 한 번). 이미 달린 포스트는 건너뛴다.
|
||||
python scripts/fill_bot_comments.py 2026-10-27"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
from common.enums import ErrorType # noqa: E402
|
||||
from crud.feed_crud import FeedCRUD # noqa: E402
|
||||
from services.bot_comment import fill_bot_comments # noqa: E402
|
||||
from services.feed_service import clear_feed_cache # noqa: E402
|
||||
|
||||
|
||||
async def main(day: date) -> int:
|
||||
err = await fill_bot_comments(day, FeedCRUD())
|
||||
await clear_feed_cache()
|
||||
await DB_SESSION_MNG.stop()
|
||||
print(f"bot comments {day}: {err.name}")
|
||||
return 0 if err is ErrorType.SUCCESS else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main(date.fromisoformat(sys.argv[1]))))
|
||||
@@ -0,0 +1,648 @@
|
||||
{
|
||||
"WEATHER": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"옷차림 정하기 전에 한 번 보고 가요 ☀️"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저는 하루 종일 하늘에서 구경할게요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"시간마다 기온 보고 겉옷 챙길지 정해요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"아침이랑 낮 차이를 꼭 보세요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"좋은 하루 시작해요! 오늘도 날씨각이 챙길게요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"저는 밤에 다시 올게요 🌙"
|
||||
]
|
||||
]
|
||||
],
|
||||
"ALERT": [
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"나가기 전에 꼭 한 번 보고 가요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"다들 조심히 다녀요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"챙길 것 미리 챙겨 두면 든든해요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"퇴근길도 조심히 오세요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘은 실내 일정도 같이 생각해 봐요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"무리하지 말아요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"GAK": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘 이거 할 사람 손! 🙋"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저는 구경만 할게요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"계산 근거 누르면 왜 이 점수인지 나와요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"저녁엔 순위가 바뀌기도 해요 🌙"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"오늘 뭐 할지 고민될 땐 여기부터 봐요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"같이 갈 사람한테 보내 봐요!"
|
||||
]
|
||||
]
|
||||
],
|
||||
"SUNSET": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"노을 지면 제가 나올 차례예요 🌙"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"저 퇴근할 때 손 흔들어 주세요 🌇"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"해 지는 시간 맞춰 나가 봐요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"구름이 조금 있어야 더 붉게 물든대요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"노을 사진 찍으면 저도 보여 주세요 📸"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"저도요!"
|
||||
]
|
||||
]
|
||||
],
|
||||
"TOMORROW": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"내일 입을 옷은 미리 꺼내 두고 자요 🌙"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"내일 아침에 봬요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"내일 일정 잡기 전에 한 번 보고 가요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저도 내일 계획 세우는 중이에요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘도 수고했어요. 내일 날씨는 여기 있어요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"푹 자요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"WEEK": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이번 주 빨래할 날 미리 찍어 둬요 ☀️"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"제가 오는 날은 피해 주세요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"주중 약속 잡을 때 참고하세요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"주말까지 쭉 봐 두면 편해요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이번 주도 힘내요!"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"밤마다 응원할게요 🌙"
|
||||
]
|
||||
]
|
||||
],
|
||||
"EVENT": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"같이 갈 사람한테 보내 봐요 🎉"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"밤에 하는 거면 저도 갈게요 🌙"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"가기 전에 그날 날씨 한 번 더 봐요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"날씨 맞으면 바로 가요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이번 주에 하나쯤은 가 봐요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"실내 행사면 제가 와도 괜찮아요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"SEASON": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이맘때만 볼 수 있는 이야기예요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"놓치기 전에 한 번 가 봐요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"계절이 바뀌는 게 느껴져요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"그러게요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"읽고 나면 나가 보고 싶어져요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저도요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"TIP": [
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"오, 이건 몰랐어요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"친구한테 아는 척하기 좋아요 ☀️"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"알아 두면 쓸모 있는 이야기예요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저장해 둘게요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘의 상식 하나 챙겨 가요!"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"내일 또 하나 알려 줄게요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"QUOTE": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘 마음에 남는 말이네요 🌙"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"저장해 두고 또 봐요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이 말 들고 하루 시작해요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"좋다…"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"천천히 한 번 더 읽어 봤어요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"저도요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"WEEKEND_PLAN": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"주말 약속 정할 때 이거 보여 줘요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"제가 오는 날은 실내로 가요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"벌써 주말이 기다려져요 ☀️"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"저도요 🌙"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"계획 세워 두면 주말이 더 길어요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"맞아요!"
|
||||
]
|
||||
]
|
||||
],
|
||||
"AIR": [
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"창문 열기 전에 한 번 보고 가요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"환기는 공기 좋을 때 짧게!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"마스크 챙길지 여기서 정해요 😷"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"챙겨서 손해 볼 건 없어요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"바람이 불면 공기가 좀 나아져요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"밤에 한 번 더 확인해 봐요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"DAY_TRIP": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"주말에 훌쩍 떠나 볼까요? 🚗"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저 없는 곳으로 가면 딱이에요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"돌아오는 길 노을도 챙겨 봐요 🌇"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"좋아요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"같이 갈 사람한테 보내 봐요!"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"운전 조심해요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"MOON_FULL": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘은 제가 제일 동그란 날이에요 🌕"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"소원 하나씩 빌어요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"고개 들어 한 번 봐 주세요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"오늘은 안 가릴게요… 아마도"
|
||||
]
|
||||
]
|
||||
],
|
||||
"MOON_NEW": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘은 제가 쉬는 날이에요. 별 구경 하세요 ✨"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"별 사진 찍으면 보여 주세요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"제가 없는 밤이라 별이 더 잘 보여요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저도 오늘은 얌전히 있을게요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"MOON": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘 밤 저 한 번 올려다봐 주세요 🌙"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"제가 가리면 미안해요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"하루하루 모양이 바뀌는 걸 보는 재미가 있어요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"내일은 또 다르겠네요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"다음 보름까지 같이 세어 봐요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"좋아요!"
|
||||
]
|
||||
]
|
||||
],
|
||||
"UV": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘은 제가 좀 세요. 선크림 꼭 바르세요 ☀️"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"모자도 챙기면 좋아요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"낮에 나가면 그늘로 다녀요"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"물도 자주 마시고요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"cloud",
|
||||
"흐려도 자외선은 와요. 선크림 잊지 마세요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"맞아요!"
|
||||
]
|
||||
]
|
||||
],
|
||||
"HERO": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘 날씨 어때요? ☀️"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"창밖 한 번 보고 와요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"오늘도 날씨각이 먼저 챙겨 볼게요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"같이 봐요!"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"출근길 날씨 같이 봐요!"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"우산은 여기서 확인해요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"TODAY_GAK": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘 1위 해 본 사람? 🙋"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저는 집콕이 좋아요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"누르면 왜 이 점수인지 나와요"
|
||||
],
|
||||
[
|
||||
"moon",
|
||||
"저녁엔 순위가 바뀌기도 해요 🌙"
|
||||
]
|
||||
]
|
||||
],
|
||||
"FOLIAGE": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"단풍 보러 어디 가세요? 🍁"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"위에서 보면 정말 예뻐요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"절정 지나기 전에 꼭 가 봐요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"가까운 곳부터 찾아봐요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"EVENTS_BAND": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"이번 주 뭐 하고 놀지 여기서 골라요 🎉"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"가기 전에 날씨도 같이 봐요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"SEASON_BAND": [
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"예년 이맘때 이야기 읽는 재미가 있어요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"계절 바뀌는 거 같이 느껴 봐요"
|
||||
]
|
||||
]
|
||||
],
|
||||
"CARD": [
|
||||
[
|
||||
[
|
||||
"sun",
|
||||
"오늘 카드 저장해 두고 또 봐요 ✨"
|
||||
],
|
||||
[
|
||||
"cloud",
|
||||
"저는 두 번째 장이 좋아요"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
"moon",
|
||||
"친구한테도 보내 줘요"
|
||||
],
|
||||
[
|
||||
"sun",
|
||||
"같이 보면 더 재밌어요!"
|
||||
]
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"""날씨각 캐릭터(해님·구름·달님)가 포스트를 만들 때 다는 댓글. 문구는 bot_comment.json 에 글 종류마다 1~2줄 세트로 있다.
|
||||
포스트는 시도마다 하나라 구마다 내용이 달라, 문구엔 숫자나 그날 날씨를 단정하는 말을 넣지 않는다."""
|
||||
import json
|
||||
import random
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType, PostType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from services.calc.moon import nearest
|
||||
|
||||
BOT_NAMES = {"sun": "해님", "cloud": "구름", "moon": "달님"}
|
||||
BOT_COLORS = {"sun": "orange", "cloud": "blue", "moon": "purple"}
|
||||
_COPY: dict[str, list[list[list[str]]]] = json.loads((Path(__file__).parent / "bot_comment.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _moon_key(day: date) -> str:
|
||||
"""그날 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기. 달 포스트(FeedService._moon)와 같은 기준."""
|
||||
start = datetime.combine(day, time(12), tzinfo=KST)
|
||||
tonight = start + timedelta(hours=10)
|
||||
if start <= nearest(tonight, True) < start + timedelta(days=1):
|
||||
return "MOON_FULL"
|
||||
if start <= nearest(tonight, False) < start + timedelta(days=1):
|
||||
return "MOON_NEW"
|
||||
return "MOON"
|
||||
|
||||
|
||||
def bot_lines(post_type: PostType, day: date, seed: int) -> list[tuple[str, str]]:
|
||||
"""포스트에 달 (캐릭터, 문구) 1~2줄. 세트 하나를 고르고 1줄이면 첫 줄만, 2줄이면 둘째 줄이 첫 줄에 답한다. 같은 seed 면 늘 같다."""
|
||||
sets = _COPY.get(_moon_key(day) if post_type is PostType.MOON else post_type.name)
|
||||
if not sets:
|
||||
return []
|
||||
rng = random.Random(seed)
|
||||
pick = rng.choice(sets)
|
||||
return [(bot, body) for bot, body in pick[: rng.randint(1, len(pick))]]
|
||||
|
||||
|
||||
async def fill_bot_comments(day: date, crud: FeedCRUD) -> ErrorType:
|
||||
"""그날 포스트 중 캐릭터 댓글이 없는 것에 단다. 여러 번 불러도 한 번만 달린다."""
|
||||
err, posts = await DB_SESSION_MNG.execute_lambda(lambda s: crud.without_bot(s, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
lines = {p.post_id: bot_lines(PostType(p.post_type), p.feed_date, p.post_id) for p in posts or []}
|
||||
lines = {post_id: x for post_id, x in lines.items() if x}
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.add_bot_comments(s, lines)])
|
||||
LOG.info(f"[feed] bot comments {day} posts {len(lines)}: {err.name}")
|
||||
return err
|
||||
@@ -106,7 +106,8 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
if start is None or end is None or end < since:
|
||||
return None
|
||||
loc = ld.get("location") or {}
|
||||
sido = sido_of((loc.get("address") or {}).get("streetAddress", ""))
|
||||
address = html.unescape((loc.get("address") or {}).get("streetAddress") or "").strip()
|
||||
sido = sido_of(address)
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
@@ -115,7 +116,7 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
kind = EventKind.CONCERT
|
||||
return {
|
||||
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"place_name": place[:60], "address": address[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
|
||||
}
|
||||
@@ -59,7 +59,7 @@ def parse_seoul_festivals(items: list[dict]) -> list[dict]:
|
||||
continue
|
||||
rows.append({
|
||||
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
|
||||
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "address": html.unescape(it.get("addr") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": VIEW_URL.format(code=it["cultcode"]),
|
||||
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
|
||||
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
|
||||
|
||||
@@ -35,7 +35,7 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
|
||||
continue
|
||||
rows.append({
|
||||
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
|
||||
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"place_name": (it.get("addr1") or "")[:60], "address": (it.get("addr1") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
|
||||
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
|
||||
})
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
@@ -7,6 +9,9 @@ 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)?$")
|
||||
@@ -53,3 +58,17 @@ 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]
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
@@ -25,15 +24,17 @@ from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
|
||||
)
|
||||
from router.v1.index.protocol import TrendPoint
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
from services.bot_comment import fill_bot_comments
|
||||
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import MoonNight, nearest, night, view_line
|
||||
from services.calc.sky_score import GRADE_LABEL, sky_title
|
||||
from services.calc.sun import sun_times
|
||||
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService, slot_label
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
from services.sky_service import SkyService, SkyView, day_verdict
|
||||
@@ -315,6 +316,8 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, reg
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.insert_day(s, rows)])
|
||||
LOG.info(f"[feed] build {day} posts {len(rows)}: {err.name}")
|
||||
if err is ErrorType.SUCCESS:
|
||||
err = await fill_bot_comments(day, crud)
|
||||
return err
|
||||
|
||||
|
||||
@@ -422,7 +425,7 @@ class FeedService:
|
||||
cards.append(data)
|
||||
gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0)
|
||||
for p, item in zip(gak_posts, gak):
|
||||
cards.append(self._gak(p, item))
|
||||
cards.append(self._gak(p, item, board.day))
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
|
||||
items = [i for i in board.items if i.in_season] if board else []
|
||||
@@ -501,10 +504,11 @@ class FeedService:
|
||||
return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count,
|
||||
published_at=p.published_at.astimezone(KST))
|
||||
|
||||
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
||||
def _gak(self, p: Post, i: IndexItem, today: date) -> PostData:
|
||||
d = i.definition
|
||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, say=_band_sentence(d.sentences, i.score.score),
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend])],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
@@ -538,7 +542,11 @@ class FeedService:
|
||||
if len(soon) < rank:
|
||||
return None
|
||||
e = soon[rank - 1]
|
||||
rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
|
||||
ev = e.event
|
||||
# 장소 이름이 행사 이름과 같으면(출처에 장소가 비어 이름이 들어간 것) 빼고, 주소는 눌러서 지도로
|
||||
rows = ([Row(label="장소", value=ev.place_name, place=ev.address or ev.place_name)] if ev.place_name and ev.place_name != ev.name else [])
|
||||
rows += [Row(label="주소", value=ev.address, place=ev.address)] if ev.address and ev.address != ev.place_name else []
|
||||
rows += [Row(label="기간", value=day_range(ev.start_date, ev.end_date))]
|
||||
caption = _event_caption(e)
|
||||
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))],
|
||||
@@ -600,22 +608,25 @@ class FeedService:
|
||||
else "구름 사이로 잠깐씩 보일 수도 있어요." if view.startswith("흐려서")
|
||||
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
|
||||
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon", moon_pct=round(m.lit * 100), moon_waxing=m.waxing,
|
||||
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
|
||||
share_messages=[f"오늘 밤은 {name}이래 🌙"])
|
||||
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
|
||||
if is_full:
|
||||
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
|
||||
# 가장 둥근 순간이 낮(달이 안 보일 때)이면 그 시각 대신 뜨는 시각을 알려 준다
|
||||
daytime = 6 <= at.hour < 17
|
||||
line = (f"오늘 밤 보름달,\n{when}에 가장 둥글어요" if not daytime
|
||||
else f"오늘 밤 보름달,\n{_clock_word(m.rise_at)}에 떠요" if m.rise_at else "오늘 밤 보름달,\n저녁부터 밤새 떠 있어요")
|
||||
caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕"
|
||||
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="보이는지", value=view), *rows])],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", moon_pct=100, moon_waxing=False, rows=[Row(label="보이는지", value=view), *rows])],
|
||||
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
|
||||
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
|
||||
if stars is not None:
|
||||
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
|
||||
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
|
||||
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=rows)],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", moon_pct=0, moon_waxing=True, rows=rows)],
|
||||
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
|
||||
|
||||
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
||||
@@ -776,30 +787,6 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
|
||||
return sentences[str(lo)] if lo is not None else None
|
||||
|
||||
|
||||
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
|
||||
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
|
||||
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
|
||||
|
||||
|
||||
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
|
||||
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
|
||||
d, notes = i.definition, i.score.notes or {}
|
||||
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
|
||||
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
|
||||
rows = []
|
||||
for a in axes[:n]:
|
||||
head, _, tail = notes[a].partition(", ")
|
||||
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
|
||||
if prob:
|
||||
value = prob.group(0)
|
||||
elif a == "air" and tail:
|
||||
value = tail
|
||||
else:
|
||||
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
|
||||
rows.append(Row(label=_AXIS_NAME[a], value=value))
|
||||
return rows
|
||||
|
||||
|
||||
def _gak_caption(i: IndexItem) -> str:
|
||||
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"cards": [
|
||||
{ "code": "date", "reading": "미뤄 둔 약속, 오늘은 먼저 연락해 보세요.", "color": "코랄", "hex": "#ff7f6e" },
|
||||
{ "code": "yajang", "reading": "퇴근길에 바깥 자리 하나 잡고 오늘 얘기를 풀어 보세요.", "color": "호박색", "hex": "#e9a23b" },
|
||||
{ "code": "chimaek", "reading": "오늘 고생한 나한테 치킨 한 마리쯤은 괜찮아요.", "color": "머스터드", "hex": "#d9a400" },
|
||||
{ "code": "sentimental", "reading": "마음이 몽글한 날이에요. 오래 못 본 사람에게 안부를 보내 보세요.", "color": "라벤더", "hex": "#b8a6e3" },
|
||||
{ "code": "mood_song", "reading": "출근길 이어폰에 예전에 좋아하던 노래를 걸어 보세요.", "color": "네이비", "hex": "#25335c" },
|
||||
{ "code": "jipkok", "reading": "오늘은 약속보다 이불이 반가운 날, 쉬는 것도 일이에요.", "color": "오트밀", "hex": "#e3d7c3" },
|
||||
{ "code": "netflix", "reading": "찜만 해 둔 그 영화, 오늘 밤에 볼 차례예요.", "color": "버건디", "hex": "#7a1f2b" },
|
||||
{ "code": "pajeon", "reading": "오늘은 혼자 먹는 것보다 둘이 나눠 먹는 게 더 맛있어요.", "color": "올리브", "hex": "#7d8a3a" },
|
||||
{ "code": "bungeoppang", "reading": "주머니에 현금 한 장 챙겨 두면 길에서 작은 기쁨을 만나요.", "color": "브라운", "hex": "#8b5a2b" },
|
||||
{ "code": "sweetpotato", "reading": "손 시린 사람에게 따뜻한 걸 건네면 오래 기억돼요.", "color": "테라코타", "hex": "#c8643c" },
|
||||
{ "code": "iced_hot", "reading": "오늘은 차가운 것보다 따뜻한 한 잔이 머리를 맑게 해 줘요.", "color": "카멜", "hex": "#c19a6b" },
|
||||
{ "code": "stars", "reading": "잠들기 전 하늘을 한 번 올려다보면 고민이 작아 보여요.", "color": "짙은 파랑", "hex": "#1f3a7a" },
|
||||
{ "code": "riverwind", "reading": "저녁 바람 쐬며 걷다 보면 꼬였던 생각이 풀려요.", "color": "민트", "hex": "#9fdcc8" },
|
||||
{ "code": "photo", "reading": "오늘 본 예쁜 장면 하나를 사진으로 남겨 두세요.", "color": "피치", "hex": "#ffc2a1" },
|
||||
{ "code": "walk", "reading": "해 진 뒤 동네 한 바퀴가 생각 정리에 딱 좋아요.", "color": "세이지", "hex": "#a3b899" },
|
||||
{ "code": "running", "reading": "짧게라도 뛰어 보세요. 움직인 만큼 내일 몸이 가벼워요.", "color": "라임", "hex": "#b5d334" },
|
||||
{ "code": "picnic", "reading": "점심은 밖에서, 햇볕 아래 잠깐이 오후를 바꿔요.", "color": "버터 옐로", "hex": "#f6e27f" },
|
||||
{ "code": "drive", "reading": "창문 열고 좋아하는 길로 한 바퀴 돌면 기분이 바뀌어요.", "color": "하늘색", "hex": "#8ec5f0" },
|
||||
{ "code": "foliage", "reading": "지금 아니면 못 보는 것부터 챙기세요. 미루면 지나가요.", "color": "오렌지", "hex": "#f07a2a" },
|
||||
{ "code": "camping", "reading": "주말 계획을 오늘 정해 두면 한 주가 가벼워져요.", "color": "숲 초록", "hex": "#2f5d3a" },
|
||||
{ "code": "themepark", "reading": "오늘은 어른스럽지 않아도 돼요. 마음껏 웃어 보세요.", "color": "핫핑크", "hex": "#ff5fa2" },
|
||||
{ "code": "dog", "reading": "오늘은 누군가와 나란히 걷는 시간이 행운이에요.", "color": "크림", "hex": "#f3ead8" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import DayLog, User
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.fortune_crud import FortuneCRUD
|
||||
from services.calc.day_slot import SLOTS, slot_hours
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import IndexService, current_slot, shown_slot
|
||||
from services.level_service import award
|
||||
from services.week_service import WeekService
|
||||
|
||||
# 오늘 한 장 덱: 각 코드마다 리딩 한 문장과 행운 색. 이름·아이콘은 각 정의에서 가져온다
|
||||
DECK: dict[str, dict] = {c["code"]: c for c in json.loads((Path(__file__).parent / "fortune_deck.json").read_text(encoding="utf-8"))["cards"]}
|
||||
|
||||
# 연속 기록은 이만큼 거슬러 올라가 센다. 기기에서 옮겨 오는 기록도 이 안쪽만 받는다
|
||||
HISTORY_DAYS = 60
|
||||
# 연속 기록에서 쉬는 날은 이 간격에 한 번만 봐준다
|
||||
REST_EVERY_DAYS = 7
|
||||
PLACE_LIMIT = 8
|
||||
_PLACE_REF = re.compile(r"^(place|spot|event):\d{1,12}$")
|
||||
|
||||
|
||||
def streak(days: set[date], today: date) -> int:
|
||||
"""오늘(아직 안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수. 하루 빠진 날은 7일에 한 번 쉬는 날로 봐준다."""
|
||||
d = today if today in days else today - timedelta(days=1)
|
||||
count, rests = 0, []
|
||||
while True:
|
||||
if d in days:
|
||||
count += 1
|
||||
elif d - timedelta(days=1) in days and all((r - d).days >= REST_EVERY_DAYS for r in rests):
|
||||
rests.append(d)
|
||||
else:
|
||||
return count
|
||||
d -= timedelta(days=1)
|
||||
|
||||
|
||||
def hours_text(hours: set[int]) -> str:
|
||||
"""구간 시각(24 이상은 다음 날)을 '오후 4~7시'처럼. 끝은 마지막 시각의 다음 정각."""
|
||||
start, end = min(hours), max(hours) + 1
|
||||
|
||||
def part(h: int) -> tuple[str, int]:
|
||||
h %= 24
|
||||
word = "새벽" if h < 6 else "오전" if h < 12 else "오후"
|
||||
return word, h % 12 or 12
|
||||
|
||||
(w1, h1), (w2, h2) = part(start), part(end)
|
||||
return f"{w1} {h1}~{h2}시" if w1 == w2 else f"{w1} {h1}시~{w2} {h2}시"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Card:
|
||||
code: str
|
||||
name: str
|
||||
icon: str
|
||||
reading: str
|
||||
color: str
|
||||
hex: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Luck:
|
||||
time: Optional[str] # 오늘 남은 구간 중 날씨 점수가 가장 높은 때
|
||||
place: Optional[str] # 날씨 맞춤 데이트 명소 첫 곳
|
||||
place_id: Optional[int]
|
||||
top_gak: Optional[str] # 지금 1위 각
|
||||
top_icon: Optional[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Today:
|
||||
day: date
|
||||
card: Optional[Card]
|
||||
luck: Optional[Luck]
|
||||
streak: int
|
||||
checkin_open: bool # 저녁(해 지기 2시간 전)부터 체크인을 받는다
|
||||
log: Optional[DayLog] = None
|
||||
|
||||
|
||||
class FortuneService:
|
||||
def __init__(self, crud: FortuneCRUD = Depends(FortuneCRUD), index: IndexService = Depends(IndexService), week: WeekService = Depends(WeekService)) -> None:
|
||||
self.crud, self.index, self.week = crud, index, week
|
||||
|
||||
async def _card(self, code: str) -> Optional[Card]:
|
||||
if code not in DECK:
|
||||
return None
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
|
||||
d = next((d for d in defs or [] if d.code == code), None)
|
||||
if err is not ErrorType.SUCCESS or d is None:
|
||||
return None
|
||||
c = DECK[code]
|
||||
return Card(code=code, name=d.name, icon=d.icon, reading=c["reading"], color=c["color"], hex=c["hex"])
|
||||
|
||||
async def _luck(self, region_code: str) -> tuple[ErrorType, Optional[Luck], bool]:
|
||||
err, board = await self.index.board(region_code)
|
||||
if err is not ErrorType.SUCCESS or board is None:
|
||||
return err, None, False
|
||||
now = now_kst()
|
||||
sunset_at = sun_times(board.day, float(board.region.lat), float(board.region.lon)).sunset_at
|
||||
cur = current_slot(now, sunset_at)
|
||||
left = SLOTS[SLOTS.index(shown_slot(cur)):]
|
||||
best = max((k for k in left if k in board.weather_slots), key=lambda k: board.weather_slots[k], default=None)
|
||||
_, places, _, _ = await self.week.places(region_code, board.day, None)
|
||||
place = next((p for p in places if p.is_good), places[0] if places else None)
|
||||
top = board.ranked[0].definition if board.ranked else None
|
||||
luck = Luck(
|
||||
time=hours_text(slot_hours(board.day, sunset_at)[best]) if best else None,
|
||||
place=place.place.name if place else None, place_id=place.place.place_id if place else None,
|
||||
top_gak=top.name if top else None, top_icon=top.icon if top else None,
|
||||
)
|
||||
return ErrorType.SUCCESS, luck, cur in ("evening", "night")
|
||||
|
||||
async def _streak(self, user: User, today: date) -> tuple[ErrorType, int]:
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_days(s, user.user_id, today - timedelta(days=HISTORY_DAYS)))
|
||||
return err, streak(set(days or []), today)
|
||||
|
||||
async def today(self, region_code: str, user: Optional[User]) -> tuple[ErrorType, Optional[Today]]:
|
||||
"""로그인했으면 오늘 뽑은 카드·체크인·연속 기록. 안 뽑았으면 카드 없이"""
|
||||
today = now_kst().date()
|
||||
if user is None:
|
||||
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=0, checkin_open=False)
|
||||
err, row = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.draw_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, n = await self._streak(user, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if row is None:
|
||||
return ErrorType.SUCCESS, Today(day=today, card=None, luck=None, streak=n, checkin_open=False)
|
||||
err, luck, open_ = await self._luck(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, Today(day=today, card=await self._card(row.card_code), luck=luck, streak=n, checkin_open=open_, log=log)
|
||||
|
||||
async def draw(self, region_code: str, user: Optional[User], card_code: Optional[str], days: list[date]) -> tuple[ErrorType, Optional[Today]]:
|
||||
"""하루 한 장. 로그인했으면 그날 처음 뽑은 카드, 안 했으면 기기에 있는 오늘 카드(없으면 새로 뽑음)와 기기에 남은 뽑은 날로 연속 기록."""
|
||||
today = now_kst().date()
|
||||
fresh = random.choice(list(DECK))
|
||||
if user is not None:
|
||||
err, row = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_draw(s, user.user_id, today, fresh))
|
||||
if err is not ErrorType.SUCCESS or row is None:
|
||||
return err, None
|
||||
code = row.card_code
|
||||
await award(user.user_id, "tarot")
|
||||
err, n = await self._streak(user, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, log = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.log_of(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
else:
|
||||
code = card_code if card_code in DECK else fresh
|
||||
n, log = streak({d for d in days if today - timedelta(days=HISTORY_DAYS) <= d < today} | {today}, today), None
|
||||
card = await self._card(code)
|
||||
if card is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
err, luck, open_ = await self._luck(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, Today(day=today, card=card, luck=luck, streak=n, checkin_open=open_, log=log)
|
||||
|
||||
async def save_log(self, user: User, region_code: str, mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool]) -> tuple[ErrorType, Optional[DayLog]]:
|
||||
values = clean_log(mood, went_out, place_name, place_ref, card_hit, region_code)
|
||||
if values is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = now_kst().date()
|
||||
err, log = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.save_log(s, user.user_id, today, values))
|
||||
if err is ErrorType.SUCCESS:
|
||||
await award(user.user_id, "checkin")
|
||||
return err, log
|
||||
|
||||
async def import_local(self, user: User, draws: list[tuple[date, str]], logs: list[tuple[date, dict]]) -> ErrorType:
|
||||
"""로그인할 때 기기에 있던 뽑은 카드·체크인을 계정으로. 최근 60일, 덱에 있는 카드, 형식이 맞는 체크인만"""
|
||||
today = now_kst().date()
|
||||
since = today - timedelta(days=HISTORY_DAYS)
|
||||
ok_draws = [(d, c) for d, c in draws if since <= d <= today and c in DECK]
|
||||
ok_logs = [(d, v) for d, raw in logs if since <= d <= today and (v := clean_log(**raw)) is not None]
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.import_rows(s, user.user_id, ok_draws, ok_logs))
|
||||
return err
|
||||
|
||||
async def places(self, region_code: str, q: str) -> tuple[ErrorType, list[tuple[str, str]]]:
|
||||
q = " ".join(q.split())
|
||||
if not q:
|
||||
return ErrorType.SUCCESS, []
|
||||
today = now_kst().date()
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.search_places(s, q, region_code[:2], today, PLACE_LIMIT))
|
||||
|
||||
|
||||
def clean_log(mood: int, went_out: bool, place_name: Optional[str], place_ref: Optional[str], card_hit: Optional[bool], region_code: str) -> Optional[dict]:
|
||||
"""체크인 값 확인. 안 나갔으면 다녀온 곳은 비운다"""
|
||||
if not 1 <= mood <= 5 or not region_code:
|
||||
return None
|
||||
name = " ".join((place_name or "").split())[:40] or None
|
||||
if place_ref is not None and not _PLACE_REF.match(place_ref):
|
||||
return None
|
||||
if not went_out:
|
||||
name, place_ref = None, None
|
||||
return {"mood": mood, "went_out": went_out, "place_name": name, "place_ref": place_ref if name else None, "card_hit": card_hit, "region_code": region_code[:10]}
|
||||
@@ -0,0 +1,172 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from config.settings import settings
|
||||
from crud.level_crud import LevelCRUD
|
||||
|
||||
# 계정 레벨: 모은 각 총량으로 정한다 (쓰는 기능이 생겨도 레벨은 안 내려간다). 사용자 결정 10/28
|
||||
LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바람"), (200, "무지개"), (400, "노을"), (700, "은하수"), (1000, "별똥별")]
|
||||
|
||||
# 각을 주는 일: (한 번에 주는 각, 하루 한도, 이름). 로그인한 사람만 쌓인다
|
||||
ACTIONS: dict[str, tuple[int, int, str]] = {
|
||||
"attend": (10, 10, "출석"),
|
||||
"tarot": (10, 10, "오늘 타로 뽑기"),
|
||||
"saju": (10, 10, "날씨 사주 보기"),
|
||||
"react": (5, 10, "좋아요·댓글"),
|
||||
"talk": (20, 20, "동네 이야기 글쓰기"),
|
||||
"checkin": (10, 10, "저녁 체크인"),
|
||||
"share": (10, 10, "공유하기"),
|
||||
"game": (2, 20, "날씨게임 라운드 깨기"),
|
||||
"streak": (50, 50, "7일 연속 출석"),
|
||||
}
|
||||
STREAK_DAYS = 7
|
||||
# 날씨게임 점수는 폰에서 계산해 조작될 수 있다. 하루 한도로 막고, 판 시작부터 라운드당 이만큼은 지나야 받는다
|
||||
GAME_ROUND_MIN_SEC = 15
|
||||
GAME_MAX_SEC = 3 * 60 * 60
|
||||
GAME_MAX_ROUND = 100
|
||||
STREAK_LOOKBACK = 60
|
||||
|
||||
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
|
||||
UNLOCKS: dict[int, list[tuple[str, str]]] = {
|
||||
2: [("saju_week", "날씨 사주 7일 흐름")],
|
||||
3: [("saju_money", "금전운 · 일운")],
|
||||
4: [("saju_love", "연애운")],
|
||||
5: [("saju_match", "궁합")],
|
||||
6: [("saju_month", "이달 운")],
|
||||
7: [("saju_year", "올해 운")],
|
||||
}
|
||||
|
||||
|
||||
def level_of(points: int) -> int:
|
||||
return max(i + 1 for i, (need, _) in enumerate(LEVELS) if points >= need)
|
||||
|
||||
|
||||
def unlock_level(key: str) -> int:
|
||||
return next((lv for lv, items in UNLOCKS.items() if any(k == key for k, _ in items)), 1)
|
||||
|
||||
|
||||
def is_unlocked(points: int, key: str) -> bool:
|
||||
return level_of(points) >= unlock_level(key)
|
||||
|
||||
|
||||
def game_token(user_id: uuid.UUID, ts: int) -> str:
|
||||
"""판 시작 표: 시작 시각과 서명. 그 사람만 쓸 수 있다"""
|
||||
sig = hmac.new(settings.jwt_access_secret.encode(), f"game:{user_id}:{ts}".encode(), hashlib.sha256).hexdigest()[:16]
|
||||
return f"{ts}.{sig}"
|
||||
|
||||
|
||||
def game_round_ok(user_id: uuid.UUID, play: str, round_no: int, now: int) -> bool:
|
||||
ts, _, _ = play.partition(".")
|
||||
if not ts.isdigit() or not hmac.compare_digest(game_token(user_id, int(ts)), play):
|
||||
return False
|
||||
elapsed = now - int(ts)
|
||||
return 1 <= round_no <= GAME_MAX_ROUND and round_no * GAME_ROUND_MIN_SEC <= elapsed <= GAME_MAX_SEC
|
||||
|
||||
|
||||
def streak(days: set[date], today: date) -> int:
|
||||
"""오늘부터 거꾸로 이어 출석한 날 수"""
|
||||
n = 0
|
||||
while today - timedelta(days=n) in days:
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
async def award(user_id: uuid.UUID, action: str, ref: str = "") -> int:
|
||||
"""각을 준다. 하루 한도·같은 대상 중복이면 주지 않는다. 본래 동작을 막지 않게 실패는 로그만 남긴다. 새 총량(안 줬으면 0)"""
|
||||
per, cap, _ = ACTIONS[action]
|
||||
day = now_kst().date()
|
||||
crud = LevelCRUD()
|
||||
err, earned = await DB_SESSION_MNG.execute_lambda(lambda s: crud.earned(s, user_id, day, action))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[level] 각 조회 실패 {action}")
|
||||
return 0
|
||||
if earned >= cap:
|
||||
return 0
|
||||
points = min(per, cap - earned)
|
||||
err, total = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add(s, user_id, day, action, ref, points))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[level] 각 적립 실패 {action}")
|
||||
return 0
|
||||
if action == "attend" and total:
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: crud.attend_days(s, user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
||||
n = streak(set(days or []), day) if err is ErrorType.SUCCESS else 0
|
||||
if n and n % STREAK_DAYS == 0:
|
||||
more = await award(user_id, "streak", str(n))
|
||||
total = more or total
|
||||
return total or 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class TodayAction:
|
||||
action: str
|
||||
name: str
|
||||
points: int # 한 번에 주는 각
|
||||
cap: int
|
||||
earned: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Status:
|
||||
points: int
|
||||
level: int
|
||||
name: str
|
||||
floor: int # 지금 레벨이 시작하는 각
|
||||
next_points: Optional[int] # 다음 레벨까지 필요한 총량 (마지막 레벨이면 없음)
|
||||
next_name: Optional[str]
|
||||
streak: int
|
||||
today: list[TodayAction]
|
||||
unlocks: list[tuple[int, str, str]] # (레벨, 키, 이름)
|
||||
|
||||
|
||||
class LevelService:
|
||||
def __init__(self, crud: LevelCRUD = Depends(LevelCRUD)) -> None:
|
||||
self.crud = crud
|
||||
|
||||
async def status(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
day = now_kst().date()
|
||||
err, points = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.points(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, today = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.today(s, user.user_id, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.attend_days(s, user.user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
lv = level_of(points)
|
||||
floor, name = LEVELS[lv - 1]
|
||||
nxt = LEVELS[lv] if lv < len(LEVELS) else None
|
||||
return ErrorType.SUCCESS, Status(
|
||||
points=points, level=lv, name=name, floor=floor, next_points=nxt[0] if nxt else None, next_name=nxt[1] if nxt else None,
|
||||
streak=streak(set(days), day),
|
||||
today=[TodayAction(action=a, name=n, points=p, cap=c, earned=(today or {}).get(a, 0)) for a, (p, c, n) in ACTIONS.items() if a != "streak"],
|
||||
unlocks=[(lv_, k, n) for lv_, items in UNLOCKS.items() for k, n in items],
|
||||
)
|
||||
|
||||
async def attend(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
await award(user.user_id, "attend")
|
||||
return await self.status(user)
|
||||
|
||||
async def share(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
await award(user.user_id, "share")
|
||||
return await self.status(user)
|
||||
|
||||
def game_start(self, user: User) -> str:
|
||||
return game_token(user.user_id, int(time.time()))
|
||||
|
||||
async def game_round(self, user: User, play: str, round_no: int) -> tuple[ErrorType, Optional[Status]]:
|
||||
if game_round_ok(user.user_id, play, round_no, int(time.time())):
|
||||
await award(user.user_id, "game", f"{play}:{round_no}")
|
||||
return await self.status(user)
|
||||
@@ -40,7 +40,7 @@ class MyGakService:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
|
||||
return err, rows or []
|
||||
|
||||
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
async def add(self, user: User, name: str, rule: dict, icon: Optional[str] = None) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
name = gak_name(name)
|
||||
if name is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
@@ -49,7 +49,7 @@ class MyGakService:
|
||||
return err, None
|
||||
if n >= MAX_PER_USER:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule, icon))
|
||||
|
||||
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
|
||||
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
|
||||
@@ -79,5 +79,6 @@ class MyGakService:
|
||||
"score": res.score if res else None, "slot": key if res else None,
|
||||
"slots": {k: v.score for k, v in picked.items()},
|
||||
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
|
||||
"factors": {a: res.factors[a] for a in axes(r) if res.notes.get(a) and a in res.factors} if res else {},
|
||||
})
|
||||
return ErrorType.SUCCESS, (now_slot, out)
|
||||
@@ -13,6 +13,8 @@ from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from services.bot_comment import BOT_COLORS, BOT_NAMES
|
||||
from services.level_service import award
|
||||
from services.talk_service import _LINK, _PHONE
|
||||
|
||||
COMMENT_MAX = 60
|
||||
@@ -31,6 +33,7 @@ class CommentView:
|
||||
mood: Optional[str]
|
||||
liked: bool
|
||||
mine: bool
|
||||
official: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -53,7 +56,10 @@ class ReactionService:
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
if err is ErrorType.SUCCESS and on and who.user_id is not None:
|
||||
await award(who.user_id, "react", f"post:{post_id}")
|
||||
return err, count
|
||||
|
||||
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
|
||||
err = await self._post_exists(post_id)
|
||||
@@ -87,6 +93,8 @@ class ReactionService:
|
||||
|
||||
@staticmethod
|
||||
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
|
||||
if c.bot is not None:
|
||||
return CommentView(comment=c, nickname=BOT_NAMES.get(c.bot, "날씨각"), character=c.bot, color=BOT_COLORS.get(c.bot, ANON_COLOR), mood=None, liked=liked, mine=False, official=True)
|
||||
if c.user_id is None:
|
||||
mine = who.user_id is None and c.ip_hash == who.ip_hash
|
||||
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
|
||||
@@ -135,6 +143,7 @@ class ReactionService:
|
||||
return err, None
|
||||
if user is None:
|
||||
return err, self._view(c, None, None, None, None, False, who)
|
||||
await award(user.user_id, "react", f"comment:{c.comment_id}")
|
||||
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
|
||||
|
||||
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
|
||||
|
||||
@@ -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,507 @@
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""날씨 사주 화면 문장. 엔진(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 = {
|
||||
"천간합": "어울려요", "육합": "어울려요", "반합": "어울려요", "삼합": "한데 묶여요",
|
||||
"천간충": "부딪혀요", "충": "부딪혀요", "형": "엇갈려요", "삼형": "엇갈려요", "자형": "겹쳐 부담돼요",
|
||||
"파": "틀어져요", "해": "어긋나요", "원진": "서로 꺼려요",
|
||||
}
|
||||
|
||||
# (관계, 자리) → 조심할 것. 자리가 없으면 관계만으로. 지지 관계의 일(日) 자리는 연인·배우자 자리(일지)
|
||||
AVOID_TEXT: dict[tuple[str, str], str] = {
|
||||
("원진", "day"): "연인·가까운 사람의 말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.",
|
||||
("충", "day"): "가까운 사람과 의견이 부딪히기 쉬워요. 서로 원하는 걸 먼저 확인하세요.",
|
||||
("충", "month"): "회사·집안 일정이 바뀌기 쉬워요. 이직·이사처럼 큰 결정은 오늘 확정하지 마세요.",
|
||||
("충", "year"): "밖에서 잡힌 일정이 바뀌기 쉬워요. 약속 시간과 장소를 다시 확인하세요.",
|
||||
("충", "hour"): "계획대로 안 풀리기 쉬워요. 일정 사이에 여유를 두세요.",
|
||||
("원진", ""): "말이 서운하게 들리기 쉬워요. 메시지는 보내기 전에 한 번 더 읽어 보세요.",
|
||||
("형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("삼형", ""): "서류·계약·약속은 한 번 더 확인하세요.",
|
||||
("자형", ""): "같은 고민을 계속 붙잡기 쉬워요. 적어 두고 일찍 쉬세요.",
|
||||
("파", ""): "약속이 틀어지기 쉬워요. 시간과 장소를 다시 확인하세요.",
|
||||
("해", ""): "좋은 뜻으로 한 일이 오해를 사기 쉬워요. 부탁받은 일은 범위부터 정하세요.",
|
||||
("천간충", ""): "마음이 오락가락하기 쉬워요. 결정할 일은 하나씩 정리하세요.",
|
||||
}
|
||||
# 비겁이 많고 재성이 있는 원국에 비겁 날 (군겁쟁재)
|
||||
CROWDED_RIVALS = "돈을 빌려주거나 같이 투자하는 건 오늘 미루세요."
|
||||
CROWDED_WHY = "내 사주에 나와 같은 기운이 많은데 오늘도 같은 기운이 들어와요({god})"
|
||||
|
||||
# 지지 합이 든 자리 → 좋은 흐름. 일간과 천간합이면 STEM_GOOD
|
||||
GOOD_TEXT = {
|
||||
"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일 중엔 발표·면접 잡기 좋은 날이 따로 없어요."
|
||||
|
||||
# 연애 기운이 드는 이유 → (한 줄, 이유 말)
|
||||
LOVE_GOOD = {
|
||||
"도화": ("눈에 잘 띄는 날이에요. 모임이나 소개팅에 나가 보세요.", "눈에 띄는 기운(도화)"),
|
||||
"홍염": ("매력이 잘 드러나는 날이에요. 관심 있는 사람에게 먼저 연락해 보세요.", "매력의 기운(홍염)"),
|
||||
"일지합": ("연인과 마음이 잘 맞는 날이에요. 데이트 약속을 잡아 보세요.", "연인 자리와 어울림(일지 합)"),
|
||||
"재성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(재성)"),
|
||||
"관성": ("이성 인연이 들어오는 날이에요. 마음에 둔 사람에게 연락해 보세요.", "이성 인연(관성)"),
|
||||
}
|
||||
LOVE_BAD = {
|
||||
"원진": "말이 서운하게 들리기 쉬워요. 무슨 뜻인지 먼저 물어보세요.",
|
||||
"충": "의견이 부딪히기 쉬워요. 중요한 이야기는 다른 날로 미루세요.",
|
||||
"형": "오해가 생기기 쉬워요. 메시지보다 직접 말하세요.",
|
||||
"자형": "혼자 속앓이하기 쉬워요. 서운한 건 담아 두지 말고 말하세요.",
|
||||
}
|
||||
LOVE_BAD_WHY = {"원진": "연인 자리와 서로 꺼림(일지 원진)", "충": "연인 자리와 부딪힘(일지 충)", "형": "연인 자리와 엇갈림(일지 형)", "자형": "연인 자리에 같은 글자가 겹침(일지 자형)"}
|
||||
LOVE_WET = "{word} 예보가 있으니 실내 데이트로 잡으세요."
|
||||
|
||||
# 내 기운: 태어난 계절 × 원국의 결
|
||||
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]]) + " 날씨"
|
||||
|
||||
|
||||
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_AXIS = {"temp": "한 사람은 따뜻하고 한 사람은 서늘한 기운이라", "moist": "한 사람은 촉촉하고 한 사람은 건조한 기운이라"}
|
||||
MATCH_CLIMATE_OK = "{axis} 서로 모자란 걸 채워 줘요."
|
||||
MATCH_CLIMATE_SAME = "둘 다 {need}가 맞는 기운이라, 그런 날 함께 나가면 좋아요."
|
||||
|
||||
# 이달 · 올해: 그 간지 천간 십성 → (제목, 설명)
|
||||
MONTH_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("내 페이스대로 가는 달", "남에게 기대기보다 내 손으로 일을 끝내기 좋은 달이에요."),
|
||||
"겁재": ("내 몫을 챙겨야 하는 달", "같이 하는 일은 몫부터 정해 두세요. 돈 빌려주기·같이 투자하기는 서두르지 마세요."),
|
||||
"식신": ("여유가 생기는 달", "취미·맛집·여행처럼 나를 위한 일에 시간을 쓰세요."),
|
||||
"상관": ("말솜씨가 살아나는 달", "발표·제안·글쓰기처럼 내 생각을 꺼내는 일을 해 보세요."),
|
||||
"편재": ("새 기회가 보이는 달", "새 제안과 사람이 많이 찾아오는 달이에요. 큰돈이 드는 일은 조건을 따져 보고 정하세요."),
|
||||
"정재": ("알뜰하게 모으는 달", "저축·가계부 정리처럼 돈을 차곡차곡 챙기기 좋은 달이에요."),
|
||||
"편관": ("책임이 무거운 달", "맡는 일이 많아지는 달이에요. 할 일을 나눠 우선순위부터 정하세요."),
|
||||
"정관": ("평판을 쌓는 달", "약속과 마감을 잘 지키면 믿음을 얻기 좋은 달이에요."),
|
||||
"편인": ("생각이 깊어지는 달", "공부·기획처럼 혼자 파고드는 일이 잘 맞아요."),
|
||||
"정인": ("배우기 좋은 달", "공부를 시작하거나 아는 사람에게 도움을 청해 보세요."),
|
||||
}
|
||||
YEAR_TEXT: dict[str, tuple[str, str]] = {
|
||||
"비견": ("홀로서기 좋은 해", "내 이름으로 하는 일을 시작하고 키우기 좋은 해예요."),
|
||||
"겁재": ("내 몫을 챙겨야 하는 해", "동업·공동 투자는 몫과 역할을 문서로 정해 두세요."),
|
||||
"식신": ("하고 싶은 걸 하는 해", "좋아하는 일을 꾸준히 키우고 몸을 챙기기 좋은 해예요."),
|
||||
"상관": ("나를 드러내는 해", "창작·발표처럼 내 실력을 보여 주는 일이 잘 맞는 해예요."),
|
||||
"편재": ("기회가 넓어지는 해", "새 사람·새 수입원이 생기기 쉬운 해예요. 크게 벌이는 일은 나눠서 하세요."),
|
||||
"정재": ("차곡차곡 모으는 해", "저축하고 고정 수입을 늘리기 좋은 해예요."),
|
||||
"편관": ("책임이 커지는 해", "맡는 일이 무거워지는 해예요. 혼자 다 떠안지 말고 도움받을 일을 나누세요."),
|
||||
"정관": ("인정받기 좋은 해", "승진·자격시험처럼 정해진 길을 밟는 일이 잘 풀리는 해예요."),
|
||||
"편인": ("방향을 다시 잡는 해", "공부하거나 진로를 다시 생각해 보기 좋은 해예요."),
|
||||
"정인": ("배움과 도움이 많은 해", "공부·자격증을 시작하거나 멘토를 찾기 좋은 해예요."),
|
||||
}
|
||||
@@ -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 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
|
||||
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
items = await self._fetch(client)
|
||||
except (httpx.HTTPError, KeyError, ValueError) as e:
|
||||
except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) as e:
|
||||
LOG.error(f"[shorts] fetch: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
try:
|
||||
@@ -45,7 +45,6 @@ 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)
|
||||
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]
|
||||
else:
|
||||
found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS)
|
||||
return [{"id": v["id"], "title": v["title"]} for v in found]
|
||||
@@ -14,6 +14,7 @@ from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.talk_crud import TalkCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.level_service import award
|
||||
from services.talk_image import is_ours
|
||||
|
||||
BODY_MAX = 100
|
||||
@@ -66,6 +67,20 @@ def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
|
||||
return age - near - LIKE_H * math.log2(1 + t.like_count)
|
||||
|
||||
|
||||
def ago_text(at: datetime, now: datetime) -> str:
|
||||
"""글 시간: 방금 · N분 전 · N시간 전 · N일 전 · N주 전 (하루가 넘으면 시간 대신 날로)"""
|
||||
minutes = max(0, int((now - at).total_seconds() // 60))
|
||||
if minutes < 5:
|
||||
return "방금"
|
||||
if minutes < 60:
|
||||
return f"{minutes}분 전"
|
||||
hours = minutes // 60
|
||||
if hours < 24:
|
||||
return f"{hours}시간 전"
|
||||
days = hours // 24
|
||||
return f"{days}일 전" if days < 7 else f"{days // 7}주 전"
|
||||
|
||||
|
||||
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
|
||||
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
|
||||
out: list[TalkView] = []
|
||||
@@ -190,6 +205,7 @@ class TalkService:
|
||||
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err, None
|
||||
await award(user.user_id, "talk", str(t.talk_id))
|
||||
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
|
||||
|
||||
async def delete(self, user: User, talk_id: int) -> ErrorType:
|
||||
|
||||
@@ -73,6 +73,15 @@ def _no_seoul_crawl(monkeypatch):
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_bot_comments(monkeypatch):
|
||||
"""사람이 단 댓글·좋아요만 세는 테스트용: 포스트를 만들 때 캐릭터 댓글을 달지 않는다 (캐릭터 댓글은 test_bot_comment)."""
|
||||
import services.feed_service as feed_service
|
||||
from common.enums import ErrorType
|
||||
|
||||
monkeypatch.setattr(feed_service, "fill_bot_comments", lambda *a: _async(ErrorType.SUCCESS))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
|
||||
@@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
pytestmark = pytest.mark.usefixtures("no_bot_comments")
|
||||
IP_A = {"X-Forwarded-For": "203.0.113.10"}
|
||||
IP_B = {"X-Forwarded-For": "203.0.113.20"}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
pytestmark = pytest.mark.usefixtures("no_bot_comments")
|
||||
|
||||
|
||||
def client():
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import KST
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from router.router import app
|
||||
from services.bot_comment import _COPY, BOT_NAMES, _moon_key, bot_lines, fill_bot_comments
|
||||
from services.feed_service import LINEUP
|
||||
|
||||
DAY = date(2001, 1, 2)
|
||||
|
||||
|
||||
def test_every_post_type_has_lines_from_known_characters():
|
||||
for t in {x[1] for x in LINEUP} | {PostType.CARD}:
|
||||
assert bot_lines(t, DAY, 1), t
|
||||
for sets in _COPY.values():
|
||||
for s in sets:
|
||||
assert 1 <= len(s) <= 2 and len({bot for bot, _ in s}) == len(s)
|
||||
assert all(bot in BOT_NAMES and 0 < len(body) <= 60 for bot, body in s)
|
||||
|
||||
|
||||
def test_lines_are_one_or_two_and_same_for_same_post():
|
||||
counts = {len(bot_lines(PostType.GAK, DAY, post_id)) for post_id in range(40)}
|
||||
assert counts == {1, 2}
|
||||
assert bot_lines(PostType.GAK, DAY, 7) == bot_lines(PostType.GAK, DAY, 7)
|
||||
|
||||
|
||||
def test_moon_lines_follow_full_and_new_moon_nights():
|
||||
assert _moon_key(date(2025, 10, 7)) == "MOON_FULL" # 보름 10.07 12:47
|
||||
assert _moon_key(date(2024, 4, 8)) == "MOON_NEW" # 삭 04.09 03:21, 그 전날 밤
|
||||
assert _moon_key(date(2025, 10, 4)) == "MOON"
|
||||
full = {body for s in _COPY["MOON_FULL"] for _, body in s}
|
||||
assert bot_lines(PostType.MOON, date(2025, 10, 7), 3)[0][1] in full
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def day_posts():
|
||||
async def wipe():
|
||||
await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: s.execute(text(f"DELETE FROM comment WHERE post_id IN (SELECT post_id FROM post WHERE feed_date = '{DAY}')")),
|
||||
lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date = '{DAY}'")),
|
||||
])
|
||||
await wipe()
|
||||
rows = [{"feed_date": DAY, "position": i, "scope": "00", "post_type": t.value, "ref_type": 1, "published_at": datetime(2001, 1, 2, 3, tzinfo=KST)}
|
||||
for i, t in enumerate([PostType.WEATHER, PostType.GAK, PostType.MOON, PostType.SUNSET], 1)]
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: FeedCRUD().insert_day(s, rows)])
|
||||
yield
|
||||
await wipe()
|
||||
|
||||
|
||||
async def _counts():
|
||||
sql = f"""SELECT p.post_id, p.comment_count, count(c.comment_id) FROM post p LEFT JOIN comment c ON c.post_id = p.post_id AND c.bot IS NOT NULL
|
||||
WHERE p.feed_date = '{DAY}' GROUP BY p.post_id, p.comment_count ORDER BY p.post_id"""
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(sql)))
|
||||
return [tuple(r) for r in rows.all()]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fill_adds_one_or_two_comments_once_and_counts_them(day_posts):
|
||||
await fill_bot_comments(DAY, FeedCRUD())
|
||||
first = await _counts()
|
||||
assert len(first) == 4 and all(1 <= n <= 2 and count == n for _, count, n in first)
|
||||
await fill_bot_comments(DAY, FeedCRUD())
|
||||
assert await _counts() == first
|
||||
|
||||
post_id = first[0][0]
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
|
||||
assert comments and all(x["official"] and x["nickname"] in BOT_NAMES.values() and not x["mine"] for x in comments)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_build_puts_character_comments_on_new_posts(offline):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": "1144000000"})).json()
|
||||
assert feed["hero_post"]["comment_count"] >= 1
|
||||
assert all(p["comment_count"] >= 1 for p in feed["posts"])
|
||||
@@ -142,3 +142,4 @@ async def test_instagram_requires_token(offline, admin_key, monkeypatch):
|
||||
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
|
||||
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"]
|
||||
|
||||
@@ -416,18 +416,3 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
|
||||
|
||||
def test_gak_rows_shows_heaviest_conditions_with_short_values():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import gak_rows
|
||||
|
||||
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
|
||||
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
|
||||
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
|
||||
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
|
||||
d.weight_wind = 0
|
||||
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
|
||||
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
|
||||
assert gak_rows(item)[1].value == "확률 70%"
|
||||