Compare commits
118
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab686165a8 | ||
|
|
463978c183 | ||
|
|
74a46dd66a | ||
|
|
3c34b958fa | ||
|
|
c788430fa7 | ||
|
|
77d29ce24f | ||
|
|
e5716c0c7c | ||
|
|
4e9b0bacba | ||
|
|
eb2151164f | ||
|
|
59f74e46ba | ||
|
|
12f4eca8a8 | ||
|
|
685d0ce9c1 | ||
|
|
d0213f41a6 | ||
|
|
61fefd200a | ||
|
|
017022a0b0 | ||
|
|
798286d975 | ||
|
|
a8a126f6a5 | ||
|
|
96cbd19c61 | ||
|
|
0a16c5329d | ||
|
|
aad8784b48 | ||
|
|
3c9b163dd4 | ||
|
|
b0cd5ef1ef | ||
|
|
0d6ab29552 | ||
|
|
ba94a381a9 | ||
|
|
882932a51b | ||
|
|
a68268234d | ||
|
|
2ca060b626 | ||
|
|
3975e41f56 | ||
|
|
646a45c88e | ||
|
|
e0d2ad2c9b | ||
|
|
422e354f61 | ||
|
|
0aeceac257 | ||
|
|
b586db0de7 | ||
|
|
599ef05dcf | ||
|
|
92cfeabe19 | ||
|
|
e270261e32 | ||
|
|
2b1b929f8f | ||
|
|
3712c7561a | ||
|
|
0b536e1f90 | ||
|
|
260ded8c79 | ||
|
|
012d8a4821 | ||
|
|
ee46a101db | ||
|
|
a21283651e | ||
|
|
e28a2e297e | ||
|
|
043210c049 | ||
|
|
29700f9d76 | ||
|
|
d95c69e3b7 | ||
|
|
fd4a00bcf7 | ||
|
|
18a7cffb39 | ||
|
|
8a7b269c04 | ||
|
|
114c87341e | ||
|
|
1990a1f998 | ||
|
|
c0e0363759 | ||
|
|
a74e3b49d0 | ||
|
|
35cd7695fa | ||
|
|
39f11d1327 | ||
|
|
2621db0450 | ||
|
|
a8871b9231 | ||
|
|
8f32999261 | ||
|
|
65909b40ad | ||
|
|
2720a23483 | ||
|
|
4daad2ecc5 | ||
|
|
d020d27715 | ||
|
|
c0ba463e54 | ||
|
|
92620c537b | ||
|
|
055eec69ef | ||
|
|
8a677a766d | ||
|
|
db233d8ffc | ||
|
|
5c05824ce0 | ||
|
|
43e1925d70 | ||
|
|
9a82cfbedc | ||
|
|
1324898a71 | ||
|
|
b91212b9e1 | ||
|
|
66a73a4756 | ||
|
|
767ccf029a | ||
|
|
72301e9f10 | ||
|
|
0b8eb84b55 | ||
|
|
0a4b210e6c | ||
|
|
934566d45c | ||
|
|
57cad25f32 | ||
|
|
b023d55901 | ||
|
|
aa774c2a44 | ||
|
|
4cdc8b274f | ||
|
|
6b8236d1cd | ||
|
|
aa05d870a2 | ||
|
|
cac6ea236f | ||
|
|
902fb4c070 | ||
|
|
0f614dd82f | ||
|
|
52b79c6de9 | ||
|
|
118a7b29ff | ||
|
|
81f84cee05 | ||
|
|
6e4babc610 | ||
|
|
b346838054 | ||
|
|
f5575711fe | ||
|
|
c30fac20a6 | ||
|
|
8422829f9d | ||
|
|
0a98fb8879 | ||
|
|
f4fe3e965c | ||
|
|
ef57a47e29 | ||
|
|
fcf199031a | ||
|
|
a4bb2e98c8 | ||
|
|
c94f7263d8 | ||
|
|
c0d53b8708 | ||
|
|
fb47f59d57 | ||
|
|
3a73a44cb0 | ||
|
|
97ebfe2d36 | ||
|
|
5c4f23c01a | ||
|
|
5a5f585bda | ||
|
|
d6525f592c | ||
|
|
ffc330d478 | ||
|
|
7b5d905298 | ||
|
|
91deb28ec3 | ||
|
|
76a640feab | ||
|
|
3857ef8d14 | ||
|
|
91a86a2c10 | ||
|
|
cd6769ccef | ||
|
|
3e376ae4b8 | ||
|
|
e059e294d0 |
No files matched your search
@@ -20,6 +20,8 @@ PORT=9810
|
||||
|
||||
# ── 백엔드: 로그인 토큰 서명 키. 비우면 로그인이 동작하지 않는다
|
||||
# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
# 구글 로그인 OAuth 클라이언트 ID (console.cloud.google.com/apis/credentials, 웹 애플리케이션)
|
||||
GOOGLE_CLIENT_ID=
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ venv/
|
||||
|
||||
# 생성물: python backend/scripts/export_openapi.py 로 다시 만든다
|
||||
backend/openapi.json
|
||||
backend/uploads/
|
||||
|
||||
# 도구 캐시·설정 (impeccable 디자인 도구)
|
||||
.impeccable/
|
||||
|
||||
@@ -15,6 +15,33 @@
|
||||
| [x] | 노을 판정 확인 방법·SEO 방식 — 추천안을 아래 [결정 필요] 행에 정리 | 출시 전 | |
|
||||
| [ ] | `release/launch-1008` → main 병합, 킹서버 배포, 시드 재적재·`feed:*` 캐시 삭제, 운영 JWT 비밀키 교체 (운영 영향, 확인 받고) | 출시 | `deploy.sh`, `backend/scripts/load_seed.py` |
|
||||
|
||||
## 월요일 논의 (받은 피드백)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | **[결정 필요]** 사용자 포스팅(인스타식) — 지금 포스트는 스케줄러가 만든 것만 있음. 정할 것: 올릴 수 있는 것(사진·글·각 점수 첨부), 로그인 필수 여부, 피드 노출 위치·순서, 신고·숨김, 사진 저장소 | 피드백. 기존 '커뮤니티' 행과 합쳐 논의 | `backend/services/feed_service.py`, `backend/services/reaction_service.py` |
|
||||
| [ ] | **[결정 필요]** 로그인 없이 좋아요·댓글 — 지금은 좋아요·댓글·댓글 좋아요 모두 로그인 필수, 댓글 보기만 비로그인 가능. 정할 것: 중복 좋아요 막는 기준(기기 ID·IP), 비로그인 댓글 이름 표시(익명 n), 지우기 권한, 도배 방지 | 피드백 | `backend/router/v1/reaction/reaction.py:30`, `:71`, `:87` |
|
||||
| [ ] | **[결정 필요]** 로그인하면 더 되는 것 정의 — 지금 로그인 전용은 저장(북마크)·닉네임·내 정보뿐. 위 두 건이 정해지면 후보: 포스팅, 내 글·댓글 모아 보기, 지역 기억(기기 바뀌어도), 알림 | 피드백 | `backend/router/v1/auth/account.py`, `backend/router/v1/reaction/reaction.py:40` |
|
||||
|
||||
## 10/20 회의 (최미나 담당, `docs/meetings/2026-10-20.md`)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [x] | 오늘의 각을 일반 포스트 크기 카드로 + 공유 (금일 핵심) — 순위 5개 카드, 히어로도 포스트 틀, 보내기만 있음(좋아요·댓글은 서버에 포스트로 저장해야 붙음), TOP 5 띠 뺌 | 10/20 회의 결정 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | '+' 버튼 포스팅 → 오늘 피드에 섞기. 이야기 탭 없앰, 피드 위 글쓰기 칸 상시, 사람 글은 운영 포스트 3개마다 1개(방금 쓴 글은 글쓰기 칸 아래). 남은 것: 이미지 올리기, 노출 방식 대표 보고(보고서 https://claude.ai/artifact/A7ELGoAy17cnZXzhuvdF5b 추천은 캐러셀) | 10/20 회의 결정 | `frontend/src/b/talk.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 피드 순서: 히어로 → 오늘의 각 → 포스트. 주말 날씨·행사·노을 앞으로, 각·공기·자외선·상식 뒤로 | 10/20 회의 | `backend/services/feed_service.py` |
|
||||
| [ ] | 시간대 지정 각(야장·별보기)을 시간 밖에도 뒤쪽에 노출, 억새각 노출 조건 확인 | 10/20 회의 (담당 김성경 확인 필요) | `backend/services/index_service.py`, `backend/seed/index_definition.json` |
|
||||
| [ ] | 단풍 지도·단풍 포스트, 새 각 — 야구각 문장(숫자 뺌)만 반영. 농구·배구·제철 수산물각 초안은 보류(scratchpad `new_gak_draft.json`) | 10/20 회의 | `backend/seed/index_definition.json`, `backend/seed/article.json` |
|
||||
| [x] | 불쾌지수 항상 표시 | 10/20 회의 결정 (10/8도 결정) | `backend/services/hero_stats.py:70` |
|
||||
| [x] | 나만의 각을 '이름+조건(기온·비·바람·미세먼지·습도·시간대 수치) 저장'으로 바꿈 — 섞기 방식 대체, 점수는 서버가 그 동네 예보로 계산(조건에서 멀수록 깎기), 받은 링크에 조건을 담아 친구 동네 점수로. 피드에 올려 좋아요는 아직 | 10/20 회의 결정 (조합 방식 대체) | `frontend/src/b/myGak.tsx` |
|
||||
| [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` |
|
||||
| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` |
|
||||
| [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` |
|
||||
| [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침). 타로는 운세 주제별 귀여운 각 이름으로 — 예: 애정 날씨 타로 → '다툼구름각' (사용자 10/21) | 10/20 회의 | |
|
||||
| [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` |
|
||||
| [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` |
|
||||
| [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` |
|
||||
|
||||
## 진행 순서
|
||||
|
||||
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
|
||||
@@ -94,7 +121,13 @@
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 각 목록 '지금 아님' 문구 — 계절이 아니라 각 시간대(등산 7~12시·피크닉 11~16시)가 지났다는 뜻인데 '가을' 표시 옆에 있어 비활성처럼 읽힘. 그 각의 시간('오전에 좋아요' 등)으로 바꿀지 | 사용자 지적 | `frontend/src/b/GakPage.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 → 10/12 `months` 칸 + 새 각 12개, 계절 표시는 서버 `season` | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 운영 DB에 `index_definition.months` 칸 추가 — `deploy.sh` 가 배포 때 `init.sql`(`ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';`)과 `load_seed.py` 를 돌려서 자동으로 들어감. 배포 뒤 각 탭에 계절 표시가 나오는지만 확인 | 계절 각 | `backend/postgres-init/init.sql`, `deploy.sh` |
|
||||
| [ ] | **[검토 필요]** 새 각 12개 문구 — 설명·한 줄 문장(0/30/60/80)·한계 문구, '제철 아님' 표시 문구 | 계절 각 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 새 각 전용 아이콘 — 꽃구경(화분)·이불빨래/실내건조(빨래)·빙수(아이스커피)·한강밤바람(야장)·억새(볏단)·해돋이(노을)·붕어빵/군고구마(고구마)는 있는 그림 재사용 중 | 계절 각 | `frontend/public/icons/` |
|
||||
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
||||
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
||||
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||
@@ -112,7 +145,12 @@
|
||||
| [x] | 문화정보원 API 가 `23 LIMITED_NUMBER_OF_SERVICE_REQUESTS_PER_SECOND_EXCEEDS_ERROR` 를 냄 — 쪽 사이 1초, 시도 사이 1초 간격을 둬 17개 시도 수집에서 오류 없음 | 콘서트 수집 점검 중 발견 | `backend/services/external/culture_api.py` |
|
||||
| [x] | `event.kind` 칸 추가(1=축제 2=전시 3=콘서트 4=팝업). 행사 종류(축제·전시·콘서트·팝업)를 구분하는 칸이 없음 — 지금은 `source_id` 접두어로만 구분하고 전시·콘서트는 둘 다 `kcis:` 라 섞임 | 콘서트 수집 | `backend/postgres-init/init.sql` (`event`) |
|
||||
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [ ] | **[결정 필요]** 검색 노출(SEO·AEO) 대응 빌드 방식 정하기 — 지금은 브라우저에서만 그리는 React(Vite)라 검색엔진·AI가 내용을 못 읽음. 추천안: SPA는 그대로 두고 FastAPI가 지역 랜딩 256쪽(`/r/{지역}`)만 서버에서 그림(오늘 날씨·노을 상황·각 상위를 글로, 10분 캐시) + 지역별 title·description·OG·canonical, JSON-LD(WebPage·Place·BreadcrumbList·FAQPage), `/sitemap.xml`·`/robots.txt`도 백엔드가 냄. nginx는 `/r/`·`/sitemap.xml`·`/robots.txt`를 backend로, SPA는 URL로 지역을 받게. 패키지 `jinja2` 1개, 3~4일. 결정할 것: URL 형태(코드/한글), 랜딩에 보일 항목, `jinja2` 추가 | 지시 사항 (SEO·AEO 필요). 정적 사전 렌더링은 빌드 때 값이 굳어 시간마다 바뀌는 날씨가 틀리고, 봇에게만 다른 HTML은 구글이 권하지 않는 임시방편에 헤드리스 브라우저가 필요, 전체 SSR(React Router 프레임워크 모드)은 Node 서버 추가·전면 이전이라 과함. 지금은 지역이 `localStorage`에만 있어 지역별 URL 자체가 없음 | `frontend/nginx.conf`, `frontend/index.html`, `frontend/src/b/region.tsx`, `frontend/src/App.tsx`, `backend/router/` (새 라우터), `backend/requirements.txt` |
|
||||
| [x] | 검색 노출 1단계: 메타는 `index.html` 하나로 유지 + canonical, `robots.txt`·`sitemap.xml`(메인 한 줄) 추가 — 탭별 HTML로 나누는 안은 효과(탭별 공유 미리보기·탭별 색인)가 작아 보류. 도메인 `weather.o2o.kr` 고정이라 바뀌면 두 파일도 수정 | 10/8 논의 | `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` |
|
||||
| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) |
|
||||
| [ ] | 구로 나뉜 13개 시의 구마다 자기 주소(`/today/gyeonggi/seongnam/bundang`, 39장) — 운영 반영(`96cbd19`, 10/20). 남은 것: 서치 콘솔·서치어드바이저에 sitemap 다시 제출 | 구글 '분당구 오늘 날씨' 상위는 모두 구 단위 페이지, 우리는 성남시 한 장에 묶여 분당구 주소가 없었음 | `backend/scripts/gen_region_pages.py`, `frontend/vite.config.ts`, `frontend/nginx.conf`, `backend/router/v1/seo/seo.py` |
|
||||
| [ ] | **[보류]** 날씨별 옷차림 콘텐츠 — 후보: ① `/outfit` 기온별 옷차림 고정 페이지 ② 지역 페이지·오늘 탭에 '오늘 옷차림' 한 줄. 형태 미정 | 구글 트렌드 '옷차림'≈'노을'(세차의 0.8배), 네이버 자동완성 '기온별 옷차림'·'20도 옷차림'·'서울 오늘 날씨 옷차림'. 지금은 주말 탭·히어로의 '겉옷' 팁뿐 | `docs/검색어_인기_리서치.md`, `backend/services/weekend_plan.py` |
|
||||
| [ ] | 서치 콘솔: 홈 URL 검사(구조화 데이터 '날씨각' 인식 확인)·재크롤링 요청, 색인 생성 보고서에서 지역 페이지 몇 장 색인됐는지 확인 / 네이버 서치어드바이저: 주요 지역 페이지 수집 요청(네이버 색인 10/235) | 사이트 이름 '에이아이오투오' 표시, 지역 페이지 색인 부족 | `docs/구글_검색_정책_리서치.md` |
|
||||
| [x] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 (둘 다 등록됨, 10/13 확인) | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
|
||||
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
|
||||
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
|
||||
| [ ] | **[결정 필요]** 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 추천안: 서쪽이 트인 공개 웹캠·CCTV 6~8곳을 워커가 매일 '가장 붉을 때' 시각에 캡처하고, 같은 날 13시 기준 예보(상황·판정)를 따로 남김. 사람이 주 1회 사진에 잿빛/은은/고움/붉음 라벨(30분 내외) → 판정(나가 볼 만해요/애매/쉬어요) 3×3 적중표, 특히 '나가 볼 만해요' 적중률(목표 70%↑). 6~8주(약 300장)면 기준값 조정 가능. 비용 0원, 테이블 1개+워커 잡 1개+라벨 CSV로 2~3일. 결정할 것: 웹캠 출처·이용 조건, 라벨 담당 | 노을 탭 다시 기획 (10/7). 사용자 '예뻤어요/별로'는 출시 전엔 표본이 없고 출시 후 보조 지표로, 기상청 ASOS 운량은 전운량·중하층운량만이라 구름 입력 검증용이지 노을이 예뻤는지는 못 알려줌, 인스타 해시태그는 예쁜 날만 올라와 '쉬어요' 검증 불가·수집 약관 문제. `sky_score`는 갱신 때 덮어쓰고 7일 뒤 지워져 지금은 과거 예보가 안 남음 | `backend/services/calc/sky_score.py` (`situation`), `backend/services/sky_service.py`, `backend/scheduler/jobs.py` |
|
||||
@@ -134,8 +172,24 @@
|
||||
| [ ] | 각 문서: 강풍 특보 조건이 "wind 특보가 있으면"으로 찍힘 (등산·골프·낚시각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [ ] | 각 문서: "한눈에 보기" 표에 자외선·햇빛·가시거리 비중이 빠져 합이 100%가 안 됨 (등산·드라이브·물놀이각) | 각 늘리기 중 발견 (10/8) | `backend/scripts/gen_gak_doc.py` |
|
||||
| [x] | 각 중요도: 새 각 7개 제안 — 드라이브 상 / 골프·낚시·물놀이 중 / 집콕·연날리기·김장 하 | 각 늘리기 (10/8) | `backend/seed/index_definition.json` |
|
||||
| [ ] | `tests/test_sky_api.py` 2개가 09시 직전(08:58 KST)에 실패 — 시간대 경계 의존, 재실행 시 통과 | 계절 사진 작업 중 발견 (10/8) | `backend/tests/test_sky_api.py` |
|
||||
| [ ] | `tests/test_sky_api.py` 2개가 09시 직전(08:45~08:58 KST)에 실패 — 시간대 경계 의존, 재실행 시 통과 | 계절 사진 작업 중 발견 (10/8) | `backend/tests/test_sky_api.py` |
|
||||
| [ ] | 개인정보처리방침·이용약관 모달 (출시 후로 미룸) — `feat/legal` 브랜치(f6ddc67)에 구현 완료, 병합 전. 남은 것: `OPERATOR` 자리표시(회사명·대표자·사업자번호·주소·문의 이메일·보호책임자·호스팅 업체·로그 보유 기간), 탈퇴 기능 없음, 위치 좌표가 nginx 접속 로그에 남음, 만 14세 미만 확인 없음, 약관 열면 가입 입력값 사라짐, 위치정보법 신고 대상 법무 확인 | 사용자 결정 (10/8) | `frontend/src/b/legal/`, `frontend/src/b/Sheets.tsx` |
|
||||
| [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) |
|
||||
| [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` |
|
||||
| [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` |
|
||||
| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 3) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||
| [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||
| [x] | 히어로에 습도·불쾌지수 항상 표시 → 4칸(지금·습도·불쾌지수·상황 1칸, 사용자 결정). 불쾌지수 75 이상이면 경고 색, 상황 칸 후보에서 불쾌지수 뺌 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [x] | 달: '밝기 %' 표시 뺌 → 모양 + 잘 보이는지(구름·뜨고 지는 시각). 모양은 실제 해·달 황경 차이로(예전 계산은 보름을 반나절 일찍 판정). 별보기각은 빛나는 면 × 떠 있는 비율 (사용자 결정) | 10/8 회의 | `backend/services/calc/moon.py` |
|
||||
| [x] | 노을: 점수 강조(히어로에 점수 크게) → 사용자가 '29점이 키포인트 정보냐'고 해 히어로는 다시 시각 크게, 점수는 결론 카드 아래 줄로(10/12). 골든아워·블루아워 설명. 결론은 다음에 오는 것(해 뜨기 전·밤엔 일출, 그 사이엔 노을)으로, 피드 노을 카드도 같이 (사용자 결정 '각·노을도 지금 기준') | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` |
|
||||
| [x] | 주말 예보 UI 개선 → 피드 주말 예보 카드: 토·일 칸을 제목 바로 아래로(칸이 바닥에 붙어 가운데가 비어 오류처럼 보였음), 칸마다 '이날 할 만한 각' 3개 (사용자 의견) | 10/8 회의 | `frontend/src/b/WeekPage.tsx` |
|
||||
| [ ] | AEO·SEO 메타데이터 + 구글·네이버 검색 등록 (금일 핵심 업무), 넣은 태그·키워드 정의서 작성, 매시간 갱신 콘텐츠 노출 방식 정리 → 대표 보고. 도메인은 별도 유지 | 10/8 회의 결정 | `frontend/index.html`, `docs/` |
|
||||
| [ ] | `docs/콘텐츠_구현기획.md` 2-1의 오늘 날씨 점수 식이 예전 기준(기온 40·비 30·바람 15·미세먼지 15) — 새 기준은 `docs/점수_계산식.md` | 점수 계산식 정리 중 발견 (10/8) | `docs/콘텐츠_구현기획.md` |
|
||||
| [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` |
|
||||
| [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) |
|
||||
| [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) |
|
||||
| [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` |
|
||||
| [ ] | **[결정 필요]** 기존 각과 겹침 — 센치↔감성노래, 게임↔넷플릭스·집콕, 곱슬머리↔화장붕괴, 효도↔트로트, 셀카↔사진산책. 둘 다 둘지 합칠지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json` |
|
||||
| [ ] | 감사각은 '어제보다 날씨가 크게 바뀐 날'을 못 봄 — 지금은 덥거나 춥거나 비 오면 높음. 전날 대비 기온 변화 요소를 계산에 넣을지 | 새 각 추가 중 발견 (10/20) | `backend/services/calc/index_calc.py` |
|
||||
| [ ] | 테스트 2개가 날짜·시각에 따라 깨짐 — `test_feed` 스토리 수 40 고정(10월엔 계절 각이 늘어 다름, 각 추가 전 42·후 57), `test_weather_today` 7번째 칸이 시각에 따라 노을/달 | 새 각 추가 중 테스트에서 발견 (10/20) | `backend/tests/test_feed.py:64`, `backend/tests/test_weather_today.py` |
|
||||
@@ -142,6 +142,7 @@ class SkyScore(Base):
|
||||
situation: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
models_total: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
models_agree: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
air: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)
|
||||
|
||||
|
||||
class SunsetSpot(Base):
|
||||
@@ -184,6 +185,7 @@ class IndexDefinition(Base):
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
months: Mapped[list] = mapped_column(JSONB, default=list, server_default="[]") # 제철 달. 비면 일 년 내내
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
@@ -206,6 +208,7 @@ class IndexScore(Base):
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
slots: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -333,6 +336,14 @@ class PostLike(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PostLikeAnon(Base):
|
||||
__tablename__ = "post_like_anon"
|
||||
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class PostSave(Base):
|
||||
__tablename__ = "post_save"
|
||||
|
||||
@@ -359,3 +370,70 @@ class CommentLike(Base):
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class CommentLikeAnon(Base):
|
||||
__tablename__ = "comment_like_anon"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class MyGak(Base):
|
||||
__tablename__ = "my_gak"
|
||||
|
||||
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))
|
||||
rule: Mapped[dict] = mapped_column(JSONB)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class Talk(Base):
|
||||
__tablename__ = "talk"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
region_code: Mapped[str] = mapped_column(String(10))
|
||||
body: Mapped[str] = mapped_column(String(100))
|
||||
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
|
||||
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class TalkLike(Base):
|
||||
__tablename__ = "talk_like"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class TalkLikeAnon(Base):
|
||||
__tablename__ = "talk_like_anon"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class TalkReport(Base):
|
||||
__tablename__ = "talk_report"
|
||||
|
||||
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class UserBlock(Base):
|
||||
__tablename__ = "user_block"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -19,6 +19,8 @@ class ErrorType(Enum):
|
||||
EXTERNAL_API_ERROR = 2001
|
||||
NOT_FOUND = 3001
|
||||
INVALID_INPUT = 3002
|
||||
DAILY_LIMIT = 3003 # 하루에 쓸 수 있는 수를 넘음
|
||||
LINK_NOT_ALLOWED = 3004 # 글에 링크·전화번호
|
||||
AUTH_REQUIRED = 4001
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
@@ -113,6 +115,13 @@ class IndexCategory(CodeEnum):
|
||||
LIFE = 4
|
||||
|
||||
|
||||
class TalkReport(CodeEnum):
|
||||
ABUSE = 1 # 욕설·비하
|
||||
SPAM = 2 # 광고·도배
|
||||
PRIVACY = 3 # 개인정보 노출
|
||||
ETC = 4
|
||||
|
||||
|
||||
class ArticleCategory(CodeEnum):
|
||||
SEASON = 1
|
||||
TIP = 2
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs"
|
||||
ISSUERS = ("accounts.google.com", "https://accounts.google.com")
|
||||
_CERTS_TTL = 3600
|
||||
_certs: dict = {"keys": [], "at": 0.0}
|
||||
|
||||
|
||||
async def _keys(force: bool = False) -> list[dict]:
|
||||
"""구글 서명 공개키. 한 시간 캐시하고, 모르는 키가 오면 한 번 다시 받는다."""
|
||||
if force or not _certs["keys"] or time.monotonic() - _certs["at"] > _CERTS_TTL:
|
||||
async with httpx.AsyncClient(timeout=5) as c:
|
||||
res = await c.get(CERTS_URL)
|
||||
res.raise_for_status()
|
||||
_certs["keys"], _certs["at"] = res.json()["keys"], time.monotonic()
|
||||
return _certs["keys"]
|
||||
|
||||
|
||||
async def verify(credential: str) -> Optional[str]:
|
||||
"""구글 로그인 버튼이 준 ID 토큰을 확인하고 구글 사용자 고유 번호(sub)를 돌려준다. 서명·발급처·우리 클라이언트 ID·만료가 하나라도 안 맞으면 None."""
|
||||
if not settings.google_client_id:
|
||||
LOG.error("[google] GOOGLE_CLIENT_ID is empty")
|
||||
return None
|
||||
try:
|
||||
kid = jwt.get_unverified_header(credential).get("kid")
|
||||
keys = await _keys()
|
||||
key = next((k for k in keys if k.get("kid") == kid), None) or next((k for k in await _keys(force=True) if k.get("kid") == kid), None)
|
||||
if key is None:
|
||||
return None
|
||||
claims = jwt.decode(credential, key, algorithms=["RS256"], audience=settings.google_client_id, options={"verify_at_hash": False})
|
||||
except (JWTError, httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.warning("[google] id token rejected: %s", type(e).__name__)
|
||||
return None
|
||||
if claims.get("iss") not in ISSUERS or not claims.get("sub"):
|
||||
return None
|
||||
return str(claims["sub"])
|
||||
@@ -0,0 +1,38 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
from common.auth import optional_user
|
||||
from common.database.model.models import User
|
||||
from config.settings import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Liker:
|
||||
"""좋아요를 누른 사람. 로그인했으면 user_id, 아니면 IP 해시로 한 번만 센다."""
|
||||
user_id: Optional[uuid.UUID]
|
||||
ip_hash: str
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str:
|
||||
"""nginx 가 X-Forwarded-For 맨 끝에 붙인 접속 주소만 믿는다. 앞쪽은 클라이언트가 마음대로 넣을 수 있다."""
|
||||
xff = request.headers.get("x-forwarded-for", "")
|
||||
last = xff.rsplit(",", 1)[-1].strip()
|
||||
if last:
|
||||
return last
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def ip_hash(ip: str) -> str:
|
||||
"""IP 원문은 저장하지 않는다. 서버 비밀값으로 HMAC 한 값만 남긴다."""
|
||||
if not settings.jwt_refresh_secret:
|
||||
raise RuntimeError("JWT_REFRESH_SECRET is empty")
|
||||
return hmac.new(settings.jwt_refresh_secret.encode(), f"like-ip:{ip}".encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
async def liker(request: Request, user: Optional[User] = Depends(optional_user)) -> Liker:
|
||||
return Liker(user_id=user.user_id if user else None, ip_hash=ip_hash(client_ip(request)))
|
||||
@@ -1,3 +1,6 @@
|
||||
import html
|
||||
|
||||
|
||||
def hour_label(h: int) -> str:
|
||||
if h == 0:
|
||||
return "자정"
|
||||
@@ -35,3 +38,10 @@ _COMPASS = ("북", "북북동", "북동", "동북동", "동", "동남동", "남
|
||||
def compass(deg: float) -> str:
|
||||
"""방위각 → 16방위 이름. 263 → "서" """
|
||||
return _COMPASS[round(deg / 22.5) % 16]
|
||||
|
||||
|
||||
def plain(s: str) -> str:
|
||||
"""HTML 문자 참조를 다 푼다. 두 번 인코딩돼 오는 출처도 있어("<") 더 안 바뀔 때까지."""
|
||||
while (u := html.unescape(s)) != s:
|
||||
s = u
|
||||
return s
|
||||
@@ -31,6 +31,15 @@ class Settings(BaseSettings):
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||
frontend_internal_url: str = "http://frontend"
|
||||
|
||||
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
|
||||
upload_dir: str = "uploads"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -34,6 +34,13 @@ class IndexCRUD:
|
||||
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||
return await s.scalar(stmt)
|
||||
|
||||
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
||||
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
||||
stmt = select(IndexScore.index_id).where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
||||
).limit(1)
|
||||
return (await s.scalar(stmt)) is not None
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import MyGak
|
||||
|
||||
|
||||
class MyGakCRUD:
|
||||
async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]:
|
||||
return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all())
|
||||
|
||||
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)
|
||||
s.add(row)
|
||||
await s.flush()
|
||||
return row
|
||||
|
||||
async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool:
|
||||
res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id))
|
||||
return res.first() is not None
|
||||
@@ -5,17 +5,25 @@ from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
|
||||
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
|
||||
from common.liker import Liker
|
||||
|
||||
|
||||
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
|
||||
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
||||
model, keys = (member, {id_name: id_value, "user_id": who.user_id}) if who.user_id is not None else (anon, {id_name: id_value, "ip_hash": who.ip_hash})
|
||||
id_col = getattr(model, id_name)
|
||||
if on:
|
||||
res = await s.execute(insert(model).values(**keys).on_conflict_do_nothing().returning(id_col))
|
||||
else:
|
||||
res = await s.execute(delete(model).where(*(getattr(model, k) == v for k, v in keys.items())).returning(id_col))
|
||||
return res.first() is not None
|
||||
|
||||
|
||||
class ReactionCRUD:
|
||||
async def toggle_post_like(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> int:
|
||||
async def toggle_post_like(self, s: AsyncSession, post_id: int, who: Liker, on: bool) -> int:
|
||||
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
|
||||
if on:
|
||||
res = await s.execute(insert(PostLike).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing().returning(PostLike.post_id))
|
||||
else:
|
||||
res = await s.execute(delete(PostLike).where(PostLike.post_id == post_id, PostLike.user_id == user_id).returning(PostLike.post_id))
|
||||
if res.first() is not None:
|
||||
if await toggle_like_row(s, who, PostLike, PostLikeAnon, "post_id", post_id, on):
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(like_count=Post.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Post.like_count).where(Post.post_id == post_id))
|
||||
|
||||
@@ -34,6 +42,9 @@ class ReactionCRUD:
|
||||
saved = set((await s.scalars(select(PostSave.post_id).where(PostSave.user_id == user_id, PostSave.post_id.in_(post_ids)))).all())
|
||||
return liked, saved
|
||||
|
||||
async def anon_liked_posts(self, s: AsyncSession, ip_hash: str, post_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(PostLikeAnon.post_id).where(PostLikeAnon.ip_hash == ip_hash, PostLikeAnon.post_id.in_(post_ids)))).all())
|
||||
|
||||
async def saved_posts(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Post, PostSave]]:
|
||||
stmt = select(Post, PostSave).join(PostSave, PostSave.post_id == Post.post_id).where(PostSave.user_id == user_id, Post.deleted.is_(False))
|
||||
if cursor is not None:
|
||||
@@ -50,6 +61,10 @@ class ReactionCRUD:
|
||||
stmt = select(CommentLike.comment_id).where(CommentLike.user_id == user_id, CommentLike.comment_id.in_(comment_ids))
|
||||
return set((await s.scalars(stmt)).all())
|
||||
|
||||
async def anon_liked_comments(self, s: AsyncSession, ip_hash: str, comment_ids: list[int]) -> set[int]:
|
||||
stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids))
|
||||
return set((await s.scalars(stmt)).all())
|
||||
|
||||
async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment:
|
||||
c = Comment(post_id=post_id, user_id=user_id, body=body)
|
||||
s.add(c)
|
||||
@@ -68,14 +83,10 @@ class ReactionCRUD:
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
return True
|
||||
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]:
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
|
||||
if exists is None:
|
||||
return None
|
||||
if on:
|
||||
res = await s.execute(insert(CommentLike).values(comment_id=comment_id, user_id=user_id).on_conflict_do_nothing().returning(CommentLike.comment_id))
|
||||
else:
|
||||
res = await s.execute(delete(CommentLike).where(CommentLike.comment_id == comment_id, CommentLike.user_id == user_id).returning(CommentLike.comment_id))
|
||||
if res.first() is not None:
|
||||
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
||||
@@ -58,5 +58,9 @@ class SkyCRUD:
|
||||
)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def west_open_spots(self, s: AsyncSession) -> list[SunsetSpot]:
|
||||
"""서쪽이 트인 노을 명소 (sort_order 0)."""
|
||||
return list((await s.scalars(select(SunsetSpot).where(SunsetSpot.sort_order == 0))).all())
|
||||
|
||||
async def ranking_regions(self, s: AsyncSession) -> list[Region]:
|
||||
return list((await s.scalars(select(Region).where(Region.is_ranking_spot.is_(True)))).all())
|
||||
@@ -0,0 +1,66 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Region, Talk, TalkLike, TalkLikeAnon, TalkReport, User, UserBlock
|
||||
from common.liker import Liker
|
||||
from crud.reaction_crud import toggle_like_row
|
||||
|
||||
|
||||
class TalkCRUD:
|
||||
async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]:
|
||||
"""최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다."""
|
||||
stmt = (
|
||||
select(Talk, User, Region.short_name)
|
||||
.join(User, User.user_id == Talk.user_id)
|
||||
.outerjoin(Region, Region.code == Talk.region_code)
|
||||
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Talk.talk_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
|
||||
|
||||
async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all())
|
||||
|
||||
async def anon_liked(self, s: AsyncSession, ip_hash: str, talk_ids: list[int]) -> set[int]:
|
||||
return set((await s.scalars(select(TalkLikeAnon.talk_id).where(TalkLikeAnon.ip_hash == ip_hash, TalkLikeAnon.talk_id.in_(talk_ids)))).all())
|
||||
|
||||
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
|
||||
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
|
||||
|
||||
async def add(self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None) -> Talk:
|
||||
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image)
|
||||
s.add(t)
|
||||
await s.flush()
|
||||
await s.refresh(t)
|
||||
return t
|
||||
|
||||
async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]:
|
||||
return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False)))
|
||||
|
||||
async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id))
|
||||
return res.first() is not None
|
||||
|
||||
async def toggle_like(self, s: AsyncSession, talk_id: int, who: Liker, on: bool) -> int:
|
||||
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
|
||||
if await toggle_like_row(s, who, TalkLike, TalkLikeAnon, "talk_id", talk_id, on):
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id))
|
||||
|
||||
async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None:
|
||||
"""한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다."""
|
||||
res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id))
|
||||
if res.first() is None:
|
||||
return
|
||||
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at))
|
||||
|
||||
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||
@@ -22,6 +22,12 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
|
||||
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
|
||||
s.add(user)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]:
|
||||
user = await self.get(s, user_id)
|
||||
if user is None:
|
||||
|
||||
@@ -5,6 +5,7 @@ from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Event, Holiday, Place, WeatherDaily
|
||||
from common.utils.text import plain
|
||||
|
||||
|
||||
class WeekCRUD:
|
||||
@@ -46,6 +47,8 @@ class WeekCRUD:
|
||||
async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
# 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다
|
||||
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows]
|
||||
stmt = insert(Event).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["source_id"],
|
||||
|
||||
@@ -40,18 +40,19 @@ Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장
|
||||
|
||||
```
|
||||
canvas = max(mid20, high20)
|
||||
f_canvas = 0.2 + 0.8 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50)
|
||||
f_canvas = 0.4 + 0.6 × canvas/50 (canvas ≤ 50) / max(0, 1 - (canvas-50)/50) (canvas > 50)
|
||||
f_near = 1 - 0.8 × low20 / 100
|
||||
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
구름 점수 = 100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light)
|
||||
점수 = min(100, round(모델 평균 구름 점수 × 공기 보정))
|
||||
```
|
||||
|
||||
- 맑은 하늘(구름 0%)은 40점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
||||
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0):
|
||||
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 40km 이상 ×1.0 ~ 5km 이하 ×0.6. 뿌연 공기는 색을 흐린다.
|
||||
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 50% 이하 ×1.0 ~ 90% 이상 ×0.75.
|
||||
- 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다.
|
||||
- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0). 평소 공기(가시거리 20km·습도 60%)를 ×1.0 으로 두고 좋으면 올리고 나쁘면 내린다. 맑은 날 전국이 한 점수(구름 0% = 55점)에 몰리지 않게 하려는 것:
|
||||
- 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 5km 이하 ×0.8 · 20km ×1.0 · 40km 이상 ×1.12, 사이는 직선. 뿌연 공기는 색을 흐리고 맑은 공기는 더 선명하다.
|
||||
- 습도(`weather_hourly.humidity`, 가장 가까운 정시): 40% 이하 ×1.06 · 60% ×1.0 · 90% 이상 ×0.85, 사이는 직선.
|
||||
- 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15.
|
||||
- 서쪽이 트인 곳 (노을만): 구 중심 20km 안에 서쪽이 트인 노을 명소(`sunset_spot.sort_order` 0 = `sunset_spot.csv`의 `west_open` 1)가 있으면 ×1.1. 산·건물에 가리지 않고 해가 지평선까지 보이는 곳이라서. 명소에는 바다뿐 아니라 강변·높은 전망대도 있어 서울 마포·강남, 대구 수성 같은 내륙 구도 받는다. 일출은 동쪽이 트였는지 데이터가 없어 넣지 않는다.
|
||||
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다.
|
||||
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
||||
|
||||
@@ -140,17 +141,19 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
||||
|---|---|---|---|
|
||||
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
||||
| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 피크닉각 | 자외선 10 | 25·25·15·5·10 | |
|
||||
| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | |
|
||||
| 러닝각 | 자외선 5 | 35·20·10·15·10 | |
|
||||
| 가드닝각 | 자외선 5 | 25·30·10·15·10 | |
|
||||
| 피크닉각 | 자외선 10, 햇빛 10 | 20·20·15·5·10 | |
|
||||
| 등산각 | 자외선 10, 햇빛 10, 가시거리 5 | 20·20·15·5·10 | |
|
||||
| 자전거각 | 자외선 10, 햇빛 10 | 20·20·20·5·10 | 돌풍 15m/s 이상 |
|
||||
| 가드닝각 | 자외선 10, 햇빛 10 | 20·25·10·10·10 | |
|
||||
| 세차각 | 자외선 10, 햇빛 10 | 5·40·10·10·10 | |
|
||||
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
||||
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
||||
| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
| 멍뭉산책각 | | 40·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 러닝각 | | 35·20·10·15·15 | |
|
||||
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
|
||||
- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인).
|
||||
- 해가 떠 있는 시간대의 야외 활동(피크닉·등산·자전거·가드닝·세차)은 햇빛과 자외선을 **같은 비중(10씩)으로 함께** 둔다. 햇빛은 많을수록, 자외선은 낮을수록 점수가 높다. 자외선만 있으면 흐린 날이 "자외선 낮음 = 좋음"으로 맑은 날보다 높게 나오고, 햇빛만 있으면 한여름 강한 자외선을 놓친다.
|
||||
- 러닝각(6~8·19~22시)·멍뭉산책각(7~9·17~20시)은 자외선을 뺐다. 이른 아침·저녁이라 자외선이 늘 0이라 점수를 가르지 못했다. 그 비중은 러닝은 공기, 멍뭉산책은 기온으로 옮겼다. 사진산책각(일몰 무렵)도 같은 이유로 햇빛·자외선을 두지 않는다.
|
||||
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
||||
|
||||
### 3시간 구간을 계산 창에 연결하는 규칙
|
||||
|
||||
@@ -133,6 +133,7 @@ CREATE TABLE IF NOT EXISTS public.sky_score (
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS situation SMALLINT NULL; -- SkySituation: 1=가려짐 2=낮은 구름 3=물들 구름 적음 4=넓게 물듦 5=두꺼움
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_total SMALLINT NULL; -- 계산에 쓴 예보 모델 수
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_agree SMALLINT NULL; -- 그중 같은 하늘 상황을 낸 모델 수
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS air JSONB NULL; -- 해 질(뜰) 무렵 공기 보정 {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}. 결론·이유에 쓴다
|
||||
|
||||
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
@@ -153,12 +154,14 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
slots JSONB NOT NULL DEFAULT '{}', -- 오늘만: 구간별 점수 {"morning"|"day"|"evening"|"night"|"early": {score, summary, factors, zero_reason, notes}}. 각 시간대와 안 겹치는 구간은 없음
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -208,6 +211,14 @@ CREATE TABLE IF NOT EXISTS public.post_like (
|
||||
PRIMARY KEY (post_id, user_id)
|
||||
);
|
||||
|
||||
-- 로그인 없이 누른 좋아요. IP 원문 대신 HMAC-SHA256 해시로 한 IP 에 한 번만 센다. like_count 는 post_like 와 이 표를 합한 수
|
||||
CREATE TABLE IF NOT EXISTS public.post_like_anon (
|
||||
post_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (post_id, ip_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_save (
|
||||
post_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
@@ -245,6 +256,70 @@ CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like_anon (
|
||||
comment_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, ip_hash)
|
||||
);
|
||||
|
||||
-- 나만의 각: 사용자가 이름과 날씨 조건(수치)을 정해 저장. 점수는 저장하지 않고 볼 때 그 동네 예보로 계산한다
|
||||
CREATE TABLE IF NOT EXISTS public.my_gak (
|
||||
my_gak_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
name VARCHAR(12) NOT NULL, -- 사용자가 지은 이름 (소맥각)
|
||||
rule JSONB NOT NULL, -- 조건: temp [lo,hi]·rain·wind_max·air·humidity [lo,hi]·slots
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
|
||||
|
||||
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
|
||||
CREATE TABLE IF NOT EXISTS public.talk (
|
||||
talk_id BIGSERIAL PRIMARY KEY,
|
||||
user_id UUID NOT NULL,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
body VARCHAR(100) NOT NULL,
|
||||
weather VARCHAR(30), -- 쓸 때 날씨 한 줄 (예: 18° 맑음)
|
||||
image VARCHAR(200), -- 올린 사진 경로 (위치 정보를 지운 사본)
|
||||
like_count INTEGER NOT NULL DEFAULT 0,
|
||||
report_count INTEGER NOT NULL DEFAULT 0, -- 로그인한 사람의 신고만 센다
|
||||
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 신고가 쌓이면 자동으로 숨김
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
|
||||
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_like (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_like_anon (
|
||||
talk_id BIGINT NOT NULL,
|
||||
ip_hash CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, ip_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.talk_report (
|
||||
talk_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- TalkReport: 1=욕설·비하 2=광고·도배 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
-- 이 사람 글 안 보기
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL,
|
||||
blocked_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
@@ -289,12 +364,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
priority SMALLINT NOT NULL DEFAULT 2, -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
months JSONB NOT NULL DEFAULT '[]' -- 제철 달 [9, 10, 11]. 비어 있으면 일 년 내내. 제철이 아니면 순위·피드에서 빠진다
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
|
||||
@@ -12,3 +12,5 @@ apscheduler>=3.10,<4
|
||||
pytest
|
||||
python-jose[cryptography]
|
||||
bcrypt
|
||||
python-multipart
|
||||
Pillow
|
||||
@@ -11,10 +11,13 @@ from router.v1.auth.account import router as auth_router
|
||||
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.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
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.talk.talk import router as talk_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
from router.v1.week.week import router as week_router
|
||||
@@ -41,8 +44,11 @@ app.include_router(season_router)
|
||||
app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(my_gak_router)
|
||||
app.include_router(talk_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
@@ -4,7 +4,8 @@ from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
@@ -33,6 +34,17 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
|
||||
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.google(req.credential)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
|
||||
async def auth_config() -> Res_AuthConfig:
|
||||
return Res_AuthConfig(google_client_id=settings.google_client_id or None)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
|
||||
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.refresh(req.refresh_token)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import AuthProvider
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
@@ -15,6 +17,10 @@ class Req_Login(Req_WebPacketProtocol):
|
||||
password: str
|
||||
|
||||
|
||||
class Req_Google(Req_WebPacketProtocol):
|
||||
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
|
||||
|
||||
|
||||
class Req_Refresh(Req_WebPacketProtocol):
|
||||
refresh_token: str
|
||||
|
||||
@@ -47,3 +53,7 @@ class Res_Logout(Res_WebPacketProtocol):
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_AuthConfig(Res_WebPacketProtocol):
|
||||
google_client_id: Optional[str] = Field(None, description="구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다")
|
||||
@@ -5,6 +5,7 @@ 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
|
||||
from common.liker import Liker, liker
|
||||
from common.models.errors import error_info
|
||||
from router.v1.feed.protocol import Res_Feed, Res_Post
|
||||
from services.feed_service import FeedService
|
||||
@@ -15,7 +16,7 @@ router = APIRouter(prefix="/v1/feed", tags=["feed"])
|
||||
|
||||
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
|
||||
async def get_feed(
|
||||
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user),
|
||||
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)
|
||||
@@ -24,10 +25,14 @@ async def get_feed(
|
||||
ids = [p.post_id for p in feed.posts]
|
||||
counts = await reactions.counts(ids)
|
||||
liked, saved = await reactions.marks(user, ids)
|
||||
# 캐시된 피드는 모두에게 같으니, 로그인 안 한 사람의 좋아요 표시는 캐시 밖에서 IP 해시로 덧붙인다
|
||||
anon_liked = await reactions.anon_liked(who.ip_hash, ids) if user is None else set()
|
||||
for p in feed.posts:
|
||||
p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count))
|
||||
if user is not None:
|
||||
p.liked, p.saved = p.post_id in liked, p.post_id in saved
|
||||
else:
|
||||
p.liked = p.post_id in anon_liked
|
||||
return feed
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ class Row(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
||||
level: Optional[int] = Field(default=None, description="자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다")
|
||||
|
||||
|
||||
class HourCell(WebPacketProtocol):
|
||||
@@ -48,6 +49,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)")
|
||||
|
||||
|
||||
class Cut(WebPacketProtocol):
|
||||
@@ -64,6 +67,15 @@ class SunsetSlide(WebPacketProtocol):
|
||||
grade_label: str
|
||||
cuts: list[Cut]
|
||||
situation: Optional[SkySituation] = Field(default=None, description="하늘 상황. 앱이 카드 하늘 색을 고른다")
|
||||
headline: Optional[str] = Field(default=None, description="결론 (나가 볼 만해요 · 애매해요 · 쉬어요). 카드 맨 위에 크게")
|
||||
peak_at: Optional[datetime] = Field(default=None, description="가장 붉을 때")
|
||||
|
||||
|
||||
class WeekGak(WebPacketProtocol):
|
||||
index_id: int
|
||||
name: str
|
||||
icon: str
|
||||
score: int
|
||||
|
||||
|
||||
class WeekDay(WebPacketProtocol):
|
||||
@@ -74,6 +86,7 @@ class WeekDay(WebPacketProtocol):
|
||||
temp_min_c: Optional[float] = None
|
||||
temp_max_c: Optional[float] = None
|
||||
rain_prob: Optional[int] = None
|
||||
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
|
||||
|
||||
|
||||
class WeekSlide(WebPacketProtocol):
|
||||
@@ -131,6 +144,9 @@ class TopIndex(WebPacketProtocol):
|
||||
score: int
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
|
||||
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -145,16 +161,19 @@ class Hero(WebPacketProtocol):
|
||||
sky_mode: Literal["morning", "day", "sunset", "night"]
|
||||
temp_c: Optional[float] = None
|
||||
feels_c: Optional[float] = None
|
||||
discomfort: Optional[int] = None
|
||||
humidity: Optional[int] = Field(default=None, description="지금 습도 %. 히어로에 늘 보인다")
|
||||
discomfort: Optional[int] = Field(default=None, description="지금 불쾌지수. 히어로에 늘 보인다")
|
||||
discomfort_label: Optional[str] = None
|
||||
rain_2h_text: Optional[str] = None
|
||||
will_rain_2h: Optional[bool] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||
top1: Optional[TopIndex] = None
|
||||
bubble: Optional[str] = None
|
||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100")
|
||||
stats: list[HeroStat] = Field(default_factory=list, description="히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)")
|
||||
stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
|
||||
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,8 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from common.models.errors import error_info
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, SlotPoint, TrendPoint
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -16,24 +17,26 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
d = i.definition
|
||||
return IndexSummary(
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
is_core=d.is_core, season=i.season, in_season=i.in_season, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)")
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
core: bool = Query(False, description="이번 계절 핵심 지수만"),
|
||||
core: bool = Query(False, description="지금 제철인 각만"),
|
||||
service: IndexService = Depends(),
|
||||
) -> Res_IndexList:
|
||||
err, board = await service.board(region)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.season)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
|
||||
|
||||
@@ -14,6 +14,12 @@ class TrendPoint(WebPacketProtocol):
|
||||
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||
|
||||
|
||||
class SlotPoint(WebPacketProtocol):
|
||||
slot: str = Field(description="morning / day / evening / night")
|
||||
label: str = Field(description="아침 / 낮 / 저녁 / 밤")
|
||||
score: int
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
@@ -22,16 +28,21 @@ class IndexSummary(WebPacketProtocol):
|
||||
category: IndexCategory
|
||||
is_fun: bool
|
||||
is_core: bool
|
||||
season: Optional[str] = Field(default=None, description="지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음")
|
||||
in_season: bool = Field(default=True, description="false 면 제철이 아니라 순위 밖, 목록 맨 끝")
|
||||
score: int
|
||||
rank: int
|
||||
summary: str
|
||||
trend: list[TrendPoint] = []
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slot: Optional[str] = Field(default=None, description="score 가 어느 구간 점수인지 (지금 구간)")
|
||||
slots: list[SlotPoint] = Field(default=[], description="오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class Res_IndexList(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)")
|
||||
top3: list[IndexSummary] = []
|
||||
items: list[IndexSummary] = []
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,47 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.my_gak.protocol import MyGakData, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakScore
|
||||
from services.my_gak_service import MyGakService
|
||||
|
||||
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))
|
||||
|
||||
|
||||
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
|
||||
async def list_my_gak(user: Optional[User] = Depends(optional_user), service: MyGakService = Depends()) -> Res_MyGakList:
|
||||
if user is None:
|
||||
return Res_MyGakList()
|
||||
err, rows = await service.mine(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_MyGakList(result=error_info(err))
|
||||
return Res_MyGakList(items=[_data(g) for g in rows])
|
||||
|
||||
|
||||
@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))
|
||||
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
|
||||
|
||||
|
||||
@router.post("/score", response_model=Res_MyGakScore, response_model_exclude_none=True, summary="조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)")
|
||||
async def score_my_gak(req: Req_MyGakScore, service: MyGakService = Depends()) -> Res_MyGakScore:
|
||||
err, got = await service.score(req.region_code, [r.model_dump(exclude_none=True) for r in req.rules])
|
||||
if err is not ErrorType.SUCCESS or got is None:
|
||||
return Res_MyGakScore(result=error_info(err))
|
||||
now_slot, scores = got
|
||||
return Res_MyGakScore(now_slot=now_slot, scores=[MyGakScore(**x) for x in scores])
|
||||
|
||||
|
||||
@router.delete("/{my_gak_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 각 지우기")
|
||||
async def delete_my_gak(my_gak_id: int = Path(...), user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, my_gak_id)))
|
||||
@@ -0,0 +1,62 @@
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
Slot = Literal["morning", "day", "evening", "night"]
|
||||
|
||||
|
||||
class MyGakRule(WebPacketProtocol):
|
||||
temp: Optional[list[float]] = Field(None, min_length=2, max_length=2, description="체감온도 범위 [최저, 최고]° (-20~40)")
|
||||
rain: Optional[Literal["dry", "wet"]] = Field(None, description="dry: 비 안 와야 / wet: 비 와야 / 없으면 상관없음")
|
||||
wind_max: Optional[float] = Field(None, ge=1, le=20, description="바람 상한 m/s")
|
||||
air: Optional[Literal["good", "normal"]] = Field(None, description="미세먼지 허용 단계: good 좋음까지 / normal 보통까지")
|
||||
humidity: Optional[list[int]] = Field(None, min_length=2, max_length=2, description="습도 범위 [최저, 최고]%")
|
||||
slots: list[Slot] = Field(default=["morning", "day", "evening", "night"], min_length=1, max_length=4, description="볼 시간대")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check(self) -> "MyGakRule":
|
||||
if self.temp and not (-20 <= self.temp[0] < self.temp[1] <= 40):
|
||||
raise ValueError("temp 는 -20~40 안에서 최저 < 최고")
|
||||
if self.humidity and not (0 <= self.humidity[0] < self.humidity[1] <= 100):
|
||||
raise ValueError("humidity 는 0~100 안에서 최저 < 최고")
|
||||
if not (self.temp or self.rain or self.wind_max is not None or self.air or self.humidity):
|
||||
raise ValueError("조건을 하나 이상 정해야 함")
|
||||
return self
|
||||
|
||||
|
||||
class MyGakData(WebPacketProtocol):
|
||||
my_gak_id: int
|
||||
name: str
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
class Req_MyGak(Req_WebPacketProtocol):
|
||||
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
|
||||
rule: MyGakRule
|
||||
|
||||
|
||||
class Res_MyGakList(Res_WebPacketProtocol):
|
||||
items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음")
|
||||
|
||||
|
||||
class Res_MyGak(Res_WebPacketProtocol):
|
||||
item: Optional[MyGakData] = None
|
||||
|
||||
|
||||
class Req_MyGakScore(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
rules: list[MyGakRule] = Field(min_length=1, max_length=21)
|
||||
|
||||
|
||||
class MyGakScore(WebPacketProtocol):
|
||||
score: Optional[int] = Field(None, description="지금 시간대 점수. 지금이 고른 시간대가 아니면 고른 시간대 중 가장 좋은 점수. 예보가 없으면 null")
|
||||
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
|
||||
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
|
||||
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
|
||||
|
||||
|
||||
class Res_MyGakScore(Res_WebPacketProtocol):
|
||||
now_slot: Optional[Slot] = None
|
||||
scores: list[MyGakScore] = []
|
||||
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType, PostType
|
||||
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
|
||||
@@ -21,19 +22,19 @@ def _comment(v: CommentView) -> CommentData:
|
||||
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))
|
||||
|
||||
|
||||
async def _like(post_id: int, user: User, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
err, count = await service.like_post(post_id, user, on)
|
||||
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
|
||||
err, count = await service.like_post(post_id, who, on)
|
||||
return Res_PostLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요")
|
||||
async def like_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, True, service)
|
||||
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 취소")
|
||||
async def unlike_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, user, False, service)
|
||||
async def unlike_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
|
||||
return await _like(post_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/save", response_model=Res_PostSave, response_model_exclude_none=True, summary="저장")
|
||||
@@ -59,9 +60,10 @@ async def list_saved(cursor: Optional[int] = Query(None), user: User = Depends(c
|
||||
|
||||
@router.get("/post/{post_id}/comment/list", response_model=Res_CommentList, response_model_exclude_none=True, summary="댓글 목록 (로그인 없이 보기)")
|
||||
async def list_comments(
|
||||
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: ReactionService = Depends()
|
||||
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
|
||||
service: ReactionService = Depends(),
|
||||
) -> Res_CommentList:
|
||||
err, items = await service.comments(post_id, user, cursor)
|
||||
err, items = await service.comments(post_id, user, who.ip_hash, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_CommentList(result=error_info(err))
|
||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||
@@ -78,16 +80,16 @@ async def delete_comment(comment_id: int = Path(...), user: User = Depends(curre
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user)))
|
||||
|
||||
|
||||
async def _clike(comment_id: int, user: User, on: bool, service: ReactionService) -> Res_CommentLike:
|
||||
err, count = await service.like_comment(comment_id, user, on)
|
||||
async def _clike(comment_id: int, who: Liker, on: bool, service: ReactionService) -> Res_CommentLike:
|
||||
err, count = await service.like_comment(comment_id, who, on)
|
||||
return Res_CommentLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_CommentLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요")
|
||||
async def like_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, True, service)
|
||||
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||
async def unlike_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, False, service)
|
||||
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, who, False, service)
|
||||
Whitespace-only changes.
@@ -0,0 +1,25 @@
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from common.enums import ErrorType
|
||||
from services.seo_service import SeoService
|
||||
|
||||
router = APIRouter(prefix="/v1/seo", tags=["seo"])
|
||||
|
||||
_SLUG = r"^[a-z]+$"
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)")
|
||||
async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"today/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
||||
async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"today/{sido}/{place}/{gu}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
@@ -11,6 +11,7 @@ class BestTime(WebPacketProtocol):
|
||||
at: datetime
|
||||
kind: str
|
||||
label: str
|
||||
end: Optional[datetime] = Field(default=None, description="구간이면 끝 시각 (골든아워·블루아워)")
|
||||
|
||||
|
||||
class SkyScoreData(WebPacketProtocol):
|
||||
@@ -42,6 +43,8 @@ class PlanSpot(WebPacketProtocol):
|
||||
|
||||
|
||||
class SkyPlanData(WebPacketProtocol):
|
||||
kind: Literal["sunset", "sunrise"] = Field(description="다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을")
|
||||
title: str = Field(description="하늘이 어떻게 보일지 한 문장 (오늘 노을은 물들긴 하는데 색이 흐릴 거예요). 히어로 제목")
|
||||
day: date
|
||||
when: str
|
||||
verdict: Literal["go", "maybe", "rest"]
|
||||
@@ -66,6 +69,7 @@ class Res_Sky(Res_WebPacketProtocol):
|
||||
days: list[SkyScoreData] = []
|
||||
spots: list[SpotData] = []
|
||||
plan: Optional[SkyPlanData] = None
|
||||
plans: list[SkyPlanData] = Field(default=[], description="plan 과 같은 종류로 아직 안 끝난 날 최대 3일 (날짜 타일, 누르면 그날로)")
|
||||
|
||||
|
||||
class RankData(WebPacketProtocol):
|
||||
|
||||
@@ -26,6 +26,7 @@ def _situation(x: SkyScore) -> str | None:
|
||||
|
||||
def _plan(p: SkyPlan) -> SkyPlanData:
|
||||
return SkyPlanData(
|
||||
kind="sunrise" if p.kind is SkyType.SUNRISE else "sunset", title=p.title,
|
||||
day=p.day, when=p.when, verdict=p.verdict, headline=p.headline, reason=p.reason, score=p.score, grade_label=p.grade_label,
|
||||
situation_label=p.situation_label, models_total=p.models_total, models_agree=p.models_agree,
|
||||
best_at=p.best_at, spot=PlanSpot(name=p.spot.spot.name, distance_km=p.spot.distance_km) if p.spot else None,
|
||||
@@ -48,6 +49,7 @@ async def get_sky(region: str = Query(..., description="구 행정코드"), serv
|
||||
for i, s in enumerate(view.spots)
|
||||
],
|
||||
plan=_plan(view.plan) if view.plan else None,
|
||||
plans=[_plan(p) for p in view.plans],
|
||||
)
|
||||
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import TalkReport
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class TalkData(WebPacketProtocol):
|
||||
talk_id: int
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
region_name: Optional[str] = Field(None, description="쓴 사람이 고른 동네 (성남시 분당구)")
|
||||
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
|
||||
body: str
|
||||
image: Optional[str] = Field(None, description="올린 사진 주소")
|
||||
like_count: int
|
||||
liked: bool
|
||||
mine: bool
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Req_Talk(Req_WebPacketProtocol):
|
||||
region_code: str = Field(min_length=10, max_length=10)
|
||||
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
|
||||
image: Optional[str] = Field(None, max_length=200, description="먼저 올린 사진 주소 (POST /v1/talk/image 결과)")
|
||||
|
||||
|
||||
class Req_TalkReport(Req_WebPacketProtocol):
|
||||
reason: TalkReport
|
||||
|
||||
|
||||
class Res_TalkList(Res_WebPacketProtocol):
|
||||
talks: list[TalkData] = []
|
||||
next_cursor: Optional[int] = None
|
||||
|
||||
|
||||
class Res_Talk(Res_WebPacketProtocol):
|
||||
talk: Optional[TalkData] = None
|
||||
|
||||
|
||||
class Res_TalkLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Res_TalkImage(Res_WebPacketProtocol):
|
||||
image: Optional[str] = Field(None, description="글에 붙일 사진 주소")
|
||||
@@ -0,0 +1,89 @@
|
||||
from typing import Optional
|
||||
|
||||
import asyncio
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Path, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from common.auth import current_user, optional_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
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 router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData
|
||||
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
|
||||
from services.talk_service import PAGE, TalkService, TalkView
|
||||
|
||||
router = APIRouter(prefix="/v1/talk", tags=["talk"])
|
||||
|
||||
|
||||
def _data(v: TalkView) -> TalkData:
|
||||
t, u = v.talk, v.author
|
||||
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, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)")
|
||||
async def list_talks(
|
||||
cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: TalkService = Depends()
|
||||
) -> Res_TalkList:
|
||||
err, views = await service.page(user, who.ip_hash, cursor)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_TalkList(result=error_info(err))
|
||||
talks = [_data(v) for v in views]
|
||||
return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
|
||||
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
|
||||
err, v = await service.add(user, req.region_code, req.body, req.image)
|
||||
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
|
||||
|
||||
|
||||
@router.post("/image", response_model=Res_TalkImage, response_model_exclude_none=True, summary="글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)")
|
||||
async def upload_talk_image(file: UploadFile = File(...), user: User = Depends(current_user)) -> Res_TalkImage:
|
||||
data = await file.read(MAX_BYTES + 1)
|
||||
err, url = await asyncio.to_thread(save, data)
|
||||
return Res_TalkImage(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkImage(image=url)
|
||||
|
||||
|
||||
@router.get("/image/{name}", summary="올린 사진", response_class=FileResponse)
|
||||
async def get_talk_image(name: str = Path(..., max_length=40)) -> FileResponse:
|
||||
path = file_of(URL_PREFIX + name)
|
||||
if path is None:
|
||||
raise HTTPException(status_code=404)
|
||||
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "public, max-age=31536000, immutable"})
|
||||
|
||||
|
||||
@router.delete("/{talk_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 이야기 지우기")
|
||||
async def delete_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.delete(user, talk_id)))
|
||||
|
||||
|
||||
async def _like(talk_id: int, who: Liker, on: bool, service: TalkService) -> Res_TalkLike:
|
||||
err, count = await service.like(who, talk_id, on)
|
||||
return Res_TalkLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkLike(liked=on, like_count=count)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 (로그인 없으면 IP 당 한 번)")
|
||||
async def like_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, who, True, service)
|
||||
|
||||
|
||||
@router.delete("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 취소")
|
||||
async def unlike_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
|
||||
return await _like(talk_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/{talk_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이야기 신고 (서로 다른 3명이면 숨김)")
|
||||
async def report_talk(req: Req_TalkReport, talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report(user, talk_id, req.reason)))
|
||||
|
||||
|
||||
@router.post("/{talk_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 글 쓴 사람의 글 안 보기")
|
||||
async def block_talk_author(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(user, talk_id)))
|
||||
@@ -9,6 +9,7 @@ class WatchNow(WebPacketProtocol):
|
||||
temp_c: Optional[float] = None
|
||||
icon: Optional[str] = None
|
||||
rain_2h: Optional[bool] = None
|
||||
thunder: Optional[bool] = None # 2시간 안에 낙뢰 예보
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
@@ -93,11 +93,11 @@ async def get_watch_summary(
|
||||
for s in today.slots if s.at > now
|
||||
]
|
||||
if now_w is not None:
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text})
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "thunder": now_w.thunder_2h, "text": now_w.rain_2h_text})
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
res.top = [_top(i) for i in board.items[:TOP_N]]
|
||||
res.top = [_top(i) for i in board.ranked[:TOP_N]]
|
||||
codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS]
|
||||
by_code = {i.definition.code: i for i in board.items}
|
||||
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
|
||||
|
||||
@@ -5,7 +5,7 @@ import sys
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT, _cond # noqa: E402
|
||||
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
@@ -64,12 +64,16 @@ def tim(r):
|
||||
return "달이 어두울수록 좋음 (보름 20점 → 그믐 100점)"
|
||||
if t == "sunset_score":
|
||||
return "그날 노을 점수를 그대로 씀"
|
||||
if t == "sunrise_score":
|
||||
return "그날 일출 하늘 점수를 그대로 씀"
|
||||
return f"고정 {r['value']}점"
|
||||
|
||||
|
||||
def zero(z):
|
||||
if z["field"] == "warning":
|
||||
return f"{z['value']} 특보가 있으면"
|
||||
if z["field"] not in FIELD:
|
||||
return _cond(z)[2] + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
name, unit = FIELD[z["field"]]
|
||||
op = "이상" if z["op"] == ">=" else "미만"
|
||||
s = f"{name} {z['value']}{unit} {op}이면"
|
||||
@@ -83,7 +87,7 @@ def air(r):
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} {'이상이면' if r['full'] > r['zero'] else '이하면'} 만점, {r['zero']} {'이하면' if r['full'] > r['zero'] else '이상이면'} 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
("time", "시간·요일", tim)]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""/faq 지역 질문에 넣을 지역별 장소를 시드로 다시 만든다. 시도마다 한 파일: frontend/seo/region_faq/seoul.json
|
||||
|
||||
region.json 이나 place*.csv, sunset_spot.csv 가 바뀌면 실행: python backend/scripts/gen_region_faq.py
|
||||
앱 번들에 들어가는 region.json 을 키우지 않으려고 따로 둔다. vite 빌드가 /faq 를 만들 때만 읽는다.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SEED = os.path.join(ROOT, "backend", "seed")
|
||||
PAGES = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||
OUT = os.path.join(ROOT, "frontend", "seo", "region_faq")
|
||||
|
||||
OUTDOOR, INDOOR, SUNSET = 3, 2, 2
|
||||
|
||||
|
||||
def rows(name: str) -> list[dict]:
|
||||
return list(csv.DictReader(open(os.path.join(SEED, name), encoding="utf-8")))
|
||||
|
||||
|
||||
# 손으로 고른 장소를 관광공사 장소보다 먼저
|
||||
places = rows("place.csv") + rows("place_tourapi.csv")
|
||||
sunsets = rows("sunset_spot.csv")
|
||||
|
||||
|
||||
def pick(found: list[dict], n: int) -> list[str]:
|
||||
"""아이콘(산책·피크닉·사진…)이 겹치지 않게 먼저 고르고, 모자라면 순서대로 채운다."""
|
||||
out, icons = [], set()
|
||||
for p in found:
|
||||
if p["icon"] not in icons and p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
icons.add(p["icon"])
|
||||
for p in found:
|
||||
if p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
return out[:n]
|
||||
|
||||
|
||||
result = {}
|
||||
for page in json.load(open(PAGES, encoding="utf-8")):
|
||||
names = {r["name"] for r in page["regions"]}
|
||||
mine = [p for p in places if p["region_name"] in names]
|
||||
result[page["path"]] = dict(
|
||||
outdoor=pick([p for p in mine if p["is_outdoor"] == "1"], OUTDOOR),
|
||||
indoor=pick([p for p in mine if p["is_outdoor"] == "0"], INDOOR),
|
||||
sunset=list(dict.fromkeys(s["name"] for s in sunsets if s["region_name"] in names))[:SUNSET],
|
||||
)
|
||||
# 시도마다 한 파일 (seoul.json). 지난번에 만든 시도 파일은 지우고 다시 쓴다
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
for f in os.listdir(OUT):
|
||||
if f.endswith(".json"):
|
||||
os.remove(os.path.join(OUT, f))
|
||||
by_sido = {}
|
||||
for path, spots in result.items():
|
||||
by_sido.setdefault(path.split("/")[0], {})[path] = spots
|
||||
for sido, part in by_sido.items():
|
||||
json.dump(part, open(os.path.join(OUT, f"{sido}.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
||||
print(len(result), "pages", sum(any(v.values()) for v in result.values()), "with places", len(by_sido), "files")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)을 seed/region.csv 로 다시 만든다.
|
||||
|
||||
region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SRC = os.path.join(ROOT, "backend", "seed", "region.csv")
|
||||
OUT = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||
|
||||
SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju')
|
||||
R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong
|
||||
목포 mokpo 여수 yeosu 순천 suncheon 나주 naju 광양 gwangyang 동 dong 서 seo 남 nam 북 buk 광산 gwangsan 담양 damyang 곡성 gokseong 구례 gurye 고흥 goheung 보성 boseong 화순 hwasun 장흥 jangheung 강진 gangjin 해남 haenam 영암 yeongam 무안 muan 함평 hampyeong 영광 yeonggwang 장성 jangseong 완도 wando 진도 jindo 신안 sinan
|
||||
영도 yeongdo 부산진 busanjin 동래 dongnae 해운대 haeundae 사하 saha 금정 geumjeong 연제 yeonje 수영 suyeong 사상 sasang 기장 gijang 수성 suseong 달서 dalseo 달성 dalseong 군위 gunwi
|
||||
제물포 jemulpo 영종 yeongjong 미추홀 michuhol 연수 yeonsu 남동 namdong 부평 bupyeong 계양 gyeyang 서해 seohae 검단 geomdan 강화 ganghwa 옹진 ongjin 유성 yuseong 대덕 daedeok 울주 ulju 세종특별자치 sejong
|
||||
수원 suwon 성남 seongnam 의정부 uijeongbu 안양 anyang 부천 bucheon 광명 gwangmyeong 평택 pyeongtaek 동두천 dongducheon 안산 ansan 고양 goyang 과천 gwacheon 구리 guri 남양주 namyangju 오산 osan 시흥 siheung 군포 gunpo 의왕 uiwang 하남 hanam 용인 yongin 파주 paju 이천 icheon 안성 anseong 김포 gimpo 화성 hwaseong 광주 gwangju 양주 yangju 포천 pocheon 여주 yeoju 연천 yeoncheon 가평 gapyeong 양평 yangpyeong
|
||||
청주 cheongju 충주 chungju 제천 jecheon 보은 boeun 옥천 okcheon 영동 yeongdong 증평 jeungpyeong 진천 jincheon 괴산 goesan 음성 eumseong 단양 danyang
|
||||
천안 cheonan 공주 gongju 보령 boryeong 아산 asan 서산 seosan 논산 nonsan 계룡 gyeryong 당진 dangjin 금산 geumsan 부여 buyeo 서천 seocheon 청양 cheongyang 홍성 hongseong 예산 yesan 태안 taean
|
||||
포항 pohang 경주 gyeongju 김천 gimcheon 안동 andong 구미 gumi 영주 yeongju 영천 yeongcheon 상주 sangju 문경 mungyeong 경산 gyeongsan 의성 uiseong 청송 cheongsong 영양 yeongyang 영덕 yeongdeok 청도 cheongdo 고령 goryeong 성주 seongju 칠곡 chilgok 예천 yecheon 봉화 bonghwa 울진 uljin 울릉 ulleung
|
||||
창원 changwon 진주 jinju 통영 tongyeong 사천 sacheon 김해 gimhae 밀양 miryang 거제 geoje 양산 yangsan 의령 uiryeong 함안 haman 창녕 changnyeong 고성 goseong 남해 namhae 하동 hadong 산청 sancheong 함양 hamyang 거창 geochang 합천 hapcheon 제주 jeju 서귀포 seogwipo
|
||||
춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang
|
||||
전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split()
|
||||
ROMAN = dict(zip(R[::2], R[1::2]))
|
||||
G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji
|
||||
만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split()
|
||||
GU = dict(zip(G[::2], G[1::2]))
|
||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||
pages = {}
|
||||
for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||
sido, *rest = row['name'].split()
|
||||
place = rest[0]
|
||||
r = dict(code=row['code'], name=row['name'], short_name=row['short_name'], lat=float(row['lat']), lon=float(row['lon']))
|
||||
path = f"{SIDO[sido]}/{ROMAN[place[:-1]]}"
|
||||
p = pages.setdefault(path, dict(path=path, name='세종시' if sido == '세종' else f'{sido} {place}', main=None, regions=[]))
|
||||
p['regions'].append(r)
|
||||
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||
p['main'] = r['code']
|
||||
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
||||
if len(rest) == 2:
|
||||
gu = f"{path}/{GU[rest[1][:-1]]}"
|
||||
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
||||
out = list(pages.values())
|
||||
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
||||
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
||||
+2721
-142
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
@@ -6,6 +7,7 @@ from fastapi import Depends
|
||||
|
||||
from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.google_id import verify as verify_google
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
|
||||
|
||||
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
|
||||
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
|
||||
|
||||
|
||||
def auto_nickname() -> str:
|
||||
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
|
||||
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
|
||||
self.crud = crud
|
||||
@@ -47,6 +58,26 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
|
||||
sub = await verify_google(credential)
|
||||
if sub is None:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
login_id = f"google_{sub}"
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if user is None:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
|
||||
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
|
||||
if claims is None:
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
||||
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
NIGHT_END_HOUR = 5
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if NIGHT_END_HOUR <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]:
|
||||
"""그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다."""
|
||||
out: dict[str, set[int]] = {s: set() for s in SLOTS}
|
||||
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||
for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR):
|
||||
out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h)
|
||||
return out
|
||||
@@ -54,6 +54,9 @@ class Context:
|
||||
sunset_score: Optional[int]
|
||||
wind_warning: bool
|
||||
lookahead_rain_prob: int
|
||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -115,7 +118,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
return _range(t, lo, hi, rule.get("best"), rule.get("plateau", _TEMP_PLATEAU), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
if rule["type"] == "away":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
@@ -197,18 +200,22 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
v = rule.get(key, rule.get("default", 100))
|
||||
return _clamp(v), f"{_WEEKDAY_KO[ctx.day.weekday()]}요일{' 공휴일' if ctx.is_holiday else ''}"
|
||||
if kind == "moon":
|
||||
return _clamp(20 + 80 * (1 - ctx.moon)), f"달 밝기 {round(ctx.moon * 100)}%"
|
||||
return _clamp(20 + 80 * (1 - ctx.moon)), ctx.moon_note or f"달이 비추는 정도 {round(ctx.moon * 100)}%"
|
||||
if kind == "sunset_score":
|
||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
if kind == "sunrise_score":
|
||||
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
|
||||
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
|
||||
|
||||
|
||||
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
@@ -223,7 +230,7 @@ def axis_label(axis: str, rules: dict) -> str:
|
||||
rule = rules.get("air", _AIR_RULE)
|
||||
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
return rules[axis].get("label") or table[rules[axis]["type"]]
|
||||
|
||||
|
||||
def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
@@ -243,15 +250,21 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
|
||||
_FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도", "humidity": "습도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°", "humidity": "%"}
|
||||
|
||||
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
|
||||
if r["field"] == "snow":
|
||||
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
||||
if r["field"] == "rain":
|
||||
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
|
||||
if r["field"] == "rain_before":
|
||||
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
|
||||
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
||||
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
||||
|
||||
@@ -332,6 +345,9 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
||||
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
|
||||
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
@@ -350,7 +366,7 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
@@ -380,7 +396,10 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
|
||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
||||
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
||||
if reason is not None:
|
||||
score = min(score, cap)
|
||||
mid = hours[len(hours) // 2]
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
_SYNODIC_DAYS = 29.530588
|
||||
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
|
||||
@@ -11,10 +15,12 @@ def illumination(at: datetime) -> float:
|
||||
|
||||
|
||||
def _fraction(at: datetime) -> float:
|
||||
"""직전 삭에서 다음 삭까지 얼마나 지났는지 0~1. 앞뒤 삭은 실제 시각(nearest)으로 잡는다."""
|
||||
near = nearest(at, False)
|
||||
prev, nxt = (near, nearest(near + timedelta(days=_SYNODIC_DAYS), False)) if near <= at else (nearest(near - timedelta(days=_SYNODIC_DAYS), False), near)
|
||||
return (at - prev) / (nxt - prev)
|
||||
"""달이 해보다 황경으로 얼마나 앞섰는지 0~1 (0 삭, 0.5 보름). 실제 위치로 보므로 보름·삭 시각과 맞는다."""
|
||||
d = _days(at)
|
||||
t = d / 36525
|
||||
m = math.radians(357.52911 + 35999.05029 * t)
|
||||
sun = 280.46646 + 36000.76983 * t + 1.914602 * math.sin(m) + 0.019993 * math.sin(2 * m)
|
||||
return ((math.degrees(_ecliptic(d)[0]) - sun) % 360) / 360
|
||||
|
||||
|
||||
# 달 모양 이름. 차오르는 비율(0 삭 → 0.5 보름 → 1 삭) 구간마다
|
||||
@@ -51,3 +57,99 @@ def nearest(at: datetime, full: bool) -> datetime:
|
||||
offset = 0.5 if full else 0.0
|
||||
k = round((at - _KNOWN_NEW_MOON).total_seconds() / 86400 / _SYNODIC_DAYS - offset) + offset
|
||||
return min((_true_phase(k + dk, full) for dk in (-1, 0, 1)), key=lambda x: abs(x - at))
|
||||
|
||||
|
||||
_HORIZON = -0.83 # 달 윗면이 지평선에 닿는 고도 (대기 굴절·반지름 포함, 지표에서 본 고도 기준)
|
||||
_NIGHT = (19, 29) # '오늘 밤': 19시~다음 날 5시
|
||||
_STEP = timedelta(minutes=10)
|
||||
|
||||
|
||||
def _days(at: datetime) -> float:
|
||||
return (at - datetime(2000, 1, 1, 12, tzinfo=timezone.utc)).total_seconds() / 86400
|
||||
|
||||
|
||||
def _ecliptic(d: float) -> tuple[float, float, float]:
|
||||
"""2000-01-01 12시(UTC)부터 d 일 뒤 달의 황경·황위(라디안)와 거리(km). Meeus 47장 주요 항만 쓴 간이식, 오차 0.5° 안팎."""
|
||||
t = d / 36525
|
||||
r, s, c = math.radians, math.sin, math.cos
|
||||
lp = 218.3164477 + 481267.88123421 * t
|
||||
dd = r(297.8501921 + 445267.1114034 * t)
|
||||
m = r(357.5291092 + 35999.0502909 * t)
|
||||
mp = r(134.9633964 + 477198.8675055 * t)
|
||||
f = r(93.2720950 + 483202.0175233 * t)
|
||||
lam = r(lp + 6.289 * s(mp) + 1.274 * s(2 * dd - mp) + 0.658 * s(2 * dd) + 0.214 * s(2 * mp) - 0.186 * s(m) - 0.114 * s(2 * f))
|
||||
beta = r(5.128 * s(f) + 0.281 * s(mp + f) + 0.278 * s(mp - f) + 0.173 * s(2 * dd - f))
|
||||
dist_km = 385001 - 20905 * c(mp) - 3699 * c(2 * dd - mp) - 2956 * c(2 * dd)
|
||||
return lam, beta, dist_km
|
||||
|
||||
|
||||
def altitude(at: datetime, lat: float, lon: float) -> float:
|
||||
"""그 시각 그 자리에서 본 달 고도(도). 뜨고 지는 시각은 몇 분 차이."""
|
||||
d = _days(at)
|
||||
r, s, c = math.radians, math.sin, math.cos
|
||||
lam, beta, dist_km = _ecliptic(d)
|
||||
eps = r(23.439 - 0.0000004 * d)
|
||||
ra = math.atan2(s(lam) * c(eps) - math.tan(beta) * s(eps), c(lam))
|
||||
dec = math.asin(s(beta) * c(eps) + c(beta) * s(eps) * s(lam))
|
||||
ha = r(280.46061837 + 360.98564736629 * d + lon) - ra
|
||||
phi = r(lat)
|
||||
alt = math.asin(s(phi) * s(dec) + c(phi) * c(dec) * c(ha))
|
||||
return math.degrees(alt - math.asin(6378.14 / dist_km) * c(alt))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MoonNight:
|
||||
"""그날 밤(19시~다음 날 5시) 달. lit 는 빛나는 면의 비율(모양), 밝기가 아니다."""
|
||||
name: str
|
||||
lit: float
|
||||
waxing: bool # 삭 → 보름 사이 (해 진 뒤 서쪽 하늘에 있다가 지는 쪽)
|
||||
rise_at: Optional[datetime] # 밤 사이에 뜨면 그 시각 (저녁부터 떠 있으면 None)
|
||||
set_at: Optional[datetime] # 밤 사이에 지면 그 시각 (새벽까지 떠 있으면 None)
|
||||
up_hours: tuple[int, ...] # 달이 떠 있는 시각 (19~28, 24 이상은 다음 날)
|
||||
|
||||
|
||||
def night(day: date, lat: float, lon: float) -> MoonNight:
|
||||
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||
mid = start + timedelta(hours=23)
|
||||
at, end = start + timedelta(hours=_NIGHT[0]), start + timedelta(hours=_NIGHT[1])
|
||||
prev = altitude(at, lat, lon) > _HORIZON
|
||||
rise_at = set_at = None
|
||||
ups: set[int] = set()
|
||||
while at < end:
|
||||
up = altitude(at, lat, lon) > _HORIZON
|
||||
if up and not prev and rise_at is None:
|
||||
rise_at = at
|
||||
if prev and not up and set_at is None:
|
||||
set_at = at
|
||||
if up:
|
||||
ups.add(int((at - start).total_seconds() // 3600))
|
||||
prev = up
|
||||
at += _STEP
|
||||
return MoonNight(name=phase_name(mid), lit=illumination(mid), waxing=_fraction(mid) < 0.5, rise_at=rise_at, set_at=set_at, up_hours=tuple(sorted(ups)))
|
||||
|
||||
|
||||
def up_ratio(m: MoonNight, hours: range) -> float:
|
||||
"""hours(19~28 기준 시각) 중 달이 떠 있는 비율."""
|
||||
return sum(h in m.up_hours for h in hours) / len(hours)
|
||||
|
||||
|
||||
def view_line(m: MoonNight, cloudy: Optional[float]) -> str:
|
||||
"""오늘 밤 달이 잘 보이는지 한 마디. 안 보이면 왜인지까지. cloudy 는 달이 떠 있는 동안 흐린 정도 0~1 (모르면 None)."""
|
||||
if m.lit < 0.03:
|
||||
return "해와 같은 쪽에 있어 안 보여요"
|
||||
if not m.up_hours:
|
||||
return "해 진 뒤 곧 져서 밤엔 안 보여요" if m.waxing else "새벽 늦게 떠서 밤엔 안 보여요"
|
||||
if m.rise_at is not None and m.rise_at.hour not in range(19, 22):
|
||||
return f"{_clock(m.rise_at)}에 떠요"
|
||||
if cloudy is not None and cloudy >= 0.6:
|
||||
return "흐려서 구름에 가려요"
|
||||
if cloudy is not None and cloudy >= 0.3:
|
||||
return "구름 사이로 보여요"
|
||||
if m.set_at is not None:
|
||||
return f"{_clock(m.set_at)}까지 보여요"
|
||||
return "밤새 잘 보여요"
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
h = at.astimezone(KST).hour
|
||||
return f"{'새벽' if h < 6 else '밤' if h >= 21 or h == 0 else '저녁'} {h % 12 or 12}시"
|
||||
@@ -0,0 +1,52 @@
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from typing import Literal, Optional
|
||||
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
|
||||
|
||||
Rain = Literal["dry", "wet"]
|
||||
Air = Literal["good", "normal"]
|
||||
|
||||
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
|
||||
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
|
||||
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
|
||||
|
||||
|
||||
def _n(v: float) -> float:
|
||||
"""근거 문구에 15.0° 대신 15° 로 나오게."""
|
||||
return int(v) if float(v).is_integer() else v
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MyRule:
|
||||
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
|
||||
|
||||
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
|
||||
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
|
||||
wind_max: Optional[float] = None # 바람 상한(m/s)
|
||||
air: Optional[Air] = None # 미세먼지 허용 단계
|
||||
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
|
||||
slots: tuple[str, ...] = SLOTS # 볼 시간대
|
||||
|
||||
|
||||
def axes(rule: MyRule) -> list[str]:
|
||||
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
|
||||
|
||||
|
||||
def definition(rule: MyRule) -> SimpleNamespace:
|
||||
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
|
||||
used = axes(rule)
|
||||
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
|
||||
return SimpleNamespace(
|
||||
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
|
||||
"rain": {"dir": rule.rain or "dry"},
|
||||
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
|
||||
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
|
||||
"air": _AIR[rule.air] if rule.air else None,
|
||||
"time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
|
||||
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
@@ -1,14 +1,17 @@
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
|
||||
DISTANCES_KM = (20, 100)
|
||||
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 40점 = 은은함).
|
||||
_CLEAR_CANVAS = 0.2
|
||||
# 물들 구름이 하나도 없을 때의 canvas 값. 50% 까지 곧게 올라가 맑은 날도 구름 몇 % 차이로 점수가 갈린다 (맑은 하늘 55점 = 은은함).
|
||||
_CLEAR_CANVAS = 0.4
|
||||
# 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다.
|
||||
RAIN_BEFORE_HOURS = (2, 6)
|
||||
# 서쪽이 바다·강·전망대로 트여 해가 지평선까지 보이는 곳은 산·건물에 가리지 않아 노을이 더 잘 보인다.
|
||||
OPEN_WEST_BONUS = 1.1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -25,6 +28,7 @@ class Air:
|
||||
humidity: float | None = None
|
||||
rain_before: int | None = None # RAIN_BEFORE_HOURS 사이 가장 높은 비 확률
|
||||
rain_now: int | None = None
|
||||
open_west: bool = False # 가까이 서쪽이 트인 노을 명소가 있음 (노을만)
|
||||
|
||||
|
||||
def score(near20: Layers, far100: Layers) -> int:
|
||||
@@ -36,24 +40,94 @@ def score(near20: Layers, far100: Layers) -> int:
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
|
||||
def _ramp(v: float, bad: float, good: float, low: float) -> float:
|
||||
"""good 쪽은 1.0, bad 쪽은 low, 사이는 직선."""
|
||||
t = max(0.0, min(1.0, (v - bad) / (good - bad)))
|
||||
return low + (1 - low) * t
|
||||
# 공기 보정 기준점 (값, 배수). 평소 공기(가시거리 20km, 습도 60%)가 ×1.0 이고 좋으면 올리고 나쁘면 내린다. 양 끝 밖은 끝 값 그대로.
|
||||
_VISIBILITY_FACTOR = ((5, 0.8), (20, 1.0), (40, 1.12))
|
||||
_HUMIDITY_FACTOR = ((40, 1.06), (60, 1.0), (90, 0.85))
|
||||
|
||||
|
||||
def _interp(v: float, points: tuple[tuple[float, float], ...]) -> float:
|
||||
"""기준점 사이를 직선으로 잇는다."""
|
||||
if v <= points[0][0]:
|
||||
return points[0][1]
|
||||
for (x0, f0), (x1, f1) in zip(points, points[1:]):
|
||||
if v <= x1:
|
||||
return f0 + (f1 - f0) * (v - x0) / (x1 - x0)
|
||||
return points[-1][1]
|
||||
|
||||
|
||||
def air_factor(air: Air) -> float:
|
||||
"""공기로 구름 점수를 보정하는 배수. 뿌연 공기·높은 습도는 색을 흐리게 하고, 비 갠 뒤는 더 붉다."""
|
||||
"""공기로 구름 점수를 보정하는 배수. 맑고 건조하면 올리고 뿌옇거나 습하면 내린다. 비 갠 뒤는 더 붉다."""
|
||||
f = 1.0
|
||||
if air.visibility_km is not None:
|
||||
f *= _ramp(air.visibility_km, 5, 40, 0.6)
|
||||
f *= _interp(air.visibility_km, _VISIBILITY_FACTOR)
|
||||
if air.humidity is not None:
|
||||
f *= _ramp(air.humidity, 90, 50, 0.75)
|
||||
f *= _interp(air.humidity, _HUMIDITY_FACTOR)
|
||||
if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40:
|
||||
f *= 1.15
|
||||
if air.open_west:
|
||||
f *= OPEN_WEST_BONUS
|
||||
return f
|
||||
|
||||
|
||||
HAZY = 0.7 # 공기 보정이 이보다 작으면 결론을 한 단계 낮추고 이유에 공기를 말한다
|
||||
|
||||
|
||||
def air_note(air: Optional[dict]) -> Optional[str]:
|
||||
"""공기 보정이 크게 깎였으면 그 이유를 눈에 보이는 말로 (숫자 없이). 아니면 None.
|
||||
가시거리 20km 미만 = 먼 건물이 흐릿하게 보이는 정도, 습도 70% 이상 = 습한 공기."""
|
||||
if not air or air.get("factor") is None or air["factor"] >= HAZY:
|
||||
return None
|
||||
hazy = air.get("visibility_km") is not None and air["visibility_km"] < 20
|
||||
humid = air.get("humidity") is not None and air["humidity"] >= 70
|
||||
if hazy and humid:
|
||||
return "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"
|
||||
if hazy:
|
||||
return "먼 건물이 흐릿할 만큼 공기가 뿌예서 노을 색이 바래 보일 거예요"
|
||||
return "공기가 습해서 노을 색이 바래 보일 거예요"
|
||||
|
||||
|
||||
def topic(word: str) -> str:
|
||||
"""받침 있으면 '은', 없으면 '는'. 오늘은 · 모레는"""
|
||||
last = ord(word[-1]) - 0xAC00
|
||||
return f"{word}{'은' if 0 <= last < 11172 and last % 28 else '는'}"
|
||||
|
||||
|
||||
GRADE_RANK = {SkyGrade.GRAY: 0, SkyGrade.SOFT: 1, SkyGrade.GLOW: 2, SkyGrade.RED: 3}
|
||||
|
||||
|
||||
def sky_title(
|
||||
grade_: SkyGrade, kind: SkyType = SkyType.SUNSET, when: Optional[str] = None, peak_at: Optional[datetime] = None,
|
||||
) -> str:
|
||||
"""히어로·피드 카드 큰 글씨. 점수 등급으로: 잿빛이면 거의 안 보인다고, 아니면 노을 피크 시각과 어떻게 물드는지.
|
||||
when 이 없으면 날 없이(피드 카드)."""
|
||||
w = "아침 노을" if kind is SkyType.SUNRISE else "노을"
|
||||
if grade_ is SkyGrade.GRAY:
|
||||
return f"{topic(when) + ' ' if when else ''}{w}이 거의 안 보여요"
|
||||
pre = f"{peak_at:%H:%M}, " if peak_at is not None else ""
|
||||
day = f"{when} " if when else ""
|
||||
if grade_ is SkyGrade.RED:
|
||||
sky = "아침 하늘" if kind is SkyType.SUNRISE else "하늘"
|
||||
return f"{pre}{day}{sky}이 온통 붉게 물들어요"
|
||||
how = "곱게" if grade_ is SkyGrade.GLOW else "은은하게"
|
||||
return f"{pre}{day}{w}이 {how} 물들어요"
|
||||
|
||||
|
||||
def plain_line(grade_: SkyGrade, situation: SkySituation | None, air: Optional[dict], kind: SkyType = SkyType.SUNSET) -> Optional[str]:
|
||||
"""잿빛 날만, 큰 글씨 아래 왜 안 보이는지 한 줄. 다른 날은 없음."""
|
||||
if grade_ is not SkyGrade.GRAY:
|
||||
return None
|
||||
side = "해 뜨는 쪽" if kind is SkyType.SUNRISE else "해 지는 쪽"
|
||||
by_situation = {
|
||||
SkySituation.COVERED: f"{side} 하늘이 구름에 가려요",
|
||||
SkySituation.LOW_CLOUD: "구름이 낮게 깔려 있어요",
|
||||
SkySituation.THICK: "구름이 너무 두꺼워요",
|
||||
SkySituation.FEW: "구름이 거의 없어요",
|
||||
}
|
||||
if situation in by_situation:
|
||||
return by_situation[situation]
|
||||
return "하늘이 뿌예서 색이 바래요" if air_note(air) else None
|
||||
|
||||
|
||||
def grade(value: int) -> SkyGrade:
|
||||
if value >= 80:
|
||||
return SkyGrade.RED
|
||||
@@ -131,23 +205,42 @@ SITUATION_VERDICT = {
|
||||
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
|
||||
|
||||
|
||||
def reason(near20: Layers, far100: Layers) -> str:
|
||||
def reason(near20: Layers, far100: Layers, kind: SkyType = SkyType.SUNSET) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
side = "해 뜨는 쪽" if kind is SkyType.SUNRISE else "해 지는 쪽"
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
||||
return f"{side} 멀리까지 구름이 끼어 햇빛이 하늘을 물들이지 못해요"
|
||||
if near20.low >= 60:
|
||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
||||
return "낮게 깔린 구름이 하늘을 덮어 붉은빛을 가려요"
|
||||
canvas = round(max(near20.mid, near20.high))
|
||||
if canvas < 10:
|
||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
||||
return "하늘에 구름이 거의 없어요. 노을은 구름에 햇빛이 비쳐야 붉어져서 은은하게 끝나요"
|
||||
if canvas > 85:
|
||||
return f"중·높은 구름이 {canvas}%로 두꺼워 빛이 덜 비쳐요"
|
||||
return "구름이 너무 두껍게 덮여 햇빛이 잘 안 비쳐요"
|
||||
if 25 <= canvas <= 75:
|
||||
return f"중·높은 구름이 {canvas}% 알맞게 깔리고 해 지는 쪽이 트였어요"
|
||||
return f"물들 중·높은 구름이 {canvas}%로 {'적은' if canvas < 25 else '많은'} 편이에요"
|
||||
return f"{side} 하늘에 구름이 적당히 있어 햇빛을 받아 물들기 좋아요"
|
||||
return f"구름이 {'적은' if canvas < 25 else '많은'} 편이라 물드는 색이 약할 수 있어요"
|
||||
|
||||
|
||||
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime) -> list[dict]:
|
||||
"""일몰 전 골든아워 → 해 짐 → 가장 붉을 때 → 블루아워. 분 아래는 버린다."""
|
||||
rows = [("golden", "골든아워", golden_at), ("sun", "해 져요", sun_at), ("peak", "가장 붉을 때", peak_at), ("blue", "블루아워", blue_at)]
|
||||
return [{"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label} for kind, label, at in rows if at is not None]
|
||||
def _row(kind: str, label: str, at: datetime | None, end: datetime | None = None) -> dict | None:
|
||||
if at is None:
|
||||
return None
|
||||
row = {"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label}
|
||||
if end is not None:
|
||||
row["end"] = end.replace(second=0, microsecond=0).isoformat()
|
||||
return row
|
||||
|
||||
|
||||
def sunrise_timeline(blue_at: datetime, blue_end_at: datetime, peak_at: datetime | None, sun_at: datetime, golden_end_at: datetime) -> list[dict]:
|
||||
"""블루아워(범위) → 노을 피크 → 해 뜸 → 골든아워(범위). 분 아래는 버린다."""
|
||||
rows = [_row("blue", "블루아워", blue_at, blue_end_at), _row("peak", "노을 피크", peak_at), _row("sun", "해 떠요", sun_at),
|
||||
_row("golden", "골든아워", sun_at, golden_end_at)]
|
||||
return [r for r in rows if r]
|
||||
|
||||
|
||||
def sunset_timeline(golden_at: datetime, sun_at: datetime, peak_at: datetime | None, blue_at: datetime, blue_end_at: datetime) -> list[dict]:
|
||||
"""골든아워 시작 → 해 짐(골든아워 끝) → 노을 피크 → 블루아워(범위). 분 아래는 버린다."""
|
||||
rows = [_row("golden", "골든아워", golden_at), _row("sun", "해 져요", sun_at), _row("peak", "노을 피크", peak_at),
|
||||
_row("blue", "블루아워", blue_at, blue_end_at)]
|
||||
return [r for r in rows if r]
|
||||
|
||||
@@ -4,6 +4,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
_SUN_ALTITUDE = -0.833
|
||||
_CIVIL_ALTITUDE = -6.0
|
||||
_BLUE_ALTITUDE = -4.0 # 블루아워: 해 고도 -4° ~ -6°
|
||||
_GOLDEN_ALTITUDE = 6.0
|
||||
|
||||
|
||||
@@ -16,6 +17,9 @@ class SunTimes:
|
||||
dawn_start_at: datetime
|
||||
sunrise_azimuth: int
|
||||
golden_start_at: datetime
|
||||
golden_end_at: datetime # 아침에 해 고도가 골든아워 높이까지 올라오는 때
|
||||
blue_start_at: datetime # 저녁 블루아워 시작 (해 고도 -4°)
|
||||
blue_end_morning_at: datetime # 아침 블루아워 끝 (해 고도 -4°)
|
||||
|
||||
|
||||
def _solar(d: date, lon: float) -> tuple[float, float]:
|
||||
@@ -44,6 +48,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
h_sun = _hour_angle(lat, decl, _SUN_ALTITUDE) * 4
|
||||
h_civil = _hour_angle(lat, decl, _CIVIL_ALTITUDE) * 4
|
||||
h_golden = _hour_angle(lat, decl, _GOLDEN_ALTITUDE) * 4
|
||||
h_blue = _hour_angle(lat, decl, _BLUE_ALTITUDE) * 4
|
||||
phi, dl = math.radians(lat), math.radians(decl)
|
||||
azimuth = math.degrees(math.acos(max(-1.0, min(1.0, math.sin(dl) / math.cos(phi)))))
|
||||
return SunTimes(
|
||||
@@ -54,4 +59,7 @@ def sun_times(d: date, lat: float, lon: float) -> SunTimes:
|
||||
dawn_start_at=at(noon_min - h_civil),
|
||||
sunrise_azimuth=round(azimuth),
|
||||
golden_start_at=at(noon_min + h_golden),
|
||||
golden_end_at=at(noon_min - h_golden),
|
||||
blue_start_at=at(noon_min + h_blue),
|
||||
blue_end_morning_at=at(noon_min - h_blue),
|
||||
)
|
||||
Vendored
+5
-3
@@ -11,7 +11,9 @@ VILAGE_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilag
|
||||
ULTRA_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst"
|
||||
WARNING_URL = "https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd"
|
||||
_SKY = {"1": Sky.CLEAR, "3": Sky.PARTLY, "4": Sky.CLOUDY}
|
||||
_PTY = {"0": RainType.NONE, "1": RainType.RAIN, "2": RainType.SLEET, "3": RainType.SNOW, "4": RainType.SHOWER}
|
||||
# 단기예보 0~4, 초단기예보는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림이 더 있다
|
||||
_PTY = {"0": RainType.NONE, "1": RainType.RAIN, "2": RainType.SLEET, "3": RainType.SNOW, "4": RainType.SHOWER,
|
||||
"5": RainType.RAIN, "6": RainType.SLEET, "7": RainType.SNOW}
|
||||
_REQUIRED = ("TMP", "SKY", "PTY", "POP", "REH")
|
||||
|
||||
|
||||
@@ -77,13 +79,13 @@ def day_start_base(day: date) -> datetime:
|
||||
|
||||
|
||||
def parse_ultra(items: list[dict]) -> list[dict]:
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온."""
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온·낙뢰(LGT, 0 이면 없음)."""
|
||||
by_time: dict[datetime, dict[str, str]] = {}
|
||||
for it in items:
|
||||
at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST)
|
||||
by_time.setdefault(at, {})[it["category"]] = it["fcstValue"]
|
||||
return [
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"])}
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"]), "lightning": parse_amount(v.get("LGT", "")) > 0}
|
||||
for at, v in sorted(by_time.items())
|
||||
if "PTY" in v and "T1H" in v
|
||||
]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
@@ -11,9 +12,9 @@ from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
@@ -21,20 +22,20 @@ from crud.season_crud import SeasonCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide,
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
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, hero_stats, uv_label
|
||||
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.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
from services.sky_service import SkyService, SkyView, day_verdict
|
||||
from services.sky_service import outlook as sky_outlook
|
||||
from services.weather_service import TodayWeather, WeatherService
|
||||
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
@@ -76,19 +77,19 @@ def sido_of(region_code: str) -> str:
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위.
|
||||
# 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
_FEED_TTL_MAX = 3600
|
||||
_PARTIAL_TTL = 60
|
||||
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
|
||||
_NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
_RAIN_PROB = 40
|
||||
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
|
||||
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
|
||||
@@ -118,6 +119,7 @@ _AIR_LINE = {
|
||||
AirGrade.BAD: ("공기가 탁해요,\n마스크 챙겨요", "😷 마스크 챙겨!"),
|
||||
AirGrade.VERY_BAD: ("공기가 많이 탁해요,\n바깥은 짧게", "😷 오늘은 실내로!"),
|
||||
}
|
||||
_AIR_RAIN_LINE = ("공기는 맑은데 비가 와요,\n창문은 닫아 둬요", "☔ 창문은 닫아 둬!") # 맑음·보통인데 지금~2시간 안에 비
|
||||
_AIR_ADVICE = {
|
||||
AirGrade.BAD: "KF80 마스크 쓰고, 오래 뛰는 바깥 운동은 줄여요",
|
||||
AirGrade.VERY_BAD: "외출은 줄이고 창문은 닫아 둬요. 나가면 KF94 마스크",
|
||||
@@ -131,22 +133,20 @@ def _pick(articles: list[Article], day: date) -> Optional[Article]:
|
||||
return articles[day.toordinal() % len(articles)] if articles else None
|
||||
|
||||
|
||||
def _discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float]) -> HeroInput:
|
||||
def _hero_input(
|
||||
now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str],
|
||||
) -> HeroInput:
|
||||
temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else []
|
||||
rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else []
|
||||
ahead = [x for x in today.slots if x.row and x.at > now] if today else []
|
||||
later = next((x.at for x in ahead if x.row.rain_type != RainType.NONE.value or x.row.rain_prob >= _HERO_RAIN_PROB), None)
|
||||
return HeroInput(
|
||||
now=now, night=slot in ("evening", "night"), rain_at=rainy[0].at if rainy else None,
|
||||
now=now, night=slot in ("evening", "night"), after_dark=slot == "night", rain_at=rainy[0].at if rainy else None,
|
||||
rain_later_at=later, today_known=bool(ahead),
|
||||
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
||||
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
moon=phase_name(_tonight(now)),
|
||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
|
||||
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -154,23 +154,14 @@ def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신·정각(지금 구간이 줄어듦) 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
|
||||
now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
nxt = min(c for c in changes if c > now)
|
||||
@@ -231,7 +222,8 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
if slot == "night":
|
||||
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
|
||||
events = pool.get(PostType.EVENT, [])
|
||||
gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True)
|
||||
front = range(1, max(1, len(rest) // 2 + 1))
|
||||
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
|
||||
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
|
||||
rest.insert(gap, e)
|
||||
return head + rest
|
||||
@@ -247,7 +239,8 @@ def _by_position(posts: list[Post]) -> list[Post]:
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
|
||||
slots=i.slots, slot_ranks=i.slot_ranks)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
@@ -333,6 +326,9 @@ class FeedService:
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||
# 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다
|
||||
if not res.bands.top5:
|
||||
return ErrorType.SUCCESS, res
|
||||
try:
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||
except RedisError as e:
|
||||
@@ -371,7 +367,7 @@ class FeedService:
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
for p in posts or []:
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
@@ -383,15 +379,16 @@ class FeedService:
|
||||
for p, item in zip(gak_posts, gak):
|
||||
cards.append(self._gak(p, item))
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
items = board.items if board else []
|
||||
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
|
||||
items = [i for i in board.items if i.in_season] if board else []
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour)),
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
top5=[_top(i) for i in board.ranked[:5]] if board else [],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
@@ -427,25 +424,29 @@ class FeedService:
|
||||
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
|
||||
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
|
||||
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
|
||||
return None
|
||||
return float(rows[0].uv_index)
|
||||
"""지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour))
|
||||
rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None, moon: Optional[tuple[MoonNight, str]] = None) -> Hero:
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
bubble = f"지금은 {top.definition.name}!" if top.score.score >= 70 else "지금은 쉬어 가요"
|
||||
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
||||
return Hero(
|
||||
now_at=now, sky_mode=_SKY_MODE[slot],
|
||||
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None,
|
||||
humidity=cur.humidity if cur else None,
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
|
||||
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv))],
|
||||
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
|
||||
top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
|
||||
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -456,7 +457,7 @@ class FeedService:
|
||||
def _gak(self, p: Post, i: IndexItem) -> 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)],
|
||||
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))],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
@@ -503,7 +504,8 @@ class FeedService:
|
||||
for label, w in zip(("이번 주말", "다음 주말"), weekends):
|
||||
f = forecast(w)
|
||||
slides.append(WeekSlide(kind="week", eyebrow=f"{label} · {day_range(w[0].day, w[-1].day)}", line=f.line, tip=f.tip, days=[
|
||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob)
|
||||
WeekDay(day=d.day, weekday=d.weekday, icon=d.icon, text=d.headline, temp_min_c=d.temp_min_c, temp_max_c=d.temp_max_c, rain_prob=d.rain_prob,
|
||||
gaks=_day_gaks(c.board, d.day))
|
||||
for d in w
|
||||
]))
|
||||
first = forecast(weekends[0])
|
||||
@@ -521,39 +523,42 @@ class FeedService:
|
||||
return None
|
||||
|
||||
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
||||
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·밝기와 다음 보름. 피드 아래쪽에 둔다."""
|
||||
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·잘 보이는지와 다음 보름. 피드 아래쪽에 둔다."""
|
||||
tonight = _tonight(c.now)
|
||||
m, view = _moon_view(c.region, c.now, c.hourly)
|
||||
start = tonight.replace(hour=12)
|
||||
full, new = nearest(tonight, True).astimezone(KST), nearest(tonight, False).astimezone(KST)
|
||||
at, is_full = (full, True) if start <= full < start + timedelta(days=1) else (new, False) if start <= new < start + timedelta(days=1) else (None, False)
|
||||
row = next((h for h in c.hourly if h.forecast_at.astimezone(KST) == tonight), None)
|
||||
sky = Sky(row.sky) if row is not None else None
|
||||
rows = [Row(label="밤 하늘", value=_MOON_SKY[sky])] if sky is not None else []
|
||||
rows = [Row(label=label, value=_clock_word(t)) for label, t in (("달 뜸", m.rise_at), ("달 짐", m.set_at)) if t is not None]
|
||||
eyebrow = f"오늘 밤 달 · {c.region.short_name}"
|
||||
if at is None:
|
||||
name, pct = phase_name(tonight), round(illumination(tonight) * 100)
|
||||
name = m.name
|
||||
nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full
|
||||
nxt = nxt.astimezone(KST)
|
||||
waxing = name in ("초승달", "상현달", "차오르는 달")
|
||||
caption = ("구름이 많아 달은 숨바꼭질해요." if sky is Sky.CLOUDY
|
||||
# 본문(잘 보이는지)과 어긋나지 않게: 안 보이는 밤·흐린 밤은 그 이유에 맞춰서
|
||||
caption = ("달이 없는 만큼 별은 더 잘 보여요 ✨" if "안 보여요" in view
|
||||
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밝기 {pct}%", icon="moon",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon",
|
||||
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}에 가장 둥글어요"
|
||||
caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY else "소원 빌기 딱 좋은 밤이에요 🌕"
|
||||
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="100%"), *rows])],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", 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=[Row(label="달 밝기", value="0%"), *rows])],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=rows)],
|
||||
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
|
||||
|
||||
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
|
||||
@@ -630,14 +635,13 @@ class FeedService:
|
||||
return None
|
||||
label = uv_label(top)
|
||||
at = peak.forecast_at.astimezone(KST)
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
|
||||
high = top >= UV_HIGH
|
||||
if high:
|
||||
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
|
||||
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
|
||||
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv]
|
||||
when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵"
|
||||
todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요"
|
||||
line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}"
|
||||
return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
||||
share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
@@ -649,39 +653,39 @@ class FeedService:
|
||||
return None
|
||||
worst = max(g for _, _, g in values)
|
||||
label = AIR_GRADE_LABEL[worst]
|
||||
rows = [Row(label=name, value=f"{v}㎍/㎥ · {AIR_GRADE_LABEL[g]}") for name, v, g in values]
|
||||
rows = [Row(label=name, value=AIR_GRADE_LABEL[g]) for name, _, g in values]
|
||||
if worst in _AIR_ADVICE:
|
||||
rows.append(Row(label="이렇게 해요", value=_AIR_ADVICE[worst]))
|
||||
line, tail = _AIR_LINE[worst]
|
||||
icon = "vent" if worst <= AirGrade.NORMAL else "cloud"
|
||||
raining = worst <= AirGrade.NORMAL and c.now_w.will_rain_2h
|
||||
line, tail = _AIR_RAIN_LINE if raining else _AIR_LINE[worst]
|
||||
icon = "umbrella" if raining else "vent" if worst <= AirGrade.NORMAL else "cloud"
|
||||
return PostData(**base, title=f"미세먼지 {label}", icon=icon, caption=f"{air.station_name} 측정소 · {air.measured_at.astimezone(KST).hour}시 기준",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"지금 공기 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
||||
|
||||
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 하늘 상황으로 말하고, '쉬어요'면 한 줄 카드."""
|
||||
after = c.now >= c.sunset_at
|
||||
target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset
|
||||
if target is None:
|
||||
"""노을 탭 결론과 같은 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을. 노을 탭 히어로와 같은 문장, 안 볼 만한 날은 한 줄 카드."""
|
||||
plan = c.sky.plan
|
||||
if plan is None:
|
||||
return None
|
||||
when = "내일" if after else "오늘"
|
||||
target, when, rise = plan.target, plan.when, plan.kind is SkyType.SUNRISE
|
||||
word, icon = ("일출", "sun") if rise else ("노을", "sunset")
|
||||
sit = SkySituation(target.situation) if target.situation else None
|
||||
line = SITUATION_LINE[sit] if sit else GRADE_LABEL[SkyGrade(target.grade)]
|
||||
better = sky_outlook(target, c.sky.days, c.now.date())
|
||||
sun = next((b for b in target.best_times if b["kind"] == "sun"), target.best_times[0])
|
||||
sun_at = datetime.fromisoformat(sun["at"]).astimezone(KST)
|
||||
if day_verdict(target) == "rest":
|
||||
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=f"{line}." + (f" {better}" if better else ""),
|
||||
slides=[], share_messages=[f"{when} 노을은 쉬어요, {line}"])
|
||||
line = plan.situation_label or "" # 보이는 날만 그날 하늘 한 줄
|
||||
better = plan.outlook
|
||||
if day_verdict(target) == "rest" or SkyGrade(target.grade) is SkyGrade.GRAY: # 거의 안 보이는 날은 한 줄 카드
|
||||
return PostData(**base, size="line", title=plan.title, icon=icon, caption=" ".join(filter(None, [line and f"{line}.", better])),
|
||||
slides=[], share_messages=[plan.title])
|
||||
cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"]
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=line, score=target.score,
|
||||
grade_label=line, cuts=cuts, situation=sit)]
|
||||
if c.sky.spots:
|
||||
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} {word} · {c.region.name}", line=line, score=target.score,
|
||||
grade_label=GRADE_LABEL[SkyGrade(target.grade)], cuts=cuts, situation=sit,
|
||||
headline=sky_title(SkyGrade(target.grade), plan.kind, None, plan.best_at), peak_at=plan.best_at)]
|
||||
if c.sky.spots and not rise:
|
||||
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {compass(c.sky.sunset_azimuth)}쪽", icon="sunset",
|
||||
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{compass(x.direction)} {x.distance_km}km", place=x.spot.name) for n, x in enumerate(c.sky.spots)]))
|
||||
caption = better or "보통 해 진 뒤 10~20분이 가장 붉어요."
|
||||
return PostData(**base, title=f"{when} 노을 · {line}", icon="sunset", caption=caption,
|
||||
slides=slides, share_messages=[f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요"])
|
||||
caption = better or ("보통 해 뜨기 10~20분 전이 가장 붉어요." if rise else "보통 해 진 뒤 10~20분이 가장 붉어요.")
|
||||
share = f"{plan.title} {'🌅' if rise else '🌇'}"
|
||||
return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share])
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
tomorrow = c.now.date() + timedelta(days=1)
|
||||
@@ -720,9 +724,32 @@ 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:
|
||||
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간)."""
|
||||
band = _band_sentence(i.definition.sentences, i.score.score)
|
||||
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
if nxt is not None:
|
||||
diff = nxt.score - i.score.score
|
||||
@@ -731,7 +758,7 @@ def _gak_caption(i: IndexItem) -> str:
|
||||
else:
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
return f"{band} {tail}" if band else tail
|
||||
return tail
|
||||
|
||||
|
||||
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
|
||||
@@ -757,7 +784,29 @@ def _event_caption(e: EventItem) -> str:
|
||||
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
_MOON_SKY = {Sky.CLEAR: "맑음, 잘 보여요", Sky.PARTLY: "구름 조금, 사이사이 보여요", Sky.CLOUDY: "흐림, 가려질 수 있어요"}
|
||||
_CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
|
||||
|
||||
|
||||
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
|
||||
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
|
||||
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
|
||||
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
|
||||
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
|
||||
|
||||
|
||||
def _moon_view(region: Region, now: datetime, hourly: list[WeatherHourly]) -> tuple[MoonNight, str]:
|
||||
"""오늘 밤 달과 잘 보이는지 한 마디. 구름은 달이 떠 있는 시각의 시간별 예보 하늘로 본다."""
|
||||
day = feed_day(now.astimezone(KST))
|
||||
m = night(day, float(region.lat), float(region.lon))
|
||||
start = kst_midnight(day)
|
||||
by_at = {h.forecast_at: h for h in hourly}
|
||||
skies = [_CLOUDY[Sky(r.sky)] for h in m.up_hours if (r := by_at.get(start + timedelta(hours=h))) is not None]
|
||||
return m, view_line(m, sum(skies) / len(skies) if skies else None)
|
||||
|
||||
|
||||
def _clock_word(at: datetime) -> str:
|
||||
h = at.astimezone(KST).hour
|
||||
return f"{'새벽' if h < 6 else '밤' if h >= 21 or h == 0 else '저녁'} {h % 12 or 12}시 {at.astimezone(KST).minute:02d}분"
|
||||
|
||||
|
||||
def _tonight(now: datetime) -> datetime:
|
||||
|
||||
@@ -10,10 +10,11 @@ from services.air_service import GRADE_LABEL
|
||||
Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
|
||||
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
MUGGY = 75
|
||||
SHOWN = 2
|
||||
SHOWN = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -38,16 +39,44 @@ class HeroInput:
|
||||
temp_max: Optional[float] = None
|
||||
temp: Optional[float] = None
|
||||
feels: Optional[float] = None
|
||||
discomfort: Optional[int] = None
|
||||
moon: Optional[str] = None
|
||||
humidity: Optional[int] = None
|
||||
discomfort: Optional[int] = None
|
||||
after_dark: bool = False # 밤 구간(일몰 1시간 뒤~). night 는 저녁 구간까지 포함한다
|
||||
|
||||
|
||||
_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험")
|
||||
|
||||
|
||||
def uv_level(uv: float) -> int:
|
||||
"""기상청 자외선 단계 1 낮음 ~ 5 위험."""
|
||||
return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5
|
||||
|
||||
|
||||
def uv_label(uv: float) -> str:
|
||||
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
||||
return _UV_LABELS[uv_level(uv) - 1]
|
||||
|
||||
|
||||
def _discomfort_label(v: int) -> str:
|
||||
return "보통" if v < 75 else "높음" if v < 80 else "매우 높음"
|
||||
def discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def humidity_label(h: int) -> str:
|
||||
return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함"
|
||||
|
||||
|
||||
def hero_status(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
out: list[HeroStatItem] = []
|
||||
if x.humidity is not None:
|
||||
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
|
||||
if x.discomfort is not None:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||
if not x.after_dark and x.uv is not None:
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||
if x.air is not None:
|
||||
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
|
||||
return out
|
||||
|
||||
|
||||
def _rain_value(now: datetime, at: datetime) -> str:
|
||||
@@ -55,7 +84,7 @@ def _rain_value(now: datetime, at: datetime) -> str:
|
||||
|
||||
|
||||
def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 두 칸. 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
||||
"""히어로 상황 칸 (습도·불쾌지수는 늘 따로 보인다). 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
||||
alerts: list[HeroStatItem] = []
|
||||
if x.rain_at is not None:
|
||||
alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain"))
|
||||
@@ -69,8 +98,6 @@ def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
||||
alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷"))
|
||||
if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C:
|
||||
alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀"))
|
||||
if x.discomfort is not None and x.discomfort >= MUGGY:
|
||||
alerts.append(HeroStatItem("muggy", "muggy", "불쾌지수", f"{x.discomfort} · {_discomfort_label(x.discomfort)}", "warn"))
|
||||
|
||||
# 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다
|
||||
fills: list[HeroStatItem] = []
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
@@ -9,42 +9,71 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, now_kst
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.moon import night, up_ratio, view_line
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
|
||||
|
||||
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
||||
DAYS = 3
|
||||
_LOOKAHEAD_HOURS = (9, 18)
|
||||
_STARS_HOURS = range(21, 26) # 달빛이 별보기를 가리는지 보는 시각 (별보기각 시간대)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
||||
# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도.
|
||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=30, weight_wind=15, weight_humidity=0, weight_air=15, weight_time=0,
|
||||
weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"},
|
||||
"wind": {"type": "calm", "ok": 2, "limit": 10}, "humidity": {"type": "range", "lo": 40, "hi": 60, "best": 50},
|
||||
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 9, "to": 21}],
|
||||
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
|
||||
|
||||
SEASONS = ("겨울", "봄", "여름", "가을")
|
||||
|
||||
|
||||
def season_of(month: int) -> str:
|
||||
"""봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2."""
|
||||
return SEASONS[month % 12 // 3]
|
||||
|
||||
|
||||
def in_season(defn, month: int) -> bool:
|
||||
"""제철 달이 없으면 일 년 내내."""
|
||||
months = getattr(defn, "months", None)
|
||||
return not months or month in months
|
||||
|
||||
|
||||
def season_badge(defn, month: int) -> Optional[str]:
|
||||
"""제철이 정해진 각이 지금 제철이면 그 계절 이름. 일 년 내내인 각은 없음."""
|
||||
months = getattr(defn, "months", None)
|
||||
return season_of(month) if months and month in months else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class IndexItem:
|
||||
definition: IndexDefinition
|
||||
score: IndexScore
|
||||
rank: int
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
|
||||
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -53,6 +82,12 @@ class IndexBoard:
|
||||
day: date
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
weather_slots: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||
return [i for i in self.items if i.active]
|
||||
|
||||
|
||||
def _hour(r: WeatherHourly) -> Hour:
|
||||
@@ -79,11 +114,12 @@ def slot_label(day: date, today: date) -> str:
|
||||
|
||||
|
||||
def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각."""
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각. around 는 일몰·일출 시각 ±hours."""
|
||||
out = []
|
||||
for w in defn.windows:
|
||||
if w.get("around") == "sunset":
|
||||
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
|
||||
if w.get("around") in ("sunset", "sunrise"):
|
||||
sun = sun_times(day, float(region.lat), float(region.lon))
|
||||
h = (sun.sunset_at if w["around"] == "sunset" else sun.sunrise_at).astimezone(KST).hour
|
||||
out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)))
|
||||
else:
|
||||
out.append(list(range(w["from"], w["to"])))
|
||||
@@ -118,13 +154,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
only: Optional[set[int]] = None,
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).
|
||||
only 가 있으면 그 시각만 남긴다."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
if only is not None:
|
||||
hours = [h for h in hours if h in only]
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
@@ -135,6 +175,71 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
return EARLY if now.hour < NIGHT_END_HOUR else slot_of(now, sunset_at)
|
||||
|
||||
|
||||
def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
|
||||
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
return {k: shown[k] for k in SLOTS if k in shown}
|
||||
|
||||
|
||||
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
|
||||
"""그날 비·눈 오는 시각(0~23)."""
|
||||
start = kst_midnight(day)
|
||||
return frozenset(h for h in range(24) if (r := by_at.get(start + timedelta(hours=h))) is not None and r.rain_type != RainType.NONE.value)
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
now: Optional[datetime] = None,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
|
||||
hours_by_slot = slot_hours(day, sunset_at)
|
||||
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
|
||||
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _trim_passed(hours_by_slot: dict[str, set[int]], day: date, sunset_at: datetime, now: datetime) -> Optional[str]:
|
||||
"""지금 구간에서 이미 지난 시각을 뺀다(지난 단기예보 비가 지금 점수에 남지 않게). 지금 구간 이름, 오늘이 아니면 None."""
|
||||
hour = int((now - kst_midnight(day)).total_seconds() // 3600)
|
||||
cur = next((k for k, hours in hours_by_slot.items() if hour in hours), None)
|
||||
if cur is not None:
|
||||
hours_by_slot[cur] = {h for h in hours_by_slot[cur] if h >= hour}
|
||||
return cur
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
|
||||
def _with_slot(row: IndexScore, data: dict) -> IndexScore:
|
||||
"""저장된 하루 점수 행을 구간 점수로 바꾼 사본 (DB에 붙지 않음)."""
|
||||
out = IndexScore(**{c.key: getattr(row, c.key) for c in IndexScore.__table__.columns})
|
||||
out.score, out.summary, out.zero_reason, out.notes = data["score"], data["summary"], data["zero_reason"], data["notes"]
|
||||
for a in AXES:
|
||||
setattr(out, f"{a}_score", data["factors"].get(a, 0))
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
@@ -200,31 +305,101 @@ class IndexService:
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
err, weather_score = await self.ensure(region, now)
|
||||
err, weather_parts = await self.ensure(region, now)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||
slots = slot_days(today)
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, slots[-1]))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True)
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key],
|
||||
)
|
||||
for i, d in enumerate(ranked)
|
||||
]
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
month = today.month
|
||||
out_season = [d for d in defs if not in_season(d, month)]
|
||||
defs = [d for d in defs if in_season(d, month)]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
row = by_key.get((d.index_id, today))
|
||||
if row is None:
|
||||
continue
|
||||
if not row.slots:
|
||||
now_score[d.index_id] = row
|
||||
elif cur in row.slots:
|
||||
now_score[d.index_id] = _with_slot(row, row.slots[cur])
|
||||
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
|
||||
)
|
||||
for d in off:
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
|
||||
))
|
||||
for k in SLOTS:
|
||||
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||
for n, i in enumerate(in_slot):
|
||||
i.slot_ranks[k] = n + 1
|
||||
# 제철이 아닌 각은 구간 순위 없이 맨 끝에
|
||||
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings = await asyncio.gather(
|
||||
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
|
||||
"""공식 각이 아닌 정의(내 각)들을 그 동네 오늘 아침·낮·저녁·밤으로 계산한다. (지금 구간, 정의마다 구간별 결과)"""
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if not rows:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
ctx = Context(
|
||||
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
|
||||
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||
)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
cur = current_slot(now, sunset_at)
|
||||
out = []
|
||||
for d in defns:
|
||||
parts = slot_results(d, today, region, by_at, {}, ctx, sunset_at, now)
|
||||
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
|
||||
return ErrorType.SUCCESS, (shown_slot(cur), out)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings, ultra = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||
self.warning_service.for_region(region, now),
|
||||
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
|
||||
)
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
@@ -243,45 +418,55 @@ class IndexService:
|
||||
)
|
||||
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
base_ctx = dict(
|
||||
pm25=air.pm25 if air else None,
|
||||
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
if by_om:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
if ultra is not None:
|
||||
inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY)
|
||||
# 지금 구간은 지금 시각부터 보므로 정각마다 다시 계산
|
||||
inputs_at = max(inputs_at, now.replace(minute=0, second=0, microsecond=0))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()):
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_parts
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||
_, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today))
|
||||
sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value}
|
||||
sunrise = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNRISE.value}
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
out = []
|
||||
for day in days:
|
||||
m = night(day, float(region.lat), float(region.lon))
|
||||
ctx = Context(
|
||||
day=day, is_holiday=day in (holidays or set()), moon=illumination(datetime.combine(day, time(23), tzinfo=KST)),
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
||||
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at, now) if day == today else {}
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
"estimated": result.estimated, "computed_at": now,
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
return err, weather_parts
|
||||
@@ -0,0 +1,77 @@
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType
|
||||
from crud.my_gak_crud import MyGakCRUD
|
||||
from services.calc.day_slot import SLOTS
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition
|
||||
from services.index_service import IndexService
|
||||
|
||||
# 한 사람이 만들 수 있는 내 각 수
|
||||
MAX_PER_USER = 20
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
|
||||
|
||||
|
||||
def gak_name(name: str) -> Optional[str]:
|
||||
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
|
||||
name = " ".join(name.split())
|
||||
if not name or _LINK.search(name):
|
||||
return None
|
||||
name = name if name.endswith("각") else f"{name}각"
|
||||
return name if len(name) <= 12 else None
|
||||
|
||||
|
||||
def my_rule(rule: dict) -> MyRule:
|
||||
return MyRule(
|
||||
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
|
||||
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
|
||||
)
|
||||
|
||||
|
||||
class MyGakService:
|
||||
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
|
||||
self.crud, self.index = crud, index
|
||||
|
||||
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
|
||||
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]]:
|
||||
name = gak_name(name)
|
||||
if name is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
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))
|
||||
|
||||
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))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
|
||||
|
||||
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
|
||||
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
|
||||
mine = [my_rule(r) for r in rules]
|
||||
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
|
||||
if err is not ErrorType.SUCCESS or got is None:
|
||||
return err, None
|
||||
now_slot, parts = got
|
||||
out = []
|
||||
for r, p in zip(mine, parts):
|
||||
picked = {k: v for k, v in p.items() if k in r.slots}
|
||||
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
|
||||
res = picked.get(key) if key else None
|
||||
out.append({
|
||||
"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 [],
|
||||
})
|
||||
return ErrorType.SUCCESS, (now_slot, out)
|
||||
@@ -3,38 +3,23 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import AirQuality, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.text import hour_label
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import fetch_ultra, parse_ultra
|
||||
from services.warning_service import WarningItem, WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import RainHour, WeatherService, ultra_hours
|
||||
|
||||
_FETCH_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class CommuteRow:
|
||||
label: str
|
||||
@@ -56,6 +41,7 @@ class NowWeather:
|
||||
air: Optional[AirQuality]
|
||||
air_text: Optional[str]
|
||||
warnings: Optional[list[WarningItem]] = field(default=None)
|
||||
thunder_2h: bool = False
|
||||
|
||||
|
||||
def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]:
|
||||
@@ -139,27 +125,8 @@ class NowService:
|
||||
return ErrorType.SUCCESS, NowWeather(
|
||||
region=region, will_rain_2h=will_rain, rain_2h_text=rain_text, rain_hours=hours,
|
||||
tomorrow_text=tomorrow_text, tomorrow_rain_from=rain_from, commute=commute, air=air, air_text=air_text, warnings=warnings,
|
||||
thunder_2h=any(h.lightning for h in hours),
|
||||
)
|
||||
|
||||
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if cached:
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] == base.isoformat():
|
||||
return [RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"]) for h in data["hours"]]
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
return None
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
except _FETCH_ERRORS as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
return await ultra_hours(region, now)
|
||||
@@ -7,6 +7,7 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Comment, Post, User
|
||||
from common.enums import ErrorType
|
||||
from common.liker import Liker
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
|
||||
@@ -41,11 +42,11 @@ class ReactionService:
|
||||
return err
|
||||
return ErrorType.SUCCESS if post is not None else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_post(self, post_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
async def like_post(self, post_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
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, user.user_id, on))
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
|
||||
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
|
||||
err = await self._post_exists(post_id)
|
||||
@@ -60,6 +61,12 @@ class ReactionService:
|
||||
err, marks = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.my_marks(s, user.user_id, post_ids))
|
||||
return marks if err is ErrorType.SUCCESS else (set(), set())
|
||||
|
||||
async def anon_liked(self, ip_hash: str, post_ids: list[int]) -> set[int]:
|
||||
if not post_ids:
|
||||
return set()
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_posts(s, ip_hash, post_ids))
|
||||
return liked if err is ErrorType.SUCCESS else set()
|
||||
|
||||
async def counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
|
||||
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
|
||||
if not post_ids:
|
||||
@@ -71,13 +78,16 @@ class ReactionService:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
|
||||
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
|
||||
|
||||
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
ids = [c.comment_id for c, *_ in rows]
|
||||
if user is not None and rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, [c.comment_id for c, *_ in rows]))
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
|
||||
elif rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
|
||||
return ErrorType.SUCCESS, [
|
||||
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
|
||||
for c, n, ch, co, mo in rows
|
||||
@@ -99,8 +109,8 @@ class ReactionService:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_comment(self, comment_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, user.user_id, on))
|
||||
async def like_comment(self, comment_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, who, on))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||
@@ -0,0 +1,106 @@
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from html import escape
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from config.settings import settings
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import Res_Feed
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.feed_service import FeedService
|
||||
|
||||
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
at = at.astimezone(KST)
|
||||
h = at.hour % 12 or 12
|
||||
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||
|
||||
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def day_summary(rows: list[WeatherHourly]) -> str:
|
||||
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
if not rows:
|
||||
return ""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
|
||||
|
||||
|
||||
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
|
||||
parts = [day_summary(rows)] if rows else []
|
||||
h = feed.hero
|
||||
if h and h.temp_c is not None:
|
||||
status = "·".join(f"{s.label} {s.value}" for s in h.status)
|
||||
parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".")
|
||||
firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1]
|
||||
if firsts:
|
||||
parts.append(", ".join(firsts) + ".")
|
||||
if sunset_at:
|
||||
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
line = today_line(feed, rows, sunset_at)
|
||||
if not line:
|
||||
return template
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||
|
||||
|
||||
class SeoService:
|
||||
def __init__(
|
||||
self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)
|
||||
) -> None:
|
||||
self.feed, self.regions, self.weather = feed, regions, weather
|
||||
|
||||
async def template(self, path: str) -> Optional[str]:
|
||||
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
r = await client.get(f"{settings.frontend_internal_url}/{path}.html")
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[seo] template {path}: {e}")
|
||||
return None
|
||||
return r.text if r.status_code == 200 and _CODE.search(r.text) else None
|
||||
|
||||
async def page(self, path: str) -> tuple[ErrorType, Optional[str]]:
|
||||
template = await self.template(path)
|
||||
if template is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
code = _CODE.search(template).group(1)
|
||||
err, feed = await self.feed.feed(code)
|
||||
if err is not ErrorType.SUCCESS or feed is None:
|
||||
LOG.error(f"[seo] feed {code}: {err}")
|
||||
return ErrorType.SUCCESS, template
|
||||
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||
today = now_kst().date()
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(today)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
+104
-39
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
@@ -20,8 +20,8 @@ from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from services.calc.sky_score import (
|
||||
DISTANCES_KM, GRADE_LABEL, RAIN_BEFORE_HOURS, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Air, Layers, air_factor, best_times,
|
||||
confidence, grade, mean_layers, reason, score, situation, sunset_timeline, verdict,
|
||||
DISTANCES_KM, GRADE_LABEL, RAIN_BEFORE_HOURS, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Air, Layers, air_factor, best_times,
|
||||
GRADE_RANK, air_note, confidence, grade, mean_layers, plain_line, reason, sky_title, score, situation, sunrise_timeline, sunset_timeline, verdict,
|
||||
)
|
||||
from services.calc.sun import SunTimes, sun_times
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
|
||||
@@ -31,6 +31,7 @@ DAYS = 3
|
||||
SPOT_RADIUS_KM = EVENT_RADIUS_KM
|
||||
SPOT_LIMIT = 3
|
||||
_MARKER_TTL = 24 * 3600
|
||||
OPEN_WEST_KM = 20 # 이 안에 서쪽이 트인 명소가 있으면 노을 가산 (부안 채석강·진도 세방낙조가 구 중심에서 10km 넘게 떨어져 있어 20km)
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@@ -43,7 +44,10 @@ class Spot:
|
||||
|
||||
@dataclass
|
||||
class SkyPlan:
|
||||
"""노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로."""
|
||||
"""노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로. 다음에 오는 일출 또는 노을."""
|
||||
kind: SkyType
|
||||
title: str # 하늘이 어떻게 보일지 한 문장 (히어로 제목)
|
||||
target: SkyScore
|
||||
day: date
|
||||
when: str
|
||||
verdict: str
|
||||
@@ -69,6 +73,7 @@ class SkyView:
|
||||
days: list[SkyScore]
|
||||
spots: list[Spot]
|
||||
plan: Optional[SkyPlan] = None
|
||||
plans: list[SkyPlan] = field(default_factory=list) # plan 과 같은 종류(노을·일출)로 아직 안 끝난 날 최대 3일. 날짜 타일용
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -98,44 +103,89 @@ def _word(d: date, today: date) -> str:
|
||||
return _DAY_WORD[i] if 0 <= i < len(_DAY_WORD) else f"{d.month}.{d.day}"
|
||||
|
||||
|
||||
def _subject(word: str) -> str:
|
||||
"""받침 있으면 '이', 없으면 '가'. 오늘이 · 모레가"""
|
||||
last = ord(word[-1]) - 0xAC00
|
||||
return f"{word}{'이' if 0 <= last < 11172 and last % 28 else '가'}"
|
||||
|
||||
|
||||
def day_verdict(x: SkyScore) -> str:
|
||||
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로."""
|
||||
return SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
|
||||
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로. 공기가 뿌예 점수가 크게 깎였으면 한 단계 낮춘다."""
|
||||
v = SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
|
||||
if air_note(getattr(x, "air", None)) is not None and VERDICT_RANK[v] > 0:
|
||||
v = next(k for k, r in VERDICT_RANK.items() if r == VERDICT_RANK[v] - 1)
|
||||
return v
|
||||
|
||||
|
||||
def peak_of(x: SkyScore) -> Optional[datetime]:
|
||||
peak = next((b for b in x.best_times or [] if b["kind"] == "peak"), None)
|
||||
return datetime.fromisoformat(peak["at"]) if peak else None
|
||||
|
||||
|
||||
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
|
||||
"""뒤의 날 중 결론이 더 좋은 날이 있을 때만 한 줄. 없으면 빈 문자열."""
|
||||
later = [x for x in days if x.score_date > target.score_date and VERDICT_RANK[day_verdict(x)] > VERDICT_RANK[day_verdict(target)]]
|
||||
"""뒤의 날 중 점수 등급이 더 높은 날이 있을 때만 그날 문장 (18:07, 모레 노을이 은은하게 물들어요). 없으면 빈 문자열."""
|
||||
rank = lambda x: GRADE_RANK[SkyGrade(x.grade)] # noqa: E731
|
||||
later = [x for x in days if x.score_date > target.score_date and x.grade is not None and rank(x) > rank(target)]
|
||||
if not later:
|
||||
return ""
|
||||
best = max(later, key=lambda x: (VERDICT_RANK[day_verdict(x)], x.score))
|
||||
line = SITUATION_LINE[SkySituation(best.situation)] if best.situation else VERDICT_LINE[day_verdict(best)]
|
||||
return f"{_subject(_word(best.score_date, today))} 더 나아요 · {line}"
|
||||
best = max(later, key=lambda x: (rank(x), x.score))
|
||||
kind = SkyType.SUNRISE if best.sky_type == SkyType.SUNRISE.value else SkyType.SUNSET
|
||||
return sky_title(SkyGrade(best.grade), kind, _word(best.score_date, today), peak_of(best))
|
||||
|
||||
|
||||
def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date) -> SkyPlan:
|
||||
def build_plan(
|
||||
target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date, kind: SkyType = SkyType.SUNSET,
|
||||
) -> SkyPlan:
|
||||
"""days 는 target 과 같은 종류(일출·노을)만."""
|
||||
v = day_verdict(target)
|
||||
rise = kind is SkyType.SUNRISE
|
||||
when = _word(target.score_date, today)
|
||||
peak = next((b for b in target.best_times if b["kind"] == "peak"), None)
|
||||
peak_at = datetime.fromisoformat(peak["at"]) if peak else None
|
||||
return SkyPlan(
|
||||
kind=kind, target=target,
|
||||
title=sky_title(SkyGrade(target.grade), kind, when, peak_at),
|
||||
day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v],
|
||||
reason=reason(*layers) if layers else _FALLBACK_REASON[v],
|
||||
reason=". ".join(filter(None, [reason(*layers, kind) if layers else _FALLBACK_REASON[v], air_note(target.air)])),
|
||||
score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
|
||||
situation_label=SITUATION_LINE[SkySituation(target.situation)] if target.situation else None,
|
||||
situation_label=plain_line(SkyGrade(target.grade), SkySituation(target.situation) if target.situation else None, target.air, kind),
|
||||
models_total=target.models_total, models_agree=target.models_agree,
|
||||
best_at=peak_at, spot=spots[0] if spots and v != "rest" else None,
|
||||
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), None, st.dusk_end_at.astimezone(KST)),
|
||||
best_at=peak_at, spot=spots[0] if spots and v != "rest" and not rise else None,
|
||||
timeline=(
|
||||
sunrise_timeline(st.dawn_start_at.astimezone(KST), st.blue_end_morning_at.astimezone(KST), peak_at, st.sunrise_at.astimezone(KST), st.golden_end_at.astimezone(KST))
|
||||
if rise
|
||||
else sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), peak_at, st.blue_start_at.astimezone(KST), st.dusk_end_at.astimezone(KST))
|
||||
),
|
||||
outlook=outlook(target, days, today),
|
||||
)
|
||||
|
||||
|
||||
def next_event(sunsets: list[SkyScore], sunrises: list[SkyScore], lat: float, lon: float, now: datetime) -> Optional[tuple[SkyType, SkyScore, SunTimes]]:
|
||||
"""가장 먼저 끝나지 않은 일출(해 뜰 때까지) 또는 노을(블루아워 끝까지)."""
|
||||
upcoming = []
|
||||
for kind, days in ((SkyType.SUNRISE, sunrises), (SkyType.SUNSET, sunsets)):
|
||||
for x in days:
|
||||
st = sun_times(x.score_date, lat, lon)
|
||||
end = st.sunrise_at if kind is SkyType.SUNRISE else st.dusk_end_at
|
||||
if end > now:
|
||||
upcoming.append((end, kind, x, st))
|
||||
if not upcoming:
|
||||
return None
|
||||
_, kind, target, st = min(upcoming, key=lambda e: e[0])
|
||||
return kind, target, st
|
||||
|
||||
|
||||
def day_plans(
|
||||
plan: Optional[SkyPlan], sunsets: list[SkyScore], sunrises: list[SkyScore], spots: list[Spot], lat: float, lon: float, now: datetime,
|
||||
) -> list[SkyPlan]:
|
||||
"""plan 과 같은 종류로 아직 끝나지 않은 날들의 결론. plan 의 날은 plan 그대로."""
|
||||
if plan is None:
|
||||
return []
|
||||
rise = plan.kind is SkyType.SUNRISE
|
||||
same = sunrises if rise else sunsets
|
||||
out = []
|
||||
for x in same:
|
||||
st = sun_times(x.score_date, lat, lon)
|
||||
if (st.sunrise_at if rise else st.dusk_end_at) <= now:
|
||||
continue
|
||||
out.append(plan if x.score_date == plan.day else build_plan(x, st, None, spots, same, now.date(), plan.kind))
|
||||
return out[:DAYS]
|
||||
|
||||
|
||||
def _slot(now: datetime) -> str:
|
||||
"""노을은 13시, 일출은 21시 이후 예보로 다시 계산한다."""
|
||||
return "am" if now.hour < 13 else "pm" if now.hour < 21 else "night"
|
||||
@@ -173,11 +223,19 @@ def _air(
|
||||
)
|
||||
|
||||
|
||||
def _open_west(region: Region, spots: list[SunsetSpot]) -> bool:
|
||||
"""구 중심 OPEN_WEST_KM 안에 서쪽이 트인 노을 명소가 있는지."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
return any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= OPEN_WEST_KM for p in spots)
|
||||
|
||||
|
||||
def _score_rows(
|
||||
region: Region, today: date, clouds: dict, now: datetime,
|
||||
hourly: Optional[dict[tuple[str, datetime], WeatherHourly]] = None, om: Optional[dict[tuple[str, datetime], OpenMeteoHourly]] = None,
|
||||
open_west: bool = False,
|
||||
) -> list[dict]:
|
||||
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로."""
|
||||
"""구름 점수(모델 평균)에 공기 보정(가시거리·습도·비 갠 뒤)을 곱한다. 공기 값이 없으면 구름 점수 그대로.
|
||||
open_west 면 노을에만 서쪽이 트인 곳 가산을 더한다."""
|
||||
rows = []
|
||||
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
||||
for i in range(DAYS):
|
||||
@@ -195,7 +253,9 @@ def _score_rows(
|
||||
model_layers.append(layers)
|
||||
if not per_model:
|
||||
continue
|
||||
value = min(100, round(statistics.mean(per_model) * air_factor(_air(region.code, sun_at, hourly or {}, om or {}))))
|
||||
air = replace(_air(region.code, sun_at, hourly or {}, om or {}), open_west=open_west and kind is SkyType.SUNSET)
|
||||
factor = air_factor(air)
|
||||
value = min(100, round(statistics.mean(per_model) * factor))
|
||||
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(len(DISTANCES_KM))))
|
||||
rows.append({
|
||||
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
|
||||
@@ -203,6 +263,8 @@ def _score_rows(
|
||||
"best_times": best_times(kind, sun_at.astimezone(KST), twilight_at.astimezone(KST), statistics.mean(highs)),
|
||||
"computed_at": now,
|
||||
"situation": sit.value, "models_total": len(model_layers), "models_agree": sum(situation(*m) is sit for m in model_layers),
|
||||
"air": {"factor": round(factor, 2), "visibility_km": round(air.visibility_km, 1) if air.visibility_km is not None else None,
|
||||
"humidity": air.humidity},
|
||||
})
|
||||
return rows
|
||||
|
||||
@@ -248,8 +310,10 @@ class SkyService:
|
||||
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
||||
near = nearest_spots(lat, lon, spots or [])
|
||||
first = sun_times(now.date(), lat, lon)
|
||||
plan = await self._plan(region, sunsets, near, now)
|
||||
sunrises = [x for x in scores if x.sky_type == SkyType.SUNRISE.value][:DAYS]
|
||||
plan = await self._plan(region, sunsets, sunrises, near, now)
|
||||
return ErrorType.SUCCESS, SkyView(
|
||||
plans=day_plans(plan, sunsets, sunrises, near, lat, lon, now),
|
||||
region=region,
|
||||
sunset_azimuth=first.sunset_azimuth,
|
||||
sunset=next((x for x in sunsets if x.score_date == now.date()), None),
|
||||
@@ -259,26 +323,24 @@ class SkyService:
|
||||
plan=plan,
|
||||
)
|
||||
|
||||
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
target, st = None, None
|
||||
for x in sunsets:
|
||||
st = sun_times(x.score_date, lat, lon)
|
||||
if st.dusk_end_at > now:
|
||||
target = x
|
||||
break
|
||||
if target is None or st is None:
|
||||
async def _plan(self, region: Region, sunsets: list[SkyScore], sunrises: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
"""다음에 오는 것으로 결론을 낸다: 오늘 해 뜨기 전엔 오늘 일출, 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출.
|
||||
구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||
picked = next_event(sunsets, sunrises, float(region.lat), float(region.lon), now)
|
||||
if picked is None:
|
||||
return None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
|
||||
kind, target, st = picked
|
||||
sun_at = st.sunrise_at if kind is SkyType.SUNRISE else st.sunset_at
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(sun_at)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
||||
by_km: dict[int, list[Layers]] = {}
|
||||
for r in rows or []:
|
||||
if r.kind == SkyType.SUNSET.value:
|
||||
if r.kind == kind.value:
|
||||
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
|
||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
|
||||
same = sunrises if kind is SkyType.SUNRISE else sunsets
|
||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, same, now.date(), kind)
|
||||
|
||||
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
||||
@@ -364,7 +426,10 @@ class SkyService:
|
||||
LOG.error(f"[sky] air openmeteo: {err.name}")
|
||||
hourly = {(w.region_code, w.forecast_at): w for w in hourly_rows or []}
|
||||
om = {(o.region_code, o.forecast_at): o for o in om_rows or []}
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om)]
|
||||
err, west_spots = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.west_open_spots(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] west spots: {err.name}")
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now, hourly, om, _open_west(r, west_spots or []))]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: self.crud.upsert_clouds(s, cloud_rows),
|
||||
lambda s: self.crud.upsert_scores(s, score_rows),
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from config.settings import settings
|
||||
from common.enums import ErrorType
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
|
||||
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
|
||||
URL_PREFIX = "/v1/talk/image/"
|
||||
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
|
||||
|
||||
|
||||
def folder() -> str:
|
||||
path = os.path.join(settings.upload_dir, "talk")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def file_of(url: str) -> Optional[str]:
|
||||
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
|
||||
name = url.removeprefix(URL_PREFIX)
|
||||
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
|
||||
return None
|
||||
path = os.path.join(folder(), name)
|
||||
return path if os.path.isfile(path) else None
|
||||
|
||||
|
||||
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
|
||||
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
|
||||
if len(data) > MAX_BYTES:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
img = ImageOps.exif_transpose(src).convert("RGB")
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
img.thumbnail((MAX_SIDE, MAX_SIDE))
|
||||
name = f"{uuid.uuid4().hex}.webp"
|
||||
img.save(os.path.join(folder(), name), "WEBP", quality=82)
|
||||
return ErrorType.SUCCESS, URL_PREFIX + name
|
||||
@@ -0,0 +1,137 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import 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 Talk, User, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, TalkReport
|
||||
from common.liker import Liker
|
||||
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.talk_image import file_of
|
||||
|
||||
BODY_MAX = 100
|
||||
DAILY_MAX = 5
|
||||
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
|
||||
HIDE_AT = 3
|
||||
PAGE = 20
|
||||
|
||||
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
|
||||
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
|
||||
|
||||
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
|
||||
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
|
||||
if row is None:
|
||||
return None
|
||||
rain = RainType(row.rain_type)
|
||||
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
|
||||
return f"{round(float(row.temp_c))}° {word}".strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class TalkView:
|
||||
talk: Talk
|
||||
author: User
|
||||
region_name: Optional[str]
|
||||
liked: bool
|
||||
mine: bool
|
||||
|
||||
|
||||
class TalkService:
|
||||
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
|
||||
self.crud, self.regions, self.weather = crud, regions, weather
|
||||
|
||||
async def page(self, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]:
|
||||
viewer = user.user_id if user else None
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
if rows:
|
||||
ids = [t.talk_id for t, *_ in rows]
|
||||
if user is not None:
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
|
||||
else:
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
return ErrorType.SUCCESS, [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
|
||||
|
||||
async def _weather_now(self, region_code: str) -> Optional[str]:
|
||||
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
|
||||
now = now_kst()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
|
||||
if err is not ErrorType.SUCCESS or not rows:
|
||||
return None
|
||||
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
|
||||
|
||||
async def add(self, user: User, region_code: str, body: str, image: Optional[str] = None) -> tuple[ErrorType, Optional[TalkView]]:
|
||||
body = " ".join(body.split())
|
||||
if not body or len(body) > BODY_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if image is not None and file_of(image) is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if _LINK.search(body) or _PHONE.search(body):
|
||||
return ErrorType.LINK_NOT_ALLOWED, None
|
||||
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if region is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
today = kst_midnight(now_kst().date())
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= DAILY_MAX:
|
||||
return ErrorType.DAILY_LIMIT, None
|
||||
weather = await self._weather_now(region_code)
|
||||
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image))
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err, None
|
||||
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:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
|
||||
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
|
||||
|
||||
async def like(self, who: Liker, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, _ = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, who, on))
|
||||
|
||||
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
|
||||
return err
|
||||
|
||||
async def block_author(self, user: User, talk_id: int) -> ErrorType:
|
||||
err, t = await self._talk(talk_id)
|
||||
if err is not ErrorType.SUCCESS or t is None:
|
||||
return err
|
||||
if t.user_id == user.user_id:
|
||||
return ErrorType.INVALID_INPUT
|
||||
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
|
||||
return err
|
||||
@@ -5,6 +5,7 @@ from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
@@ -14,23 +15,31 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Region, SunTime, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, latest_vilage_base, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.calc.sun import sun_times
|
||||
from services.calc.weather_calc import discomfort_index, feels_like_c
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_vilage, latest_mid_base, parse_mid, parse_vilage
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
|
||||
|
||||
SLOT_HOURS = range(0, 24, 3)
|
||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
||||
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
|
||||
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
||||
_MIN_DAY_HOURS = 8
|
||||
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
lightning: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slot:
|
||||
at: datetime
|
||||
@@ -49,6 +58,18 @@ class TodayWeather:
|
||||
slots: list[Slot]
|
||||
|
||||
|
||||
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
|
||||
"""초단기예보가 닿는 시각은 비·비 없음 모두 초단기예보로 바꾼 사본. 단기예보는 3시간마다라 그 사이 바뀐 비를 놓친다."""
|
||||
out = dict(by_at)
|
||||
for h in ultra or []:
|
||||
r = out.get(h.at)
|
||||
if r is None or (h.rain_type.value, h.rain_mm) == (r.rain_type, float(r.rain_mm)):
|
||||
continue
|
||||
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
||||
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": h.rain_mm})
|
||||
return out
|
||||
|
||||
|
||||
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
|
||||
rows = []
|
||||
for at, v in hourly.items():
|
||||
@@ -138,7 +159,7 @@ class WeatherService:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
|
||||
now = now_kst()
|
||||
await self.ensure_vilage(region, now)
|
||||
_, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
|
||||
day = day or now.date()
|
||||
sun = await self._ensure_sun(region, day)
|
||||
start = kst_midnight(day)
|
||||
@@ -154,11 +175,13 @@ class WeatherService:
|
||||
sunset_score = next(
|
||||
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
|
||||
)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
slots = []
|
||||
hour_now = now.replace(minute=0, second=0, microsecond=0)
|
||||
for h in SLOT_HOURS:
|
||||
at = start + timedelta(hours=h)
|
||||
row = by_at.get(at)
|
||||
# 지금이 든 칸은 칸 첫 시각 대신 지금 시각 예보 (이미 지난 시각의 비가 '지금'으로 보이지 않게)
|
||||
row = by_at.get(hour_now) if at <= now < at + timedelta(hours=3) and hour_now in by_at else by_at.get(at)
|
||||
icon, tone, note = _slot_view(at, row, sun)
|
||||
if note == "노을" and sunset_score is not None:
|
||||
note = f"노을 {sunset_score}"
|
||||
@@ -262,3 +285,45 @@ class WeatherService:
|
||||
}
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
|
||||
return SunTime(**row)
|
||||
|
||||
|
||||
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
|
||||
|
||||
|
||||
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if not cached:
|
||||
return None
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] != base.isoformat():
|
||||
return None
|
||||
return [
|
||||
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
||||
for h in data["hours"]
|
||||
]
|
||||
|
||||
|
||||
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
||||
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
||||
if attempt:
|
||||
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
||||
if (hours := await _cached_ultra(key, base)) is not None:
|
||||
return hours
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
continue
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
return None
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
@@ -43,7 +43,7 @@ def anyio_backend():
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users",
|
||||
)
|
||||
|
||||
|
||||
@@ -80,7 +80,6 @@ def offline(monkeypatch):
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -118,7 +117,7 @@ def offline(monkeypatch):
|
||||
|
||||
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
IP_A = {"X-Forwarded-For": "203.0.113.10"}
|
||||
IP_B = {"X-Forwarded-For": "203.0.113.20"}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_post_like_counts_once_per_ip(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
h = await _login(c, "anon_like_01")
|
||||
assert (await c.post(url, headers={**h, **IP_A})).json()["like_count"] == 3
|
||||
|
||||
feed_a = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
|
||||
p = next(x for x in feed_a["posts"] if x["post_id"] == post_id)
|
||||
assert p["liked"] is True and p["like_count"] == 3 and "saved" not in p
|
||||
other = (await c.get("/v1/feed", params={"region": REGION}, headers={"X-Forwarded-For": "203.0.113.30"})).json()
|
||||
assert next(x for x in other["posts"] if x["post_id"] == post_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_only_last_forwarded_ip_counts(offline):
|
||||
"""클라이언트가 X-Forwarded-For 앞쪽을 바꿔도 nginx 가 붙인 마지막 주소가 같으면 같은 사람이다."""
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "1.1.1.1, 203.0.113.10"})).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "2.2.2.2, 203.0.113.10"})).json()["like_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_like(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
h = await _login(c, "anon_like_02")
|
||||
comment_id = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "맑아요"})).json()["comment"]["comment_id"]
|
||||
url = f"/v1/reaction/comment/{comment_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=IP_A)).json()["comments"]
|
||||
assert listed[0]["liked"] is True
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["comments"]
|
||||
assert listed[0]["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_B)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_talk_like():
|
||||
async with client() as c:
|
||||
h = await _login(c, "anon_like_03")
|
||||
talk_id = (await c.post("/v1/talk", json={"region_code": REGION, "body": "바람 불어요"}, headers=h)).json()["talk"]["talk_id"]
|
||||
url = f"/v1/talk/{talk_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
talks = (await c.get("/v1/talk/list", headers=IP_A)).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is True
|
||||
talks = (await c.get("/v1/talk/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
@@ -50,11 +50,11 @@ async def test_signup_rejects_bad_input():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reactions_require_login_and_update_feed(offline):
|
||||
async def test_comment_requires_login_and_reactions_update_feed(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
post_id = feed["posts"][0]["post_id"]
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like")).status_code == 401
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "안녕"})).status_code == 401
|
||||
|
||||
token = (await _signup(c))["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.database.model.models import WeatherHourly
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
|
||||
from services.weather_service import RainHour, with_ultra_rain
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
REGION = SimpleNamespace(lat=37.5, lon=127.0)
|
||||
CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
|
||||
|
||||
def _rows(rain_from: int = 99):
|
||||
start = kst_midnight(DAY)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value,
|
||||
rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(0, 30)
|
||||
}
|
||||
|
||||
|
||||
def _defn(windows):
|
||||
return SimpleNamespace(
|
||||
weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[], windows=windows,
|
||||
)
|
||||
|
||||
|
||||
def test_slot_hours_split_by_sunset():
|
||||
hours = slot_hours(DAY, SUNSET)
|
||||
assert hours["morning"] == set(range(5, 11))
|
||||
assert hours["day"] == set(range(11, 16))
|
||||
assert hours["evening"] == {16, 17, 18}
|
||||
assert hours["night"] == set(range(19, 29))
|
||||
|
||||
|
||||
def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
|
||||
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score > 80
|
||||
assert parts["evening"].score < parts["morning"].score
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
|
||||
|
||||
def test_weather_score_covers_every_slot():
|
||||
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
|
||||
|
||||
def test_shown_parts_uses_last_night_before_five():
|
||||
parts = {"morning": 1, "day": 2, "evening": 3, "night": 4, EARLY: 5}
|
||||
assert _shown_parts(parts, "day") == {"morning": 1, "day": 2, "evening": 3, "night": 4}
|
||||
assert _shown_parts(parts, EARLY) == {"morning": 1, "day": 2, "evening": 3, "night": 5}
|
||||
|
||||
|
||||
def _hourly(h: int, rain: RainType = RainType.NONE) -> WeatherHourly:
|
||||
at = kst_midnight(DAY) + timedelta(hours=h)
|
||||
return WeatherHourly(
|
||||
region_code="1", forecast_at=at, temp_c=21, feels_c=21, discomfort_index=60, sky=Sky.CLOUDY.value, rain_type=rain.value,
|
||||
rain_prob=30, rain_mm=0, humidity=60, wind_ms=1.0, issued_at=at,
|
||||
)
|
||||
|
||||
|
||||
def test_ultra_overrides_vilage_rain_both_ways():
|
||||
"""초단기예보가 닿는 시각은 초단기예보가 이긴다: 단기예보가 맑아도 비로, 단기예보가 비여도 비 없음으로."""
|
||||
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER), _hourly(12, RainType.RAIN))}
|
||||
at = lambda h: kst_midnight(DAY) + timedelta(hours=h) # noqa: E731
|
||||
ultra = [RainHour(at=at(10), rain_type=RainType.RAIN, rain_mm=1.5), RainHour(at=at(9), rain_type=RainType.NONE, rain_mm=0),
|
||||
RainHour(at=at(11), rain_type=RainType.NONE, rain_mm=0)]
|
||||
out = with_ultra_rain(by_at, ultra)
|
||||
assert (out[at(10)].rain_type, float(out[at(10)].rain_mm)) == (RainType.RAIN.value, 1.5)
|
||||
assert (out[at(11)].rain_type, float(out[at(11)].rain_mm)) == (RainType.NONE.value, 0)
|
||||
assert out[at(9)] is by_at[at(9)] and out[at(12)] is by_at[at(12)]
|
||||
assert by_at[at(10)].rain_type == RainType.NONE.value and by_at[at(11)].rain_type == RainType.SHOWER.value
|
||||
|
||||
|
||||
def test_ultra_rain_lowers_slot_score():
|
||||
defn = _defn([{"from": 9, "to": 17}])
|
||||
by_at = {r.forecast_at: r for r in (_hourly(h) for h in range(5, 30))}
|
||||
rainy = with_ultra_rain(by_at, [RainHour(at=kst_midnight(DAY) + timedelta(hours=10), rain_type=RainType.RAIN, rain_mm=2.0)])
|
||||
dry, wet = (slot_results(defn, DAY, REGION, b, {}, CTX, SUNSET)["morning"].score for b in (by_at, rainy))
|
||||
assert wet < dry
|
||||
|
||||
|
||||
def test_slot_needs_two_overlapping_hours():
|
||||
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
|
||||
by_at = _rows()
|
||||
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
|
||||
|
||||
def test_current_slot_skips_passed_hours():
|
||||
"""13:30이면 낮 구간(11~15시)은 13시부터 본다. 11~12시에만 온 비는 지금 점수를 깎지 않는다. 지난 아침 구간은 그대로."""
|
||||
defn = _defn([{"from": 5, "to": 24}])
|
||||
by_at = {r.forecast_at: r for r in (_hourly(h, RainType.RAIN if h in (11, 12) else RainType.NONE) for h in range(5, 30))}
|
||||
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
|
||||
with_now = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET, now)
|
||||
without = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert with_now["day"].score > without["day"].score
|
||||
assert with_now["morning"].score == without["morning"].score
|
||||
|
||||
|
||||
def test_current_slot_keeps_last_hour():
|
||||
"""구간 끝 한 시간만 남아도 지금 구간 점수를 낸다."""
|
||||
now = datetime(2026, 10, 8, 15, 10, tzinfo=KST)
|
||||
assert "day" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
|
||||
+69
-13
@@ -61,7 +61,9 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 34
|
||||
assert len(body["stories"]) == 40
|
||||
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
|
||||
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -70,7 +72,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
assert body["bands"]["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
assert "미세먼지" not in weather["caption"]
|
||||
air = next(p for p in body["posts"] if p["post_type"] == PostType.AIR.value)
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "10㎍/㎥ · 좋음"), ("미세먼지", "20㎍/㎥ · 좋음")]
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "좋음"), ("미세먼지", "좋음")]
|
||||
event = next(p for p in body["posts"] if p["post_type"] == PostType.EVENT.value)
|
||||
assert event["slides"][0]["eyebrow"].startswith("가까운 행사 · ")
|
||||
|
||||
@@ -87,6 +89,18 @@ def test_feed_cache_expires_when_time_slot_changes():
|
||||
assert feed_ttl_sec(now, sunset) <= 600
|
||||
|
||||
|
||||
def test_feed_cache_expires_when_ultra_forecast_arrives():
|
||||
"""초단기예보 비가 각 점수에 들어가니, 다음 초단기예보가 나오는 :45 에 캐시가 끝나야 한다."""
|
||||
from datetime import datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import feed_ttl_sec
|
||||
|
||||
now = datetime(2026, 10, 2, 13, 20, tzinfo=KST)
|
||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||
assert feed_ttl_sec(now, sunset) == 25 * 60
|
||||
|
||||
|
||||
def _card(post_type, post_id=1):
|
||||
from datetime import datetime
|
||||
|
||||
@@ -137,6 +151,27 @@ def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||
assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE
|
||||
|
||||
|
||||
def test_arrange_puts_shareable_cards_before_plain_info():
|
||||
"""주말·노을·행사는 앞쪽 절반, 공기·자외선·상식은 각 뒤로."""
|
||||
from datetime import datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import arrange
|
||||
|
||||
sunset = datetime(2026, 10, 1, 18, 10, tzinfo=KST)
|
||||
cards = [_card(t, n) for n, t in enumerate([
|
||||
PostType.WEATHER, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.TOMORROW, PostType.WEEK,
|
||||
PostType.EVENT, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.WEEKEND_PLAN, PostType.AIR, PostType.UV, PostType.MOON,
|
||||
])]
|
||||
for slot, h in (("morning", 8), ("day", 13), ("evening", 17), ("evening", 19), ("night", 22)):
|
||||
out = [c.post_type for c in arrange(cards, slot, datetime(2026, 10, 1, h, tzinfo=KST), sunset, False, "2026-10-01:1114000000")]
|
||||
half = len(out) // 2
|
||||
assert PostType.SUNSET in out[:half] and PostType.WEEK in out[:half], (slot, out)
|
||||
assert all(i < half + 2 for i, t in enumerate(out) if t is PostType.EVENT), (slot, out)
|
||||
first_gak = out.index(PostType.GAK)
|
||||
assert all(out.index(t) > first_gak for t in (PostType.AIR, PostType.TIP) if t in out), (slot, out)
|
||||
|
||||
|
||||
def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
from datetime import datetime
|
||||
|
||||
@@ -190,7 +225,7 @@ def test_gak_key_handles_sunset_window():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
async def test_feed_missing_gak_is_not_cached(offline, monkeypatch):
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from services.index_service import IndexService
|
||||
@@ -202,8 +237,7 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
||||
assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == []
|
||||
|
||||
|
||||
def _alert_ctx(warnings=(), rain_prob=0):
|
||||
@@ -261,7 +295,7 @@ def test_text_helpers_short_day_and_compass():
|
||||
assert compass(263) == "서" and compass(247) == "서남서"
|
||||
|
||||
|
||||
def _air(pm25, pm10, measured_hours_ago=0):
|
||||
def _air(pm25, pm10, measured_hours_ago=0, rain=False):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -271,7 +305,7 @@ def _air(pm25, pm10, measured_hours_ago=0):
|
||||
now = datetime(2026, 10, 2, 9, 30, tzinfo=KST)
|
||||
air = None if pm25 is None and pm10 is None else SimpleNamespace(
|
||||
station_name="테스트", pm25=pm25, pm10=pm10, measured_at=now.replace(minute=0) - timedelta(hours=measured_hours_ago))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air, will_rain_2h=rain))
|
||||
return FeedService._air(None, _base() | {"post_type": PostType.AIR}, ctx)
|
||||
|
||||
|
||||
@@ -280,8 +314,11 @@ def test_air_post_shows_both_values_and_advice_only_when_bad():
|
||||
assert [r.label for r in good.slides[0].rows] == ["초미세먼지", "미세먼지"] and good.title == "미세먼지 좋음"
|
||||
bad = _air(40, 60)
|
||||
assert bad.title == "미세먼지 나쁨" and bad.slides[0].rows[-1].label == "이렇게 해요"
|
||||
wet = _air(10, 20, rain=True)
|
||||
assert "창문은 닫아" in wet.slides[0].line and wet.icon == "umbrella"
|
||||
assert "창문은 닫아" not in _air(40, 60, rain=True).slides[0].line
|
||||
very = _air(20, 160)
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "160㎍/㎥ · 매우나쁨"
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "매우나쁨"
|
||||
|
||||
|
||||
def test_air_post_off_without_fresh_data():
|
||||
@@ -346,14 +383,14 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
|
||||
|
||||
def test_gak_caption_starts_with_score_band_sentence():
|
||||
def test_gak_band_sentence_moves_to_slide_and_caption_keeps_hours():
|
||||
"""점수 구간 설명 문장은 슬라이드(say)에 두고, 글 설명엔 내일 점수나 하기 좋은 때만."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _gak_caption
|
||||
from services.feed_service import _band_sentence, _gak_caption
|
||||
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
||||
item.definition.sentences = {}
|
||||
assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
|
||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
||||
|
||||
|
||||
@@ -367,6 +404,25 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
|
||||
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
|
||||
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
|
||||
assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요"
|
||||
assert post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시"
|
||||
assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요"
|
||||
assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)]
|
||||
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||
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%"
|
||||
@@ -0,0 +1,80 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from jose import jwk, jwt
|
||||
|
||||
import common.google_id as google_id
|
||||
import services.auth_service as auth_service
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
|
||||
CLIENT_ID = "test-client.apps.googleusercontent.com"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_keys(monkeypatch):
|
||||
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
|
||||
public["kid"] = "k1"
|
||||
|
||||
async def keys(force: bool = False):
|
||||
return [public]
|
||||
|
||||
monkeypatch.setattr(google_id, "_keys", keys)
|
||||
|
||||
def sign(**over):
|
||||
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
|
||||
claims.update(over)
|
||||
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
|
||||
|
||||
return sign
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_verify_accepts_only_our_valid_tokens(google_keys):
|
||||
assert await google_id.verify(google_keys()) == "1234567890"
|
||||
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
|
||||
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
|
||||
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
|
||||
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert first["access_token"] and first["me"]["provider"] == 2
|
||||
nick = first["me"]["nickname"]
|
||||
assert "홍길동" not in nick and "@" not in nick
|
||||
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
|
||||
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
|
||||
assert other["me"]["login_id"] != first["me"]["login_id"]
|
||||
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
|
||||
assert bad["result"]["desc"] == "AUTH_FAILED"
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
|
||||
assert me["nickname"] == nick
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_config_exposes_client_id_only_when_set(monkeypatch):
|
||||
async with client() as c:
|
||||
monkeypatch.setattr(settings, "google_client_id", "")
|
||||
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
|
||||
|
||||
|
||||
def test_auto_nickname_fits_nickname_rule():
|
||||
for _ in range(50):
|
||||
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
|
||||
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import AirGrade
|
||||
from common.utils.kma_time import KST
|
||||
from services.hero_stats import HeroInput, hero_stats
|
||||
from services.hero_stats import HeroInput, hero_stats, hero_status
|
||||
|
||||
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
|
||||
|
||||
@@ -12,8 +12,9 @@ def _view(x: HeroInput) -> list[tuple[str, str, str, str]]:
|
||||
|
||||
|
||||
def test_clear_day_shows_uv_warning_and_temp_swing():
|
||||
x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23, discomfort=68)
|
||||
assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn"), ("coldwind", "일교차 10°", "아침엔 겉옷", "normal")]
|
||||
x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23)
|
||||
assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn")]
|
||||
assert _view(HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=2.0, temp_min=13, temp_max=23)) == [("coldwind", "일교차 10°", "아침엔 겉옷", "normal")]
|
||||
|
||||
|
||||
def test_rain_comes_first():
|
||||
@@ -30,12 +31,12 @@ def test_rain_later_today_and_no_rain_today():
|
||||
|
||||
def test_bad_air_beats_uv_and_wears_mask():
|
||||
x = HeroInput(now=NOW, night=False, air=AirGrade.VERY_BAD, uv=7.2)
|
||||
assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn"), ("glasses", "자외선", "7 · 높음", "warn")]
|
||||
assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn")]
|
||||
|
||||
|
||||
def test_summer_night_muggy_then_moon_and_no_card_for_no_rain():
|
||||
x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, discomfort=80, moon="보름달")
|
||||
assert _view(x) == [("muggy", "불쾌지수", "80 · 매우 높음", "warn"), ("moon", "오늘 밤 달", "보름달", "normal")]
|
||||
def test_night_without_alert_shows_moon_and_no_card_for_no_rain():
|
||||
x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, moon="보름달")
|
||||
assert _view(x) == [("moon", "오늘 밤 달", "보름달", "normal")]
|
||||
|
||||
|
||||
def test_one_coldwind_card_only():
|
||||
@@ -45,3 +46,27 @@ def test_one_coldwind_card_only():
|
||||
|
||||
def test_nothing_known_gives_nothing():
|
||||
assert hero_stats(HeroInput(now=NOW, night=False)) == []
|
||||
|
||||
|
||||
def _status(x: HeroInput) -> list[tuple[str, str, str]]:
|
||||
return [(s.label, s.value, s.tone) for s in hero_status(x)]
|
||||
|
||||
|
||||
def test_status_line_has_four_by_day_and_warns_only_caution():
|
||||
summer = datetime(2026, 7, 7, 14, 20, tzinfo=KST)
|
||||
x = HeroInput(now=summer, night=False, humidity=55, discomfort=75, uv=4.2, air=AirGrade.GOOD)
|
||||
assert _status(x) == [("습도", "보통", "normal"), ("불쾌지수", "불쾌", "warn"), ("자외선", "보통", "normal"), ("미세먼지", "좋음", "normal")]
|
||||
x = HeroInput(now=summer, night=False, humidity=72, discomfort=60, uv=6.0, air=AirGrade.BAD)
|
||||
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
|
||||
|
||||
|
||||
def test_status_line_shows_discomfort_all_year():
|
||||
x = HeroInput(now=NOW, night=False, humidity=95, discomfort=66, uv=1.0, air=AirGrade.GOOD)
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "불쾌지수", "자외선", "미세먼지"]
|
||||
|
||||
|
||||
def test_status_line_drops_uv_at_night_and_missing_values():
|
||||
assert _status(HeroInput(now=NOW, night=True, after_dark=True, humidity=25, uv=3.0, air=AirGrade.NORMAL)) == [("습도", "건조", "normal"), ("미세먼지", "보통", "normal")]
|
||||
# 저녁 구간(night=True, 아직 해 있음)엔 자외선이 남는다
|
||||
assert _status(HeroInput(now=NOW, night=True, uv=0.6)) == [("자외선", "낮음", "normal")]
|
||||
assert _status(HeroInput(now=NOW, night=False)) == []
|
||||
@@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,17 +51,24 @@ def fakes(monkeypatch):
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
seasons = [i["in_season"] for i in body["items"]]
|
||||
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -71,10 +78,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_filters_core(fakes):
|
||||
async def test_index_list_filters_core_to_gak_in_season_now(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json()
|
||||
assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"}
|
||||
month = now_kst().month
|
||||
assert {i["code"] for i in body["items"]} == {d["code"] for d in _seed() if month in d["months"]}
|
||||
assert all(i["season"] == season_of(month) for i in body["items"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -84,7 +93,7 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
assert body["index"]["code"] == "yajang"
|
||||
assert [f["label"] for f in body["factors"]] == ["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["zero_rules"] == "비 소식이 있거나 비 확률 70% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
@@ -115,6 +124,33 @@ def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
def test_every_index_has_valid_months_and_weights():
|
||||
for d in _seed():
|
||||
assert isinstance(d["months"], list) and all(1 <= m <= 12 for m in d["months"]), d["code"]
|
||||
assert sum(d[f"weight_{a}"] for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")) == 100, d["code"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypatch):
|
||||
today = now_kst().date()
|
||||
other = [m for m in range(1, 13) if m != today.month]
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="always", priority=2, months=[], sort_order=1),
|
||||
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
|
||||
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
_, board = await service.board(REGION)
|
||||
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
assert view == [("now", True, True, season_of(today.month)), ("always", True, True, None), ("off", False, False, None)]
|
||||
assert [i.definition.code for i in board.ranked] == ["now", "always"]
|
||||
assert all(not i.slot_ranks for i in board.items if not i.in_season)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
@@ -123,16 +159,36 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
|
||||
every = ("morning", "day", "evening", "night", "early")
|
||||
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
|
||||
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
|
||||
_, board = await service.board(REGION)
|
||||
ranks = {i.definition.code: i.slot_ranks for i in board.items}
|
||||
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
|
||||
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
|
||||
assert "night" not in ranks["high"]
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
|
||||
@@ -259,7 +259,84 @@ def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)),
|
||||
("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)),
|
||||
("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)),
|
||||
("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)),
|
||||
("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)),
|
||||
("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)),
|
||||
("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)),
|
||||
])
|
||||
def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("hangang", dict(feels=20.0, wind=1.5, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("themepark", dict(day=_WED, feels=20.0, wind=2.0), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("date", dict(feels=20.0, wind=1.5), dict(feels=5.0, prob=90, rain=RainType.RAIN, pm25=60)),
|
||||
("frizz", dict(feels=28.0, prob=90, rain=RainType.RAIN, hum=90), dict(feels=12.0, hum=35)),
|
||||
("boiler", dict(feels=2.0, hum=85, prob=60), dict(feels=22.0, hum=40)),
|
||||
("sunscreen", dict(feels=26.0, uv=8.0), dict(feels=8.0, uv=0.5)),
|
||||
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
|
||||
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
|
||||
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
|
||||
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
|
||||
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
|
||||
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
|
||||
("selfie", dict(wind=1.0, hum=35, sunshine_ratio=0.8), dict(prob=90, rain=RainType.RAIN, hum=90, wind=8.0, sunshine_ratio=0.0)),
|
||||
("sentimental", dict(feels=13.0, prob=90, rain=RainType.RAIN, wind=3.0, hum=85), dict(feels=28.0, hum=40, wind=0.5)),
|
||||
])
|
||||
def test_trend_and_mood_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
assert _seed_score("golf", day=_WED, **perfect) < 100
|
||||
|
||||
|
||||
def test_weather_score_100_only_on_perfect_day():
|
||||
from services.index_service import WEATHER_SCORE_DEF
|
||||
|
||||
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
|
||||
|
||||
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
|
||||
|
||||
|
||||
def test_raining_now_caps_even_with_low_rain_prob():
|
||||
"""초단기예보로 비가 들어온 시각은 예보 확률이 낮아도 '비 소식' 상한이 걸린다."""
|
||||
defn = _defn(zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}])
|
||||
r = evaluate(defn, [[_h(19, prob=30, rain=RainType.RAIN)]], CTX)
|
||||
assert r.score <= 20 and r.zero_reason == "비 소식이 있어 최대 20점"
|
||||
assert evaluate(defn, [[_h(19, prob=30)]], CTX).zero_reason is None
|
||||
|
||||
|
||||
def test_humidity_cap():
|
||||
defn = _defn(zero_rules=[{"field": "humidity", "op": ">=", "value": 85, "cap": 40}])
|
||||
assert evaluate(defn, [[_h(19, hum=92)]], CTX).zero_reason == "습도 85% 이상이라 최대 40점"
|
||||
assert zero_rules_text([{"field": "rain", "op": "==", "value": "yes"}]) == "비 소식이 있으면 0점"
|
||||
|
||||
|
||||
def test_axis_label_can_be_overridden():
|
||||
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
|
||||
|
||||
|
||||
def test_umbrella_lost_needs_rain_that_stopped():
|
||||
"""우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점."""
|
||||
defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}])
|
||||
after_rain = replace(CTX, rain_hours=frozenset({9, 10}))
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
|
||||
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.index_calc import Context, DayForecast, Hour, estimate, evaluate, time_score, zero_rules_text
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import in_season, season_badge, season_of, window_hours
|
||||
|
||||
CTX = Context(day=date(2027, 1, 9), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SNOWMAN = SimpleNamespace(
|
||||
weight_temp=50, weight_rain=10, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
factor_rules={"temp": {"type": "range", "lo": -5, "hi": 2, "best": -1}, "rain": {"dir": "wet"}, "wind": {"type": "calm", "ok": 3, "limit": 10},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[{"field": "snow", "op": "==", "value": "no"}], windows=[{"from": 9, "to": 16}],
|
||||
)
|
||||
|
||||
|
||||
def _h(hour, rain=RainType.NONE, feels=-1.0):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=80 if rain is not RainType.NONE else 0, wind_ms=1.0, humidity=70, sky=Sky.CLOUDY)
|
||||
|
||||
|
||||
def test_season_names_and_in_season():
|
||||
assert [season_of(m) for m in (1, 3, 6, 9, 12)] == ["겨울", "봄", "여름", "가을", "겨울"]
|
||||
always, winter = SimpleNamespace(months=[]), SimpleNamespace(months=[12, 1, 2])
|
||||
assert in_season(always, 7) and in_season(winter, 1) and not in_season(winter, 7)
|
||||
# 일 년 내내인 각엔 계절 표시가 없다
|
||||
assert season_badge(always, 1) is None and season_badge(winter, 1) == "겨울" and season_badge(winter, 7) is None
|
||||
assert in_season(SimpleNamespace(), 5)
|
||||
|
||||
|
||||
def test_snowman_is_zero_without_snow_and_high_when_snowing_near_zero():
|
||||
dry = evaluate(SNOWMAN, [[_h(h) for h in range(9, 16)]], CTX)
|
||||
assert dry.score == 0 and dry.zero_reason == "눈 소식이 없어 0점"
|
||||
snowy = evaluate(SNOWMAN, [[_h(h, RainType.SNOW) for h in range(9, 16)]], CTX)
|
||||
assert snowy.score >= 80 and snowy.zero_reason is None
|
||||
assert zero_rules_text(SNOWMAN.zero_rules) == "눈 소식이 없으면 0점"
|
||||
|
||||
|
||||
def test_snowman_estimate_from_mid_forecast_is_zero():
|
||||
fc = DayForecast(temp_min_c=-4, temp_max_c=1, rain_prob_am=70, rain_prob_pm=70, sky=Sky.CLOUDY)
|
||||
assert estimate(SNOWMAN, fc, [list(range(9, 16))], CTX).score == 0
|
||||
|
||||
|
||||
def test_sunrise_score_time_rule():
|
||||
assert time_score({"type": "sunrise_score"}, Context(**{**CTX.__dict__, "sunrise_score": 72})) == (72, "일출 하늘 점수 72")
|
||||
assert time_score({"type": "sunrise_score"}, CTX)[0] == 70
|
||||
|
||||
|
||||
def test_window_around_sunrise_covers_sunrise_hour():
|
||||
region = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
day = date(2027, 1, 1)
|
||||
h = sun_times(day, region.lat, region.lon).sunrise_at.astimezone(KST).hour
|
||||
assert window_hours(SimpleNamespace(windows=[{"around": "sunrise", "hours": 1}]), day, region) == [[h - 1, h, h + 1]]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from datetime import datetime, timezone
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.moon import nearest, phase_name
|
||||
from services.calc.moon import MoonNight, altitude, nearest, night, phase_name, view_line
|
||||
from services.feed_service import FeedService, _tonight
|
||||
|
||||
|
||||
@@ -27,7 +28,7 @@ def test_tonight_follows_feed_day_starting_at_3am():
|
||||
|
||||
def _moon_post(now: datetime):
|
||||
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
|
||||
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구"), hourly=[], board=None)
|
||||
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구", lat=37.38, lon=127.12), hourly=[], board=None)
|
||||
return FeedService._moon(None, base, c)
|
||||
|
||||
|
||||
@@ -38,3 +39,41 @@ def test_moon_post_every_night_with_full_and_new_moon_stories():
|
||||
assert new.title == "오늘 밤 달 없는 밤"
|
||||
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
||||
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
||||
|
||||
|
||||
SEOUL = (37.57, 126.98)
|
||||
|
||||
|
||||
def _night_of(at):
|
||||
"""그 시각과 23시가 가장 가까운 밤."""
|
||||
return (at.astimezone(KST) - timedelta(hours=11)).date()
|
||||
|
||||
|
||||
def test_full_moon_is_up_all_night_and_highest_near_solar_midnight():
|
||||
full = nearest(datetime(2026, 10, 25, tzinfo=KST), True)
|
||||
day = _night_of(full)
|
||||
m = night(day, *SEOUL)
|
||||
assert m.name == "보름달" and set(range(20, 29)) <= set(m.up_hours)
|
||||
start = datetime.combine(day, datetime.min.time(), tzinfo=KST)
|
||||
peak = max((start + timedelta(hours=22, minutes=10 * i) for i in range(24)), key=lambda t: altitude(t, *SEOUL))
|
||||
assert 23 <= (peak.hour if peak.hour >= 12 else peak.hour + 24) <= 25
|
||||
assert view_line(m, 0.0) == "밤새 잘 보여요"
|
||||
assert view_line(m, 0.8) == "흐려서 구름에 가려요"
|
||||
|
||||
|
||||
def test_first_quarter_sets_around_midnight_and_new_moon_is_not_seen():
|
||||
new = nearest(datetime(2026, 10, 12, tzinfo=KST), False)
|
||||
quarter = night(_night_of(new + timedelta(days=7.4)), *SEOUL)
|
||||
assert quarter.set_at is not None and quarter.set_at.astimezone(KST).hour in (21, 22, 23, 0, 1, 2)
|
||||
assert view_line(quarter, 0.0).endswith("까지 보여요")
|
||||
assert view_line(night(_night_of(new), *SEOUL), 0.0) == "해와 같은 쪽에 있어 안 보여요"
|
||||
hidden = MoonNight(name="초승달", lit=0.05, waxing=True, rise_at=None, set_at=None, up_hours=())
|
||||
assert view_line(hidden, 0.0) == "해 진 뒤 곧 져서 밤엔 안 보여요"
|
||||
assert view_line(replace(hidden, name="그믐달", waxing=False), 0.0) == "새벽 늦게 떠서 밤엔 안 보여요"
|
||||
|
||||
|
||||
def test_waning_moon_rises_late():
|
||||
full = nearest(datetime(2026, 10, 25, tzinfo=KST), True)
|
||||
m = night(_night_of(full + timedelta(days=7.4)), *SEOUL)
|
||||
assert m.rise_at is not None and m.rise_at.astimezone(KST).hour in (21, 22, 23, 0, 1, 2)
|
||||
assert view_line(m, 0.0).endswith("에 떠요")
|
||||
@@ -0,0 +1,86 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from router.router import app
|
||||
from services.calc.index_calc import Context, Hour, evaluate
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition
|
||||
from services.my_gak_service import MAX_PER_USER, gak_name
|
||||
|
||||
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "조건토끼"})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _hours(feels: float, rain: RainType = RainType.NONE, prob: int = 0, wind: float = 1.0, humidity: int = 50) -> list[Hour]:
|
||||
return [Hour(hour=h, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=humidity, sky=Sky.CLEAR) for h in (19, 20, 21)]
|
||||
|
||||
|
||||
def _score(rule: MyRule, hours: list[Hour], pm25: int | None = 10) -> int:
|
||||
ctx = Context(day=date(2026, 10, 20), is_holiday=False, pm25=pm25, air_label=None, moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
return evaluate(definition(rule), [hours], ctx).score
|
||||
|
||||
|
||||
def test_name_gets_gak_suffix_and_rejects_links_and_numbers():
|
||||
assert gak_name(" 소맥 ") == "소맥각"
|
||||
assert gak_name("야독각") == "야독각"
|
||||
assert gak_name("naver.com") is None
|
||||
assert gak_name("01012345678") is None
|
||||
assert gak_name("가" * 12) is None
|
||||
|
||||
|
||||
def test_only_chosen_conditions_count_and_score_falls_with_distance():
|
||||
rule = MyRule(temp=(15, 25), rain="dry")
|
||||
assert axes(rule) == ["temp", "rain"]
|
||||
inside = _score(rule, _hours(20))
|
||||
near = _score(rule, _hours(27))
|
||||
far = _score(rule, _hours(33))
|
||||
assert inside >= 90 and inside > near > far
|
||||
# 고르지 않은 바람·습도는 아무리 나빠도 점수에 안 들어간다
|
||||
assert _score(rule, _hours(20, wind=15, humidity=95)) == inside
|
||||
|
||||
|
||||
def test_dry_rule_caps_when_raining_and_wet_rule_likes_rain():
|
||||
assert _score(MyRule(rain="dry"), _hours(20, RainType.RAIN, 90)) <= 20
|
||||
assert _score(MyRule(rain="wet"), _hours(20, RainType.RAIN, 90)) >= 90
|
||||
|
||||
|
||||
def test_wind_and_air_limits():
|
||||
assert _score(MyRule(wind_max=4), _hours(20, wind=2)) > _score(MyRule(wind_max=4), _hours(20, wind=9))
|
||||
assert _score(MyRule(air="good"), _hours(20), pm25=10) > _score(MyRule(air="good"), _hours(20), pm25=40)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_add_list_delete_and_limits():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE})).status_code == 401
|
||||
h = await _login(c, "rule_01")
|
||||
assert (await c.get("/v1/my-gak")).json()["items"] == []
|
||||
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
|
||||
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
for i in range(MAX_PER_USER):
|
||||
assert (await c.post("/v1/my-gak", json={"name": f"각{chr(0xAC00 + i)}", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert (await c.post("/v1/my-gak", json={"name": "하나더", "rule": RULE}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_bad_rules():
|
||||
async with client() as c:
|
||||
h = await _login(c, "rule_02")
|
||||
bad = lambda rule: c.post("/v1/my-gak", json={"name": "야독", "rule": rule}, headers=h) # noqa: E731
|
||||
assert (await bad({})).status_code == 422
|
||||
assert (await bad({"temp": [25, 15]})).status_code == 422
|
||||
assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422
|
||||
assert (await bad({"humidity": [10, 120]})).status_code == 422
|
||||
@@ -18,7 +18,7 @@ def test_parse_ultra_reads_rain_and_temp():
|
||||
{"category": c, "fcstDate": "20261002", "fcstTime": "1000", "fcstValue": v}
|
||||
for c, v in [("PTY", "1"), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0}]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0, "lightning": False}]
|
||||
|
||||
|
||||
def _event(area, var, cmd, tm, seq=1, stress=0):
|
||||
@@ -72,3 +72,23 @@ def test_ieyo_particle():
|
||||
assert ieyo("환기") == "환기예요"
|
||||
assert ieyo("야장각") == "야장각이에요"
|
||||
assert ieyo("아아→뜨아") == "아아→뜨아예요"
|
||||
|
||||
|
||||
def test_parse_ultra_reads_drizzle_codes():
|
||||
"""초단기예보에만 있는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림."""
|
||||
items = [
|
||||
{"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v}
|
||||
for h, pty in ((10, "5"), (11, "6"), (12, "7"))
|
||||
for c, v in [("PTY", pty), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert [p["rain_type"] for p in parse_ultra(items)] == [RainType.RAIN, RainType.SLEET, RainType.SNOW]
|
||||
|
||||
|
||||
def test_parse_ultra_reads_lightning():
|
||||
"""LGT 는 낙뢰(kA). 0 이면 없음, 칸이 없어도 없음."""
|
||||
items = [
|
||||
{"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v}
|
||||
for h, lgt in ((10, "0"), (11, "3"), (12, None))
|
||||
for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "17"), ("LGT", lgt)] if v is not None
|
||||
]
|
||||
assert [p["lightning"] for p in parse_ultra(items)] == [False, True, False]
|
||||
@@ -2,7 +2,6 @@ import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -16,7 +15,7 @@ REGION = "1114000000"
|
||||
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
|
||||
SOURCES = {
|
||||
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
|
||||
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"ultra": (weather_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
|
||||
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
|
||||
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
|
||||
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
|
||||
)
|
||||
|
||||
|
||||
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
|
||||
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
|
||||
|
||||
|
||||
def _feed() -> Res_Feed:
|
||||
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
|
||||
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
|
||||
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
|
||||
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
|
||||
|
||||
|
||||
def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
|
||||
return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
|
||||
|
||||
|
||||
def test_day_summary_min_max_prob_and_daytime_sky():
|
||||
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
|
||||
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
|
||||
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
|
||||
|
||||
|
||||
def test_today_line_has_day_now_slot_firsts_and_sunset():
|
||||
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
|
||||
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
|
||||
|
||||
|
||||
def test_fill_puts_today_into_description_and_body():
|
||||
html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
|
||||
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
|
||||
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
|
||||
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
|
||||
|
||||
|
||||
def test_fill_keeps_template_when_no_weather():
|
||||
assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/seoul/jung" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/seoul/jung")
|
||||
missing = await client.get("/v1/seo/today/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
|
||||
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
|
||||
assert page.status_code == 200 and "지금 20°" in page.text
|
||||
@@ -81,3 +81,18 @@ async def test_drop_known_skips_same_festival_from_another_source():
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upsert_events_stores_names_without_html_entities():
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Event
|
||||
from crud.week_crud import WeekCRUD
|
||||
|
||||
# 문화정보원 목록은 두 번 인코딩돼 와서 한 번 풀어도 "<" 가 남는다
|
||||
row = {**_row("kcis:1", "김상희 2인전 &lt;안녕을 빌었다&gt;", date(2026, 10, 1), date(2026, 10, 24)), "place_name": "갤러리 &middot; 1층"}
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [row])])
|
||||
_, saved = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(select(Event).where(Event.source_id == "kcis:1")))
|
||||
assert (saved.name, saved.place_name) == ("김상희 2인전 <안녕을 빌었다>", "갤러리 · 1층")
|
||||
@@ -52,10 +52,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert 255 <= body["sunset_azimuth"] <= 280
|
||||
plan = body["plan"]
|
||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert "적당히" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||
assert plan["title"].startswith(plan["timeline"][2]["at"][11:16]) and plan["title"].endswith("물들어요") and plan["models_agree"] == plan["models_total"] == 2
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
@@ -106,22 +106,18 @@ def test_nearest_spots_west_first_and_nearest_one_outside_radius():
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
|
||||
|
||||
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
def test_outlook_only_when_a_later_day_has_a_higher_grade():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import SkySituation
|
||||
from services.calc.sky_score import grade
|
||||
|
||||
today = date(2026, 10, 6)
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
||||
sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요"
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v, grade=grade(v).value, sky_type=1) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레 노을이 곱게 물들어요"
|
||||
assert sky_service.outlook(day(0, 29), [day(0, 29), day(1, 30)], today) == ""
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == ""
|
||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||
few, glow = SkySituation.FEW, SkySituation.GLOW
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -160,8 +156,8 @@ def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air():
|
||||
hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)}
|
||||
om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)}
|
||||
hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"]
|
||||
assert hazy == round(plain * 0.6 * 0.75)
|
||||
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)}
|
||||
assert hazy == round(plain * 0.8 * 0.85)
|
||||
rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=60, rain_prob=80), ("R", hour): SimpleNamespace(humidity=60, rain_prob=10)}
|
||||
assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15))
|
||||
|
||||
|
||||
@@ -169,3 +165,30 @@ def test_nearest_slot_is_closest_three_hour_end():
|
||||
from datetime import datetime, timezone
|
||||
at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731
|
||||
assert [sky_service._nearest_slot(at(h, m)).hour for h, m in ((8, 0), (9, 0), (10, 29), (10, 31))] == [9, 9, 9, 12]
|
||||
|
||||
|
||||
def test_open_west_bonus_applies_to_sunset_only_and_needs_a_spot_nearby():
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import SkyType
|
||||
from services.calc.sky_score import Layers
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
region = SimpleNamespace(code="R", lat=37.56, lon=126.91)
|
||||
today = date(2026, 10, 7)
|
||||
st = sun_times(today, region.lat, region.lon)
|
||||
clouds = {
|
||||
("R", kind.value, km, sky_service._nearest_hour(at), 3): Layers(0, 20, 0)
|
||||
for kind, at in ((SkyType.SUNSET, st.sunset_at), (SkyType.SUNRISE, st.sunrise_at)) for km in (20, 100)
|
||||
}
|
||||
now = datetime(2026, 10, 7, 3, tzinfo=timezone.utc)
|
||||
by = lambda rows: {(r["sky_type"], r["score_date"]): r["score"] for r in rows} # noqa: E731
|
||||
plain = by(sky_service._score_rows(region, today, clouds, now))
|
||||
west = by(sky_service._score_rows(region, today, clouds, now, open_west=True))
|
||||
assert west[(SkyType.SUNSET.value, today)] == min(100, round(plain[(SkyType.SUNSET.value, today)] * 1.1))
|
||||
assert west[(SkyType.SUNRISE.value, today)] == plain[(SkyType.SUNRISE.value, today)]
|
||||
|
||||
near = SimpleNamespace(lat=37.5555, lon=126.895) # 망원한강공원, 약 1.5km
|
||||
far = SimpleNamespace(lat=37.0, lon=126.0)
|
||||
assert sky_service._open_west(region, [near]) and not sky_service._open_west(region, [far]) and not sky_service._open_west(region, [])
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from services.calc.sky_score import (
|
||||
GRADE_LABEL, Air, Layers, air_factor, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict,
|
||||
@@ -24,15 +24,21 @@ def test_score_rises_steadily_with_a_few_clouds():
|
||||
assert scores == sorted(scores) and len(set(scores)) == len(scores) # 맑은 날도 구름 몇 %로 갈리고 10%에서 꺾이지 않는다
|
||||
|
||||
|
||||
def test_air_factor_hazy_humid_lowers_and_clearing_rain_raises():
|
||||
def test_air_factor_centers_on_usual_air_and_clearing_rain_raises():
|
||||
assert air_factor(Air()) == 1.0
|
||||
assert air_factor(Air(visibility_km=40, humidity=50)) == 1.0
|
||||
assert air_factor(Air(visibility_km=5)) == 0.6 and air_factor(Air(humidity=90)) == 0.75
|
||||
assert 0.6 < air_factor(Air(visibility_km=30)) < 1.0
|
||||
assert air_factor(Air(visibility_km=20, humidity=60)) == 1.0 # 평소 공기
|
||||
assert air_factor(Air(visibility_km=5)) == 0.8 and air_factor(Air(humidity=90)) == 0.85
|
||||
assert air_factor(Air(visibility_km=40)) == 1.12 and air_factor(Air(humidity=40)) == 1.06 # 맑고 건조하면 올라간다
|
||||
assert 0.8 < air_factor(Air(visibility_km=12.5)) < 1.0 < air_factor(Air(visibility_km=30)) < 1.12
|
||||
assert air_factor(Air(rain_before=70, rain_now=10)) == 1.15
|
||||
assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음
|
||||
|
||||
|
||||
def test_open_west_horizon_adds_bonus():
|
||||
assert air_factor(Air(open_west=True)) == 1.1
|
||||
assert air_factor(Air(open_west=True, rain_before=70, rain_now=10)) == 1.15 * 1.1
|
||||
|
||||
|
||||
def test_low_clouds_toward_sun_block_the_light():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
||||
@@ -64,9 +70,9 @@ def test_sunset_best_times_order():
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "적당히" in reason(canvas, CLEAR)
|
||||
assert "멀리까지 구름이 끼어" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮게 깔린 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
@@ -77,7 +83,7 @@ def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
|
||||
def test_sunset_timeline_runs_golden_to_blue():
|
||||
sun = sun_times(date(2026, 10, 6), 37.56, 126.91)
|
||||
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.dusk_end_at)
|
||||
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.blue_start_at, sun.dusk_end_at)
|
||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||
@@ -101,3 +107,66 @@ def test_ranking_summary_only_when_most_spots_share_a_situation():
|
||||
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
||||
|
||||
|
||||
def test_next_event_sunrise_then_sunset_then_tomorrow_sunrise():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.sky_service import next_event
|
||||
|
||||
day = date(2026, 10, 8)
|
||||
rows = lambda kind: [SimpleNamespace(score_date=day + timedelta(days=i), sky_type=kind.value) for i in range(3)] # noqa: E731
|
||||
sunsets, sunrises = rows(SkyType.SUNSET), rows(SkyType.SUNRISE)
|
||||
pick = lambda h, m=0: next_event(sunsets, sunrises, 37.5, 127.0, datetime(2026, 10, 8, h, m, tzinfo=KST)) # noqa: E731
|
||||
assert (pick(5)[0], pick(5)[1].score_date) == (SkyType.SUNRISE, day)
|
||||
assert (pick(9)[0], pick(9)[1].score_date) == (SkyType.SUNSET, day)
|
||||
assert (pick(18, 10)[0], pick(18, 10)[1].score_date) == (SkyType.SUNSET, day)
|
||||
assert (pick(21)[0], pick(21)[1].score_date) == (SkyType.SUNRISE, day + timedelta(days=1))
|
||||
|
||||
|
||||
def test_sunrise_reason_and_timeline():
|
||||
from services.calc.sky_score import sunrise_timeline
|
||||
|
||||
assert "해 뜨는 쪽" in reason(Layers(0, 0, 0), Layers(90, 50, 0), SkyType.SUNRISE)
|
||||
sun = sun_times(date(2026, 10, 8), 37.5, 127.0)
|
||||
rows = sunrise_timeline(sun.dawn_start_at, sun.blue_end_morning_at, sun.sunrise_at - timedelta(minutes=12), sun.sunrise_at, sun.golden_end_at)
|
||||
assert [r["kind"] for r in rows] == ["blue", "peak", "sun", "golden"]
|
||||
assert sun.dawn_start_at < sun.sunrise_at < sun.golden_end_at
|
||||
|
||||
|
||||
def test_hazy_air_lowers_verdict_and_says_why():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.calc.sky_score import air_note
|
||||
from services.sky_service import day_verdict
|
||||
|
||||
hazy = {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}
|
||||
assert air_note(hazy) == "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"
|
||||
assert air_note({"factor": 0.9, "visibility_km": 30.0, "humidity": 60}) is None
|
||||
glow = SimpleNamespace(situation=SkySituation.GLOW.value, score=29, air=hazy)
|
||||
assert day_verdict(glow) == "maybe"
|
||||
assert day_verdict(SimpleNamespace(situation=SkySituation.GLOW.value, score=60, air=None)) == "go"
|
||||
assert day_verdict(SimpleNamespace(situation=SkySituation.COVERED.value, score=10, air=hazy)) == "rest"
|
||||
|
||||
|
||||
def test_plain_line_says_why_only_on_gray_days():
|
||||
from services.calc.sky_score import plain_line
|
||||
|
||||
hazy = {"factor": 0.5, "visibility_km": 6.5, "humidity": 80}
|
||||
assert plain_line(SkyGrade.GRAY, SkySituation.GLOW, hazy) == "하늘이 뿌예서 색이 바래요"
|
||||
assert plain_line(SkyGrade.GRAY, SkySituation.COVERED, hazy, SkyType.SUNRISE) == "해 뜨는 쪽 하늘이 구름에 가려요"
|
||||
assert plain_line(SkyGrade.GRAY, SkySituation.FEW, None) == "구름이 거의 없어요"
|
||||
assert plain_line(SkyGrade.GLOW, SkySituation.GLOW, None) is None
|
||||
|
||||
|
||||
def test_sky_title_follows_grade():
|
||||
from services.calc.sky_score import sky_title
|
||||
|
||||
peak = datetime(2026, 10, 12, 18, 10, tzinfo=timezone(timedelta(hours=9)))
|
||||
assert sky_title(SkyGrade.GRAY, SkyType.SUNSET, "오늘", peak) == "오늘은 노을이 거의 안 보여요"
|
||||
assert sky_title(SkyGrade.SOFT, SkyType.SUNSET, "모레", peak) == "18:10, 모레 노을이 은은하게 물들어요"
|
||||
assert sky_title(SkyGrade.GLOW, SkyType.SUNSET, "오늘", peak) == "18:10, 오늘 노을이 곱게 물들어요"
|
||||
assert sky_title(SkyGrade.RED, SkyType.SUNSET, None, peak) == "18:10, 하늘이 온통 붉게 물들어요"
|
||||
assert sky_title(SkyGrade.GLOW, SkyType.SUNRISE, "내일", peak) == "18:10, 내일 아침 노을이 곱게 물들어요"
|
||||
assert sky_title(SkyGrade.GRAY, SkyType.SUNRISE, None) == "아침 노을이 거의 안 보여요"
|
||||
@@ -0,0 +1,89 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from services.talk_service import DAILY_MAX, HIDE_AT, weather_line
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _write(c, h, body="망원동 하늘 진짜 맑아요"):
|
||||
return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_write_list_like_delete():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401
|
||||
h = await _login(c, "talk_01")
|
||||
t = (await _write(c, h, " 바람 많이 불어요 "))["talk"]
|
||||
assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"]
|
||||
|
||||
anon = (await c.get("/v1/talk/list")).json()["talks"]
|
||||
mine = next(x for x in anon if x["talk_id"] == t["talk_id"])
|
||||
assert mine["mine"] is False and mine["nickname"] == "talk_01"
|
||||
|
||||
liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()
|
||||
assert liked["liked"] is True and liked["like_count"] == 1
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0
|
||||
|
||||
other = await _login(c, "talk_02")
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_links_phone_long_and_daily_limit():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_03")
|
||||
assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT"
|
||||
bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json()
|
||||
assert bad_region["result"]["desc"] == "INVALID_INPUT"
|
||||
for i in range(DAILY_MAX):
|
||||
assert (await _write(c, h, f"오늘 {i}번째"))["talk"]
|
||||
assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reports_hide_and_block_hides_author():
|
||||
async with client() as c:
|
||||
author = await _login(c, "talk_04")
|
||||
t = (await _write(c, author))["talk"]
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
viewer = await _login(c, "talk_05")
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True
|
||||
seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]]
|
||||
assert t["talk_id"] not in seen
|
||||
assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
for i in range(HIDE_AT):
|
||||
h = await _login(c, f"talk_r{i}")
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
def test_weather_line():
|
||||
class Row:
|
||||
temp_c, sky, rain_type = 18.4, 1, 1
|
||||
|
||||
class Wet:
|
||||
temp_c, sky, rain_type = 11.6, 3, 2
|
||||
|
||||
assert weather_line(Row()) == "18° 맑음"
|
||||
assert weather_line(Wet()) == "12° 비"
|
||||
assert weather_line(None) is None
|
||||
@@ -0,0 +1,59 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from PIL import Image
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
GPS_IFD = 0x8825
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _jpeg_with_gps(w: int = 2400, h: int = 1600) -> bytes:
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "PhoneMaker"
|
||||
exif[GPS_IFD] = {1: "N", 2: (37.0, 33.0, 0.0), 3: "E", 4: (126.0, 58.0, 0.0)}
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), (120, 180, 230)).save(buf, "JPEG", exif=exif)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upload_strips_location_resizes_and_attaches_to_talk():
|
||||
src = _jpeg_with_gps()
|
||||
assert Image.open(io.BytesIO(src)).getexif().get_ifd(GPS_IFD)
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")})).status_code == 401
|
||||
h = await _login(c, "photo_01")
|
||||
url = (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")}, headers=h)).json()["image"]
|
||||
got = await c.get(url)
|
||||
assert got.status_code == 200 and got.headers["content-type"] == "image/webp"
|
||||
img = Image.open(io.BytesIO(got.content))
|
||||
assert max(img.size) == 1080
|
||||
assert not img.getexif()
|
||||
talk = (await c.post("/v1/talk", json={"region_code": REGION, "body": "하늘 사진", "image": url}, headers=h)).json()["talk"]
|
||||
assert talk["image"] == url
|
||||
listed = (await c.get("/v1/talk/list")).json()["talks"][0]
|
||||
assert listed["image"] == url
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_non_images_and_foreign_paths():
|
||||
async with client() as c:
|
||||
h = await _login(c, "photo_02")
|
||||
bad = (await c.post("/v1/talk/image", files={"file": ("a.txt", b"not an image", "text/plain")}, headers=h)).json()
|
||||
assert bad["result"]["desc"] == "INVALID_INPUT"
|
||||
for image in ("https://evil.example/a.webp", "/v1/talk/image/../../etc/passwd", "/v1/talk/image/" + "0" * 32 + ".webp"):
|
||||
res = (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕", "image": image}, headers=h)).json()
|
||||
assert res["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.get("/v1/talk/image/" + "0" * 32 + ".webp")).status_code == 404
|
||||
@@ -4,7 +4,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.router import app
|
||||
from router.v1.watch.watch import timeline
|
||||
@@ -83,3 +85,18 @@ async def test_watch_summary_unknown_region_fails(offline):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json()
|
||||
assert body["result"]["success"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
|
||||
start = now_kst().replace(minute=0, second=0, microsecond=0)
|
||||
items = [
|
||||
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
|
||||
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
|
||||
]
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(items))
|
||||
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
|
||||
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
|
||||
assert body["now"]["rain_2h"] is True and body["now"]["thunder"] is True
|
||||
@@ -5,7 +5,6 @@ from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
@@ -63,7 +62,7 @@ async def clean():
|
||||
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
|
||||
now = now_kst()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
|
||||
@@ -92,7 +91,7 @@ async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
|
||||
raise DataGoKrRequestFailed("HTTP 504")
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", fail)
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", fail)
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
|
||||
|
||||
@@ -43,6 +43,8 @@ services:
|
||||
REDIS_PORT: "6379"
|
||||
ports:
|
||||
- "${API_BIND:-9810}:9800"
|
||||
volumes:
|
||||
- uploads:/app/uploads # 사람 글 사진
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -104,3 +106,4 @@ services:
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
uploads:
|
||||
@@ -19,6 +19,8 @@ docker compose up -d --wait postgres redis
|
||||
docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql
|
||||
docker compose up -d --build backend worker frontend
|
||||
docker compose exec -T backend python scripts/load_seed.py
|
||||
# 피드 캐시는 최대 1시간이라, 각 규칙이 바뀌어도 오늘 탭만 옛 순위로 남는다
|
||||
docker compose exec -T redis sh -c "redis-cli --scan --pattern 'feed:*' | xargs -r redis-cli del" >/dev/null
|
||||
|
||||
if [ "${1:-}" = "--restore-db" ]; then
|
||||
dump="${2:?덤프 파일 경로가 필요합니다}"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# 2026-10-14 작업 정리: 지역 검색 페이지 · 첫 접속 각 비어 보임
|
||||
|
||||
운영 반영: `ba94a38` (https://weather.o2o.kr)
|
||||
|
||||
## 1. 처음 들어온 지역에 "오늘 계산된 각이 없어요"가 뜸
|
||||
|
||||
- **문제**: 아무도 안 본 지역을 처음 열면 각이 비어 보였다. 1분쯤 지나야 채워졌다.
|
||||
- **원인**
|
||||
- 각은 그 지역에 처음 접속한 사람이 생길 때 계산한다.
|
||||
- 예보를 받아 오는 동안 다른 요청은 3초만 기다렸다. 3초 안에 못 받으면 빈 피드를 만들었다.
|
||||
- 그 빈 피드를 1분 동안 캐시에 저장해서, 그사이 들어온 사람도 계속 빈 화면을 봤다.
|
||||
- **해결** (`fix/first-region-feed`)
|
||||
- 기다리는 시간을 최대 15초로 늘렸다 (`backend/services/weather_service.py`).
|
||||
- 각이 없는 피드는 캐시에 저장하지 않는다 (`backend/services/feed_service.py`). 다음 요청에서 바로 채워진다.
|
||||
- **상태**: 운영 반영. 김해시·인제군·분당구 피드에서 각 42개가 다 나오는 것 확인.
|
||||
|
||||
## 2. 검색에 지역별 날씨 페이지가 잡히지 않음
|
||||
|
||||
- **문제**: 다른 날씨 사이트처럼 "성남시 날씨" 같은 검색에 우리 페이지가 따로 뜨지 않았다.
|
||||
- **원인**
|
||||
- 사이트가 SPA 한 장이라, 검색엔진에는 모든 주소가 같은 제목과 같은 본문으로 보였다.
|
||||
- 지역별 주소도 없었다.
|
||||
- **해결** (`feat/region-seo-pages`)
|
||||
- 빌드할 때 지역 페이지 HTML 230장을 만든다 (`frontend/vite.config.ts`).
|
||||
- `sitemap.xml`도 빌드가 자동으로 만든다. 주소는 235개다.
|
||||
- 주소: `/today/{시도}/{시군구}`. 예: `/today/gyeonggi/seongnam`, `/today/seoul/mapo`
|
||||
- **페이지 단위를 이렇게 정했다**
|
||||
- 우리 날씨 데이터는 구 단위뿐이다.
|
||||
- 구로 나뉜 13개 시는 시 페이지 하나로 묶었다: 수원·성남·고양·용인·화성·부천·안산·안양·창원·청주·포항·전주·천안. 사람들은 "성남 날씨"로 검색하지 "중원구 날씨"로는 덜 찾는다.
|
||||
- 시 페이지는 시청이 있는 구의 날씨를 보여 준다. 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구를 보여 준다.
|
||||
- 나머지(서울·광역시의 구, 군, 일반 시)는 지금 단위 그대로 페이지를 만든다.
|
||||
- 중구·동구·고성군처럼 이름이 겹치는 곳이 있어서 주소 앞에 시도를 붙였다.
|
||||
- **앱 동작** (`frontend/src/b/region.tsx`)
|
||||
- 지역 주소로 들어오면 그 지역을 보여 준다. 위치 권한은 묻지 않고 저장된 선택도 덮어쓰지 않는다.
|
||||
- 지역 페이지에서 다른 지역을 고르면 주소도 그 지역 주소로 바뀐다.
|
||||
- `/`로 들어오면 예전 그대로다.
|
||||
- **지역 목록이 바뀌면**: `python backend/scripts/gen_region_pages.py`를 실행해 `frontend/seo/region.json`을 다시 만든다.
|
||||
- **매일 돌릴 스케줄은 필요 없다**: 주소와 소개 글은 그대로이고, 그날 값은 요청이 올 때 채운다.
|
||||
|
||||
## 3. 검색 결과에 실제 날씨가 안 보임
|
||||
|
||||
- **문제**
|
||||
- AccuWeather·weather.com은 검색 결과 요약에 기온·습도 같은 실제 값이 보인다.
|
||||
- 우리 정적 페이지에는 고정 소개 글만 있었다.
|
||||
- **원인**: 정적 HTML에는 그날 값이 들어갈 수 없다.
|
||||
- **해결 (가벼운 SSR)**
|
||||
- nginx가 `/today/...` 요청을 백엔드로 넘긴다 (`frontend/nginx.conf`).
|
||||
- 백엔드는 정적 HTML을 받아 와서 설명 메타와 본문에 오늘 값을 채운다 (`backend/services/seo_service.py`, `/v1/seo/today/{sido}/{place}`). React 화면은 지금처럼 브라우저에서 그린다.
|
||||
- 피드 캐시를 그대로 써서 추가 계산은 없다.
|
||||
- 백엔드가 응답하지 않거나 오류가 나면 정적 HTML을 그대로 보여 준다.
|
||||
- **검색어에 맞춘 제목과 요약**
|
||||
```
|
||||
성남시 오늘 날씨, 뭐 할까? · 경기 | 날씨각
|
||||
최저 9°·최고 19°, 강수확률 0%, 맑음. 지금 15°, 습도 보통·자외선 낮음·미세먼지 좋음. 아침은 드라이브각, 낮은 빨래각, 저녁은 자전거각, 밤은 러닝각. 해 지는 시각 오후 5시 57분.
|
||||
```
|
||||
- **상태**: 운영 반영. 백엔드를 끈 상태에서 정적 HTML로 돌아가는 것도 로컬에서 확인했다.
|
||||
|
||||
## 4. "날씨각" 검색 결과 요약에 게시물 글이 나옴
|
||||
|
||||
- **문제**: "날씨각"으로 검색하면 요약에 "날씨각포근한 빗속, 우산 돌리며…"처럼 게시물 문장이 나왔다.
|
||||
- **원인**
|
||||
- 구글은 JS로 그려진 화면도 읽는다.
|
||||
- 게시물마다 작성자 이름 "날씨각" 바로 뒤에 그날 문장이 붙어 있다. 그래서 검색어 "날씨각"과 맞는 그 부분을 요약으로 뽑았다.
|
||||
- **해결**
|
||||
- 처음에는 게시물 카드에만 `data-nosnippet`을 달았다.
|
||||
- 색인된 지역 페이지 요약에 시간대 칸("9시 : 낮음…")과 행사 장소·기간도 섞여 나왔다. 그래서 앱 영역 전체(`#root`, `#boot`)에 `data-nosnippet`을 달았다 (`frontend/index.html`, `0d6ab29`). 이제 요약은 description(지역 페이지는 서버가 채운 오늘 날씨)을 쓴다.
|
||||
- React가 뜨면 서버가 채운 `<main>` 글은 지워지기 때문에, 요약에 쓸 글은 description뿐이다.
|
||||
- 홈 설명이 "날씨각은 …"으로 시작하게 바꿨다.
|
||||
- **상태**: 운영 반영. 구글이 다시 읽어 가야 검색 결과가 바뀐다.
|
||||
|
||||
## 5. 사이트 이름이 "에이아이오투오"로 나옴
|
||||
|
||||
- **원인**: 구글이 사이트 이름을 상위 도메인 `o2o.kr`(회사)의 이름으로 잡은 것으로 보인다.
|
||||
- **해결**
|
||||
- 우리 쪽에 필요한 표시는 이미 다 있다: 구조화 데이터 `WebSite` name "날씨각", `og:site_name`, "날씨각"으로 시작하는 제목.
|
||||
- 코드로 바로 바꿀 수는 없다. 서치콘솔에서 홈을 색인 요청하고 몇 주 기다린다.
|
||||
- **상태**: 대기
|
||||
|
||||
## 해야 할 일
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 |
|
||||
|---|---|---|---|
|
||||
| [ ] | 네이버 서치어드바이저에 sitemap 제출, 대표 페이지 몇 개 수집 요청 | 네이버는 제출하지 않으면 새 페이지를 늦게 가져간다 | https://searchadvisor.naver.com |
|
||||
| [x] | 구글 서치콘솔에 sitemap 제출 (2026-10-14) | 색인을 앞당긴다 | https://search.google.com/search-console |
|
||||
| [ ] | 구글 URL 검사로 홈과 성남 페이지 색인 요청 | 색인과 사이트 이름 반영을 앞당긴다 | https://search.google.com/search-console |
|
||||
| [ ] | 휴대폰에서 지역 페이지 확인 | 시 안에서 내 구로 바뀌는지, 지역을 바꾸면 주소가 바뀌는지 로컬에서 확인 못 했다 | `frontend/src/b/region.tsx` |
|
||||
| [ ] | 1~2주 뒤 색인된 페이지 수 확인 | 다음 개선(문구, 홈에서 지역 페이지로 가는 링크)을 정한다 | 서치콘솔 |
|
||||
| [ ] | `test_feed_assembles_hero_stories_posts_and_bands` 기대값 40 → 42 | `0aeceac`에서 각 2개를 추가하며 안 고쳐서 main에서도 실패한다 | `backend/tests/test_feed.py:64` |
|
||||
| [ ] | 없는 지역 주소가 200으로 홈을 보여 주는 것 | SPA 기본 동작이다. canonical이 홈이라 당장 문제는 없다 | `frontend/nginx.conf` |
|
||||
| [ ] | 요약의 "해 지는 시각"을 노을이 가장 붉은 시각으로 바꿀지 | 지금은 계산으로 나온 일몰 시각이다 | `backend/services/seo_service.py` |
|
||||
|
||||
## 작업 중 있었던 일
|
||||
|
||||
- main에 push할 때 그사이 `feat/meeting-1008`이 먼저 합쳐져 있었다.
|
||||
- 그 브랜치의 탭 다시 누르면 맨 위로 기능과 `BLayout.tsx`에서 충돌이 났고, 두 변경을 다 살려 해결했다.
|
||||
- 이 저장소는 Gitea라서 `gh`로 PR을 만들 수 없다. main에 바로 합쳐서 배포했다.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# 기능 QA 체크리스트 (휴대폰)
|
||||
|
||||
아이폰 Safari와 안드로이드 Chrome에서 http://172.30.1.36:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
아이폰 Safari와 안드로이드 Chrome에서 테스트 서버(:30040) 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
|
||||
## 0. 처음 들어가기
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# 2026-10-08(목) 회의 — 날씨각
|
||||
|
||||
## 수정
|
||||
- 전체 날씨 점수 기준 강화. 100점은 '1년에 하루 있을까' 수준으로만 (결정) — 각 점수만 낮췄고 총점은 그대로라 100점이 계속 나옴. 총점과 각 점수의 흐름도 맞아야 함 (`backend/services/index_service.py:203`)
|
||||
- 각 점수를 아침·낮·저녁·밤 시간대별로 바뀌게 (결정) — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 (`backend/services/calc/index_calc.py:297`)
|
||||
- 노을 순위 분포 넓히기 — 10위까지 4점 차로 몰림 (김성경 선임 진행 중)
|
||||
- 히어로에 습도·불쾌지수 항상 표시 (결정) — 지금은 상황별로 두 칸을 골라 불쾌지수는 일정 수치 이상일 때만 나옴 (`frontend/src/b/TodayPage.tsx`, `HeroStat`)
|
||||
- 달 '밝기 5%'가 밝기인지 보이는 면적인지 정의하고, 구름·달 모양을 반영한 산정 로직으로 (`backend/services/calc/moon.py`)
|
||||
- 노을은 하늘 상황 문구 대신 점수 강조 + 골든아워·블루아워 설명 추가 — 10/7 다시 기획(점수 대신 상황 5가지)을 되돌림 (사용자 결정) (`frontend/src/b/SkyPage.tsx`)
|
||||
- 주말 예보 UI 개선 (구체 내용 없음) (`frontend/src/b/WeekPage.tsx`)
|
||||
|
||||
## 검색 등록 (우선)
|
||||
- 도메인은 지금처럼 별도 도메인 유지 (결정, Web4Ai 하위 경로 통합 안 함)
|
||||
- AEO·SEO 메타데이터를 넣고 구글·네이버 검색 등록부터 진행 (결정, 금일 핵심 업무) — 지금은 발행만 되고 등록 안 됨
|
||||
- 넣은 태그·키워드는 정의서로 정리 → 대표 보고
|
||||
- 콘텐츠가 매시간 바뀌는 데 맞는 재발행·노출 방식 정리 → 대표 보고 (TODO의 SEO 빌드 방식 [결정 필요] 행과 이어짐)
|
||||
- 사내 용어: '인덱싱' 대신 '검색 등록' (결정)
|
||||
|
||||
## 워치 앱 (양 팀장)
|
||||
- 축제: 메인 1건을 크게, 주변 축제는 넘겨 보기
|
||||
- 날씨각 데이터 연동용 앱 등록에 구글 개발자 본인 인증 필요 (대표 또는 소장)
|
||||
|
||||
## 담당·기한
|
||||
| 할 일 | 담당 | 기한 | 보고 |
|
||||
|---|---|---|---|
|
||||
| 날씨 점수 기준 강화, 시간대별 각 점수 | 김성경·최미나 | 미정 | 대표 보고 |
|
||||
| 히어로 습도·불쾌지수, 달 밝기 로직, 노을 점수·골든아워 설명 | 최미나 | 미정 | 대표 공유 |
|
||||
| 메타데이터 정의서, 구글·네이버 검색 등록 | 최미나 | 미정 | 대표 보고 |
|
||||
| 매시간 갱신 콘텐츠 검색 노출 방식 | 최미나 | 미정 | 대표 보고 |
|
||||
|
||||
## 날씨각 외 (이 저장소 밖)
|
||||
- 스테이머뭄 중복 사이트 내리고 하나로 (최미나, 금일 핵심 업무)
|
||||
- 에드오트 신버전 정식 배포·봇/사람 분리 통계 (김성경, 10/14), 일반 키워드 메타데이터·FAQ
|
||||
- 동적 목표가 상승 편향 시뮬레이션 (양 팀장, 다음 주)
|
||||
- 챗봇 품질 검증 에이전트 기획 (양 팀장·소장)
|
||||
- Claude 크레딧 1만 달러 사용 계획 (6개월, 담당 미정)
|
||||
@@ -0,0 +1,61 @@
|
||||
# 2026-10-20(화) 회의 — 날씨각
|
||||
|
||||
방향: 'AI가 날씨에 대해 쓰고 사람도 함께 올리는 날씨 소셜미디어' (대표)
|
||||
|
||||
## 금일 핵심 업무 (최미나)
|
||||
1. 오늘의 각을 일반 포스트 크기 카드로 만들고 공유 가능하게 (결정)
|
||||
2. '+' 사용자 포스팅을 메인 피드에 어떻게 섞을지 검토 → 대표 보고 (캐러셀로 묶기 의견 포함)
|
||||
|
||||
## 공유
|
||||
- 공유는 지금 보이는 화면을 링크로 그대로. 미리보기는 날씨각 대표 이미지 1장 고정 + 설명·링크 (결정) — 지금은 포스트를 이미지로 만들어 공유(`frontend/src/b/Sheets.tsx` `ShareSheet`, `storyImage.ts`), 아침·낮·저녁·밤을 한 장에 못 담음. 대표 이미지는 이미 `og.png` 1장(`frontend/index.html:28`)
|
||||
- 공유 이미지 잘림 수정, 공유 아이콘(종이비행기) 유지
|
||||
- 담당이 회의록상 김성경(확인 필요) — 오늘의 각 카드 공유(최미나)와 겹치므로 나눌 범위 확인
|
||||
|
||||
## 사용자 포스팅·피드
|
||||
- 별도 탭 없이 '+' 버튼으로 글·이미지 올리면 오늘 피드에 노출 (결정) — 지금 브랜치(feat/my-gak)는 '이야기' 탭(/talk)에 글만 100자. 탭 → '+'로, 이미지 추가로 바꿔야 함
|
||||
- 피드 순서: 날씨 히어로 → 오늘의 각 → 포스트 무한 피드 (결정)
|
||||
- 운영 포스트가 밀리지 않게 사용자 글은 중간중간 섞는 정도로 시작, 많아지면 순서 알고리즘 고민
|
||||
|
||||
## 피드 콘텐츠
|
||||
- 빨래각처럼 평이한 정보는 줄이고 주말 날씨('토요일 비 소식 없음')·동네 행사·노을을 앞쪽으로
|
||||
- 노을각 카드를 메인 피드 중간에
|
||||
- 단풍각 강화 — 단풍 지도(설악산 등 절정 지역, 서울 절정 시기), 시즌 동안 단풍 포스트 계속 노출. 단풍각 자체는 이미 있음(`backend/seed/index_definition.json:2940`)
|
||||
- 새 각: 시즌 스포츠각(프로야구·농구·배구), 제철 수산물각(전어·꽃게)
|
||||
- 시간대 지정 각(야장·별보기 등)은 그 시간이 아니어도 숨기지 말고 뒤쪽에 — 낮에도 '오늘 밤 별보기' 보이게
|
||||
- 억새각 시간대 설정 때문에 노출 조건이 안 맞음 — 확인 필요
|
||||
|
||||
## 날씨 점수·나만의 각
|
||||
- 날씨 점수 전체 하향 — 맑고 적당한 날도 96이 아니라 92 수준
|
||||
- 날씨 점수 누르면 산정 이유 설명
|
||||
- 불쾌지수 항상 표시 (결정) — 지금은 6~9월에만 (`backend/services/hero_stats.py:70`). 10/8에도 같은 결정이었음
|
||||
- 나만의 각: 기존 각 조합(지금 만든 1단계, `a8a126f`) 대신 사용자가 이름(소맥각·새우깡각·야독각)과 조건(기온·날씨 등)을 자유롭게 써서 등록 → 피드에 올려 좋아요 받기 (결정) → 프로토타입 대표 시연
|
||||
|
||||
## 로그인·앱인토스
|
||||
- 로그인 유지. 비로그인은 좋아요·댓글·공유까지, 포스팅할 때 로그인 요청 (결정) — 댓글 로그인 필요 여부는 확인 필요. 지금은 좋아요·댓글 모두 로그인 필수(`backend/router/v1/reaction/reaction.py`)
|
||||
- 구글·토스 로그인 적용 (결정, 앱인토스 등록에 토스 로그인 필요) — 지금은 아이디·비밀번호만(`backend/router/v1/auth/account.py`), `AuthProvider`에 GOOGLE 값만 있음
|
||||
- 앱인토스 정산 계좌(대표자 명의) 입력 시 유효성 오류 → 토스에 문의
|
||||
|
||||
## 검색 노출
|
||||
- '날씨각' 외에 '오늘 날씨'·'서울 날씨'·'성동구 날씨'·'춘천 날씨' 같은 지역 날씨 검색으로 들어오게 지역별 콘텐츠 추가, 리서치·테스트하며 개선 — 담당 김성경. 지금까지 한 것: 지역·구 페이지 274개(`96cbd19`), 검색어 리서치(`docs/검색어_인기_리서치.md`, '내일 날씨'가 '오늘 날씨'보다 훨씬 많음)
|
||||
|
||||
## 홍보·수익화
|
||||
- 유튜브 채널 개설, 각 설명·오늘 날씨 숏폼 매일 자동 생성·업로드 (결정) — 기존 숏폼 자동화(크리에이토메이트 템플릿) 활용, 노하우 전수(수석, 확인 필요). 담당 미정
|
||||
- 인스타그램·스레드 계정 운영
|
||||
- '오늘 날씨 코디' 시도 — 상품 링크·협찬 수익 가능성. TODO의 옷차림 [보류] 행과 이어짐
|
||||
- 날씨 타로 — 카드를 뽑으면 '오늘은 야장각'처럼 행동 추천
|
||||
- 광고는 애드센스 수준으로 양옆 여백 등에 깔끔하게만 (검토)
|
||||
- 의견(황 본부장): 날씨각을 Web4Ai 전 사이트에 챗봇처럼 모듈로 붙이고 외부 제휴로 확산 / 캐시워크처럼 날씨각 템플릿에 사용자 사진을 얹어 인스타에 바로 올리기
|
||||
|
||||
## 담당·기한
|
||||
| 할 일 | 담당 | 기한 | 보고 |
|
||||
|---|---|---|---|
|
||||
| 오늘의 각 카드화·공유 | 최미나 | 미정 | 대표 공유 |
|
||||
| '+' 포스팅·메인 피드 노출 방식 | 최미나 | 미정 | 대표 보고 |
|
||||
| 피드 순서 재배치, 단풍·스포츠·제철 수산물각 | 최미나 | 미정 | 대표 공유 |
|
||||
| 나만의 각 자유 등록 프로토타입 | 최미나 | 미정 | 대표 시연 |
|
||||
| 구글·토스 로그인, 앱인토스 계좌 오류 문의 | 최미나 | 미정 | 대표 공유 |
|
||||
| 날씨 타로·오늘 날씨 코디 구체화 | 최미나 | 미정 | 대표 보고 |
|
||||
| 공유 방식 변경(링크·대표 이미지·잘림) | 김성경(확인 필요) | 미정 | 대표 공유 |
|
||||
| 날씨 점수 하향·산정 설명, 시간대 지정 각 노출 | 김성경(확인 필요) | 미정 | 대표 보고 |
|
||||
| 지역 날씨 검색 콘텐츠 | 김성경 | 미정 | 대표 보고 |
|
||||
| 유튜브 채널·숏폼 자동화 | 미정 (노하우: 수석) | 미정 | 대표 보고 |
|
||||
+845
-117
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,39 @@
|
||||
# 검색어 인기 리서치
|
||||
|
||||
조사일: 2026-10-20
|
||||
방법: 구글 트렌드(한국, 최근 12개월 평균, '세차'=100 기준 상대값), 구글·네이버 자동완성.
|
||||
한계: 구글 트렌드는 표본 값이라 같은 검색어도 묶음마다 수치가 2배까지 달라졌다(이번주 날씨 32·69). 자릿수로만 본다. 한국은 네이버 비중이 커서 네이버 실제 검색량(네이버 검색광고 키워드 도구, 광고 계정 필요)으로 다시 확인해야 한다.
|
||||
|
||||
## 구글 트렌드 상대 검색량 ('세차'=100)
|
||||
|
||||
| 묶음 | 검색어 = 값 |
|
||||
|---|---|
|
||||
| 날씨 일반 | 내일 날씨 ≈ 10,000 · 오늘 날씨 384 · 서울 날씨 295 · 이번주 날씨 32~69 · 주말 날씨 15 |
|
||||
| 지역 | 인천 날씨 80 · 수원 날씨 31 · 성남 날씨 7 · 강남 날씨 4 · 분당 날씨 2 · 마포구 날씨 0 · 판교 날씨 0 |
|
||||
| 생활 | 우산 181 · 빨래 160 · 미세먼지 156 · 노을 82 · 옷차림 82 · 일몰 시간 50 |
|
||||
| 활동+날씨 | 캠핑 날씨 1 · 러닝 날씨 1 · 날씨 좋은 날 1 · 세차 날씨 0 · 빨래 날씨 0 |
|
||||
|
||||
- '날씨'·'오늘 날씨'를 같은 묶음에 넣으면 나머지가 모두 0으로 반올림됐다. '날씨' 단독 검색이 압도적으로 많다.
|
||||
|
||||
## 자동완성 (사람들이 실제로 붙여 치는 말)
|
||||
|
||||
- 오늘 날씨: 구글 — 판교·성남·서울 / 네이버 — 서울·부산·인천·대전·대구, **오늘 날씨 옷차림**
|
||||
- 분당 날씨: 내일 분당 날씨, 오늘 분당 날씨, 이번주 분당 날씨, 현재 분당 날씨, 분당 날씨 비·강수량
|
||||
- 주말 날씨: 네이버 — **이번주말 날씨**, 서울·대구·대전·제주 주말 날씨, 다음주 주말 날씨
|
||||
- 날씨 좋은 날: 갈만한 곳, 카페, 산책, 드라이브, 데이트
|
||||
- 러닝 날씨: 복장, 옷 / 캠핑 날씨: 어플, 10월·11월 캠핑 날씨
|
||||
- 노을: 네이버 — 노을 지는 시간
|
||||
- 세차·빨래: 세차장·세차용품, 빨래방·건조대·쉰내 — 날씨와 붙여 치는 말은 자동완성에 없음
|
||||
|
||||
## 판단
|
||||
|
||||
- 사람이 많이 치는 꼴은 "지역 + 날씨"와 "내일/오늘/이번주(말) 날씨"다. 우리 지역 주소가 받아야 할 검색어가 이쪽이다.
|
||||
- 지역은 큰 시가 많다(인천·수원 > 성남 > 분당·강남). 구 단위('마포구 날씨', '판교 날씨')는 구글에서 거의 0이라, 구 주소는 "시 주소가 못 받는 동네 검색" 보조로 본다.
|
||||
- '세차각'·'세차 날씨'·'빨래 날씨'처럼 활동+날씨 검색은 거의 없다. 각 이름으로 검색 유입을 기대하긴 어렵고, 검색은 지역 날씨로 들어오게 하고 각은 들어온 뒤 차별점으로 쓰는 게 맞다.
|
||||
- 시간 표현은 '내일'이 '오늘'보다 훨씬 많다. 우리 지역 페이지는 제목이 "오늘 날씨"뿐이라 '내일 OO 날씨'를 받을 내용이 없다 → 내일 예보·내일 각을 페이지에 넣을지 기획 결정 필요.
|
||||
- '옷차림'(오늘 날씨 옷차림)·'우산'·'미세먼지'·'노을 지는 시간'은 날씨각이 이미 다루는 주제와 맞닿고 검색량이 세차보다 많다. 후보로 둔다.
|
||||
|
||||
## 다음에 확인할 것
|
||||
|
||||
- 네이버 검색광고 키워드 도구로 위 검색어의 네이버 월간 검색 수(PC·모바일) 확인 — https://searchad.naver.com
|
||||
- 네이버 데이터랩 검색어 트렌드로 계절 변화 확인 — https://datalab.naver.com/keyword/trendSearch.naver
|
||||
@@ -0,0 +1,424 @@
|
||||
# 날씨각 서비스 동작 안내
|
||||
|
||||
날씨 정보를 언제 가져오는지, 점수를 어떻게 매기는지, 피드가 어떻게 만들어지는지 정리한 문서입니다. 개발자가 아닌 분이 확인하실 수 있도록 썼습니다.
|
||||
|
||||
- 기준: 2026년 10월 12일 코드 (10/8 회의 반영분 포함, 아직 배포 전)
|
||||
- 개발자용 원본: 점수 계산식은 `docs/점수_계산식.md`, 각별 설정은 `docs/각_계산기준.md`, 피드는 `docs/피드_동작방식.md`
|
||||
|
||||
---
|
||||
|
||||
## 1. 날씨 정보는 언제 가져오나
|
||||
|
||||
정보는 두 가지 방식으로 가져옵니다.
|
||||
|
||||
- **정해진 시각에 미리 받기:** 서버가 시계를 보고 전국 정보를 한꺼번에 받습니다.
|
||||
- **누가 열 때 받기:** 사용자가 어떤 구를 열었는데 가진 정보가 오래됐으면 그때 받습니다. 아무도 열지 않는 구는 받지 않습니다.
|
||||
|
||||
### 1-1. 정해진 시각에 미리 받는 것
|
||||
|
||||
| 시각 | 하는 일 |
|
||||
|---|---|
|
||||
| 매일 03:00 | 그날 피드의 틀(칸 19개)을 만들고 저장해 둔 피드를 모두 비웁니다. 7일 지난 날씨 기록도 지우고, 미세먼지 측정소 목록을 새로 받습니다. |
|
||||
| 매일 03:10 · 09:10 · 15:10 · 21:10 | 해외 날씨 서비스(Open-Meteo)에서 전국의 자외선, 가시거리(얼마나 멀리 보이는지), 돌풍, 햇빛 든 시간을 받습니다. |
|
||||
| 매일 06:40 · 18:40 | 주말 나들이 점수(주말 전국 순위, 당일치기)를 미리 계산합니다. 기상청 단기·중기예보가 모두 나온 뒤입니다. |
|
||||
| 매주 월요일 04:00 | 전국 축제·전시·콘서트·팝업 정보를 받고, 끝나면 Teams로 알립니다. |
|
||||
|
||||
### 1-2. 누가 열 때 받는 것
|
||||
|
||||
| 정보 | 어디서 | 새 정보가 나오는 때 | 받는 때 |
|
||||
|---|---|---|---|
|
||||
| 단기예보 (오늘~모레, 시간별 기온·비·바람·습도·하늘) | 기상청 | 하루 8번: 02·05·08·11·14·17·20·23시 발표, 10분 뒤부터 받을 수 있음 | 가진 예보보다 새 발표가 있으면 |
|
||||
| 중기예보 (3~10일 뒤, 하루 단위) | 기상청 | 하루 2번: 06·18시 발표 | 발표 30분 뒤부터, 아직 안 받았으면 |
|
||||
| 초단기예보 (앞으로 6시간 비) | 기상청 | 매시 30분 발표, 45분부터 받을 수 있음 | 새 발표가 있으면 |
|
||||
| 미세먼지 | 에어코리아 | 매시 측정, 20분쯤 뒤에 나옴 | 이번 시각 측정값이 없으면 전국을 한 번에 |
|
||||
| 기상특보 | 기상청 | 수시 | 1시간에 한 번 |
|
||||
| 노을·일출 구름 | Open-Meteo | 수시 | 하루 3번: 오전, 13시 이후, 21시 이후 |
|
||||
| 해·달 뜨고 지는 시각 | 받지 않고 서버가 계산 | 날짜와 위치로 정해짐 | 처음 필요할 때 한 번 |
|
||||
|
||||
- 외부 서비스가 응답하지 않으면 8초까지만 기다린 뒤, 가지고 있던 정보로 화면을 보여 줍니다.
|
||||
- 예보와 점수 기록은 7일, 구름 기록은 2일, 끝난 행사는 30일 뒤에 지웁니다.
|
||||
|
||||
---
|
||||
|
||||
## 2. 점수는 어떻게 매기나
|
||||
|
||||
이 장은 점수를 내는 식을 모두 적습니다. 식 옆에 쉬운 설명과 실제 숫자 예시를 붙였습니다.
|
||||
|
||||
### 2-1. 재료: 어떤 값을 쓰나
|
||||
|
||||
| 값 | 어디서 | 단위 |
|
||||
|---|---|---|
|
||||
| 기온, 습도, 바람, 비 올 확률, 비 형태(없음·비·눈), 하늘(맑음·구름많음·흐림) | 기상청 단기예보 | 1시간마다 |
|
||||
| 체감온도 | 위 기온·습도·바람으로 서버가 계산 (2-11) | 1시간마다 |
|
||||
| 초미세먼지 | 에어코리아, 구에서 가장 가까운 측정소의 **지금 측정값** | 하나 |
|
||||
| 햇빛 든 비율 | Open-Meteo, 3시간 동안 해가 난 시간 ÷ 3시간. **해가 진 구간은 0** | 3시간마다 |
|
||||
| 자외선, 가시거리, 돌풍, 땅 표면 온도 | Open-Meteo | 3시간마다 |
|
||||
| 노을 점수, 달 모양 | 서버가 계산 (2-9, 2-10) | 하루에 하나 |
|
||||
|
||||
### 2-2. 계산 순서 (지금 날씨 점수, 각 점수, 나들이 점수 공통)
|
||||
|
||||
1. **시간 고르기:** 점수를 낼 시간들을 고릅니다. 예: 저녁 구간이면 16~19시.
|
||||
2. **대표값 하나로 묶기:** 고른 시간들의 값을 요소마다 하나로 묶습니다. 묶는 법은 아래 표와 같습니다.
|
||||
3. **요소 점수 매기기:** 대표값마다 0~100점을 매깁니다 (2-3).
|
||||
4. **섞고 깎기:** 비중대로 섞은 뒤 가장 나쁜 요소만큼 깎습니다 (2-4).
|
||||
5. **조건 적용:** "비 확률 70% 이상이면 0점" 같은 조건이 있으면 적용합니다 (2-4).
|
||||
6. **시간대가 여러 개면** (예: 러닝각 6~8시와 19~22시) 각각 계산해 더 높은 쪽을 씁니다.
|
||||
|
||||
| 요소 | 묶는 법 | 이유 |
|
||||
|---|---|---|
|
||||
| 체감온도, 습도, 햇빛 든 비율 | 평균 | 그 시간 동안 대체로 어떤지 |
|
||||
| 비 올 확률 | 가장 높은 값 | 한 번이라도 비 올 수 있으면 곤란 |
|
||||
| 비 소식 | 한 시간이라도 있으면 "비 옴" | |
|
||||
| 바람, 자외선, 돌풍 | 가장 센 값 | 가장 나쁜 순간 기준 |
|
||||
| 가시거리 | 가장 짧은 값 | |
|
||||
| 초미세먼지 | 지금 측정값 그대로 | 예보가 없음 |
|
||||
|
||||
### 2-3. 요소 점수 식
|
||||
|
||||
**내려가는 곡선.** 거의 모든 요소가 이 곡선 하나로 점수를 깎습니다. 만점 근처에서는 천천히, 멀어질수록 빠르게 내려갑니다.
|
||||
|
||||
> 곡선(t) = (e^(−t²/2) − e^(−1/2)) ÷ (1 − e^(−1/2))
|
||||
> t는 "만점 지점에서 0점 지점까지 얼마나 갔나"(0~1)입니다.
|
||||
|
||||
| t | 0 | 0.25 | 0.5 | 0.75 | 1 |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| 곡선(t) | 1.00 | 0.92 | 0.70 | 0.38 | 0 |
|
||||
|
||||
**요소 점수를 매기는 방식은 아래 다섯 가지입니다.**
|
||||
|
||||
| 방식 | 식 | 쓰는 곳 |
|
||||
|---|---|---|
|
||||
| ① 편한 범위 | 범위 안: 최적값 ± 만점폭은 100점. 그 밖은 범위 끝으로 갈수록 85점까지 곡선으로 내려감. 범위 밖: 85점에서 곡선으로 0점까지 | 기온, 습도 |
|
||||
| ② 한쪽으로 | 100 × 곡선((값 − 만점 지점) ÷ (0점 지점 − 만점 지점)) | 비 확률, 미세먼지, 햇빛, 자외선, 가시거리, 덥거나 추울수록 좋은 기온 |
|
||||
| ③ 잔잔할수록 | '괜찮은 바람'의 절반 이하는 100점, 괜찮은 바람까지 85점으로 곧게, 그 뒤 '한계 바람'에서 0점까지 곡선 | 바람 |
|
||||
| ④ 고정값 | 정해진 점수 | 상관없는 요소(50점), 정보 없음(70점) |
|
||||
| ⑤ 각 전용 | 요일, 달, 노을 점수 | 각의 '시간' 요소 (2-7) |
|
||||
|
||||
① 편한 범위의 자세한 식:
|
||||
- 만점폭 = min(정해진 만점폭, 최적값에서 범위 끝까지 거리 ÷ 3). 범위가 좁아도 끝에서 갑자기 떨어지지 않게 하려는 것입니다.
|
||||
- 범위 안에서 만점폭 밖이면: 85 + 15 × 곡선(최적값에서 벗어난 만큼 ÷ 범위 끝까지 남은 거리)
|
||||
- 범위 밖이면: 85 × 곡선(범위에서 벗어난 만큼 × 기울기 ÷ 85). 기울기는 기온 8, 습도 2입니다. 그래서 **기온은 범위 밖으로 약 10.6°, 습도는 약 42.5% 벗어나면 0점**입니다.
|
||||
|
||||
**요소별 기준과 실제 점수 (지금 날씨 점수 기준)**
|
||||
|
||||
| 요소 | 기준 | 값 → 점수 |
|
||||
|---|---|---|
|
||||
| 체감온도 | ① 편한 범위 18~24°, 최적 21°, 만점폭 0.5° | 21°→100 · 22°→99 · 23°→94 · 24°→85 · 25°→84 · 27°→77 · 30°→53 · 34°→8 |
|
||||
| 비 | 비 소식이 있으면 0점. 없으면 ② 확률 0%가 100점, 100%가 0점 | 0%→100 · 20%→95 · 30%→89 · 50%→70 · 70%→45 · 100%→0 |
|
||||
| 바람 | ③ 괜찮은 바람 초속 2m, 한계 10m | 1m→100 · 1.5m→92 · 2m→85 · 3m→83 · 4m→78 · 6m→60 · 8m→32 · 10m→0 |
|
||||
| 습도 | ① 편한 범위 40~60%, 최적 50%, 만점폭 5% | 50%→100 · 55%→99 · 58%→92 · 60%→85 · 70%→79 · 80%→62 · 90%→37 |
|
||||
| 초미세먼지 | ② 10㎍/㎥가 100점, 75가 0점 | 10→100 · 15→99 · 25→93 · 35→82 · 50→56 · 75→0 |
|
||||
| 햇빛 든 비율 | ② 90%가 100점, 20%가 0점 | 90%→100 · 70%→90 · 50%→62 · 30%→22 · 20% 이하→0 |
|
||||
|
||||
**각마다 다르게 쓰는 방식**
|
||||
|
||||
| 요소 | 방식 | 식 |
|
||||
|---|---|---|
|
||||
| 기온 | 편한 범위 (21개) | 위 ① |
|
||||
| 기온 | 추울수록 (짬뽕각·군밤각 등 8개) | ② 각마다 정한 0점 지점과 만점 지점. 예: 군밤각은 18°에서 0점, 0°에서 100점 |
|
||||
| 기온 | 더울수록 (빨래각·화장붕괴각·냉면각) | ② 예: 냉면각은 18°에서 0점, 32°에서 100점 |
|
||||
| 기온 | 범위에서 멀수록 (공부각·집콕각) | 30 + 7 × 범위에서 벗어난 도(°) |
|
||||
| 비 | 비 안 와야 좋음 (24개) | 위 표의 '비' |
|
||||
| 비 | 비 와야 좋음 (10개) | 비 소식이 있으면 100점. 없으면 ② 확률 0%가 0점, 100%가 100점 |
|
||||
| 바람 | 잔잔할수록 (20개) | ③ 각마다 괜찮은 바람·한계 바람이 다름 |
|
||||
| 바람 | 적당히 (환기각·빨래각·연날리기각) | 초속 2~5m는 100점. 2m 미만은 60 + 20 × 바람, 5m 넘으면 12m에서 0점까지 곡선 |
|
||||
| 바람 | 셀수록 (짬뽕각 등 10개) | ② 0m가 0점, 8m가 100점 |
|
||||
| 바람 | 상관없음 (김서림각) | 50점 |
|
||||
| 습도 | 편한 범위 (13개) | 위 ① |
|
||||
| 습도 | 높을수록 (8개) | ② 40%가 0점, 90%가 100점 |
|
||||
| 습도 | 낮을수록 (5개) | ② 90%가 0점, 40%가 100점 |
|
||||
| 습도 | 상관없음 (8개) | 50점 |
|
||||
| 미세먼지 | 맑을수록 (기본) | ② 15㎍/㎥가 100점, 75가 0점 |
|
||||
| 미세먼지 | 탁할수록 (집콕각) | ② 75가 100점, 15가 0점 |
|
||||
|
||||
### 2-4. 섞고 깎는 식
|
||||
|
||||
> **섞은 점수** = (요소1 점수 × 비중1 + 요소2 점수 × 비중2 + …) ÷ 100
|
||||
> **최종 점수** = 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100), 반올림
|
||||
|
||||
- 비중이 0%인 요소는 '가장 낮은 요소'를 고를 때 뺍니다.
|
||||
- 가장 낮은 요소가 0점이면 25%, 50점이면 12.5%가 깎입니다. 100점은 비중이 있는 요소가 모두 100점일 때만 나옵니다.
|
||||
|
||||
**예시: 저녁 구간 지금 날씨 점수**
|
||||
- 재료: 체감 23°, 비 확률 20%(비 소식 없음), 바람 초속 3m, 습도 65%, 초미세먼지 20, 햇빛 든 비율 60%
|
||||
- 요소 점수: 체감 94, 비 95, 바람 83, 습도 84, 미세먼지 97, 햇빛 78
|
||||
- 섞은 점수 = (94×30 + 95×25 + 83×10 + 84×10 + 97×10 + 78×15) ÷ 100 = 90.05
|
||||
- 가장 낮은 요소 = 햇빛 78 → 최종 = 90.05 × (0.75 + 0.25 × 0.78) = 90.05 × 0.945 = **85점**
|
||||
|
||||
**조건 (0점·최대 N점)**
|
||||
- 각마다 "이 조건이면 0점" 또는 "이 조건이면 최대 N점"이 있습니다. 위 식으로 낸 점수와 상한 중 작은 값을 씁니다.
|
||||
- 조건에 쓰는 값과 쓰는 각 수: 비 올 확률 18, 바람 6, 체감온도 5(구간 안 최저 또는 최고), 초미세먼지 3, 강풍 특보 3, 돌풍 3, 흐린 하늘 비율 1, 땅 표면 온도 1. 조건이 있는 각은 34개 중 22개입니다.
|
||||
- 각별 조건은 `docs/각_계산기준.md`에 있습니다.
|
||||
|
||||
### 2-5. 하루를 네 구간으로 나눕니다
|
||||
|
||||
점수와 피드 순서는 모두 아래 네 구간을 기준으로 합니다. 해 지는 시각은 지역과 날짜마다 다르기 때문에 구간 경계도 매일 달라집니다.
|
||||
|
||||
| 구간 | 시각 | 예: 분당구 10/12 (해 짐 18:00) |
|
||||
|---|---|---|
|
||||
| 아침 | 05~11시 | 05:00~11:00 |
|
||||
| 낮 | 11시 ~ 해 지기 2시간 전 | 11:00~16:00 |
|
||||
| 저녁 | 해 지기 2시간 전 ~ 해 지고 1시간 뒤 | 16:00~19:00 |
|
||||
| 밤 | 해 지고 1시간 뒤 ~ 다음 날 05시 | 19:00~05:00 |
|
||||
|
||||
- 한 시간은 그 시간의 한가운데(30분)가 속한 구간에 넣습니다. 예: 해 짐이 18:20이면 16시대(16:30)는 저녁입니다.
|
||||
- 0~5시는 전날 밤 구간으로 봅니다.
|
||||
|
||||
### 2-6. 지금 날씨 점수 (오늘 탭 맨 위 큰 숫자)
|
||||
|
||||
- **지금 구간의 시간들**만으로 2-2~2-4 순서대로 계산합니다. 아침·낮·저녁·밤 모두 같은 식이고, 들어가는 시간만 다릅니다.
|
||||
- 요소와 비중: 체감온도 30%, 비 25%, 햇빛 든 비율 15%, 바람 10%, 습도 10%, 초미세먼지 10%. 조건(0점·최대 N점)은 없습니다.
|
||||
- **밤에는 최대 64점입니다.** 해가 진 구간은 햇빛 든 비율이 0이라 햇빛 점수가 0점입니다. 다른 다섯 요소가 모두 100점이어도 85 × 0.75 = 64점입니다. 저녁 구간도 해 진 뒤 시간이 섞여 낮보다 낮게 나옵니다.
|
||||
- 초미세먼지는 지금 측정값이라, 어느 구간이든 지금 공기 상태가 들어갑니다.
|
||||
- 기준값은 경험으로 잡은 것이고, 1년에 100점이 며칠 나오는지는 아직 확인하지 않았습니다.
|
||||
|
||||
### 2-7. 각 점수 (오늘의 각 34개)
|
||||
|
||||
- **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다.
|
||||
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다.
|
||||
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다.
|
||||
- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다.
|
||||
- **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다.
|
||||
- **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다.
|
||||
|
||||
| 종류 | 식 | 쓰는 각 |
|
||||
|---|---|---|
|
||||
| 요일 | 요일·공휴일마다 정한 점수 | 19개 |
|
||||
| 고정 | 정한 점수 하나 | 13개 |
|
||||
| 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 |
|
||||
| 노을 | 그날 노을 점수 (2-9) | 사진산책각 |
|
||||
|
||||
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
|
||||
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다.
|
||||
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
|
||||
|
||||
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
|
||||
|
||||
- 토·일 **10~17시**를 2-2~2-4 순서대로 계산합니다. 시간별 예보가 8시간 모두 있어야 계산합니다.
|
||||
|
||||
| 요소 | 비중 | 식 |
|
||||
|---|---:|---|
|
||||
| 비 | 40% | 비 안 와야 좋음 (2-3 '비') |
|
||||
| 체감온도 | 35% | ① 편한 범위 17~24°, 최적 21°, 만점폭 2° |
|
||||
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50 점의 평균 |
|
||||
| 바람 | 10% | ③ 괜찮은 바람 초속 4m, 한계 12m |
|
||||
|
||||
- 비 소식이 있거나 비 확률이 60% 이상이면 **최대 30점**입니다.
|
||||
- 중기예보뿐인 날은 기온을 어림하고(2-7), 하늘은 그날 하늘 하나, 바람은 70점입니다.
|
||||
- **전국 순위:** 대표 30곳을 점수 순으로 줄 세웁니다.
|
||||
- **당일치기:** 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 가운데 더 좋은 날의 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳, 이른 날, 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보여 주지 않습니다.
|
||||
|
||||
### 2-9. 노을 점수 (노을 탭, 피드 노을 카드)
|
||||
|
||||
노을은 **해 지는(뜨는) 시각에 가장 가까운 정시의 구름**으로 정합니다. 해 지는 방향으로 **20km 앞(머리 위)**과 **100km 앞(먼 하늘)** 두 지점의 구름을 봅니다. 구름은 높이에 따라 낮은 구름, 중간 구름, 높은 구름(각 0~100%)으로 나뉩니다.
|
||||
|
||||
**① 구름 점수**
|
||||
|
||||
| 항목 | 식 | 뜻 |
|
||||
|---|---|---|
|
||||
| 물들 구름 | 20km 지점의 중간 구름과 높은 구름 중 큰 값 | 햇빛을 받아 붉게 물드는 구름 |
|
||||
| 물들 정도 | 물들 구름 0%면 0.4 → 50%에서 1.0까지 곧게 → 100%에서 0까지 곧게 | 반쯤 덮였을 때 가장 좋음. 구름 없는 맑은 하늘은 55점 안팎(은은함) |
|
||||
| 머리 위 막힘 | 1 − 0.8 × 20km 낮은 구름 ÷ 100 | 낮은 구름은 하늘을 가림 |
|
||||
| 빛 들어옴 | 1 − min(100km 낮은 구름 + 0.5 × 100km 중간 구름, 100) ÷ 100 | 먼 하늘이 막히면 햇빛이 못 들어옴 |
|
||||
|
||||
> **구름 점수** = 100 × (0.75 × 물들 정도 + 0.25 × 머리 위 막힘) × (0.25 + 0.75 × 빛 들어옴)
|
||||
|
||||
예보 모델 2개(일본 JMA, 독일 ICON)로 각각 계산해 평균을 냅니다.
|
||||
|
||||
**② 공기·장소 보정 (곱하는 값)**
|
||||
|
||||
평소 공기(가시거리 20km, 습도 60%)를 1.0으로 두고, 맑으면 올리고 뿌옇거나 습하면 내립니다. 기준점 사이는 곧게 잇고, 양 끝 밖은 끝 값 그대로입니다.
|
||||
|
||||
| 조건 | 기준점 |
|
||||
|---|---|
|
||||
| 가시거리 | 5km 0.8 · 20km 1.0 · 40km 1.12 |
|
||||
| 습도 | 40% 1.06 · 60% 1.0 · 90% 0.85 |
|
||||
| 비 갠 직후 | 해 지기 2~6시간 전 비 확률이 60% 이상이었고 그 시각 40% 미만이면 × 1.15 |
|
||||
| 서쪽이 트인 명소 | 구 중심 20km 안에 서쪽이 바다·강·전망대로 트인 노을 명소가 있으면 × 1.1 (노을만) |
|
||||
|
||||
값이 없는 조건은 건너뜁니다.
|
||||
|
||||
> **노을 점수** = min(100, 구름 점수 모델 평균 × 공기·장소 보정)
|
||||
|
||||
**예시**
|
||||
- 구름 점수 57 (구름은 알맞음), 가시거리 6.5km, 습도 80%, 근처에 서쪽 트인 명소 없음
|
||||
- 보정 = 가시거리 0.82 × 습도 0.90 = 0.74
|
||||
- 노을 점수 = 57 × 0.74 = **42점 → 은은함**
|
||||
|
||||
**③ 등급과 화면 문구**
|
||||
|
||||
| 점수 | 등급 | 노을 탭 큰 글씨 (예) |
|
||||
|---|---|---|
|
||||
| 80 이상 | 붉음 | 18:10, 오늘 하늘이 온통 붉게 물들어요 |
|
||||
| 60~79 | 고움 | 18:10, 오늘 노을이 곱게 물들어요 |
|
||||
| 40~59 | 은은함 | 18:10, 오늘 노을이 은은하게 물들어요 |
|
||||
| 40 미만 | 잿빛 | 오늘 노을이 거의 안 보여요 |
|
||||
|
||||
잿빛인 날은 시각을 말하지 않고, 왜 안 보이는지 한 줄을 붙입니다. 위에서부터 먼저 걸리는 것 하나입니다.
|
||||
|
||||
| 조건 (두 모델 평균 구름) | 문구 |
|
||||
|---|---|
|
||||
| 100km 낮은 구름 + 0.5 × 중간 구름 ≥ 60 | 해 지는 쪽 하늘이 구름에 가려요 |
|
||||
| 20km 낮은 구름 ≥ 60 | 구름이 낮게 깔려 있어요 |
|
||||
| 물들 구름 < 25 | 구름이 거의 없어요 |
|
||||
| 물들 구름 > 75 | 구름이 너무 두꺼워요 |
|
||||
| 공기·장소 보정 < 0.7 (아주 뿌옇고 습한 날) | 하늘이 뿌예서 색이 바래요 |
|
||||
|
||||
- 큰 글씨 아래에는 오늘·내일·모레 세 칸을 그날 등급 색으로 칠해 보여 주고, 칸을 누르면 그날로 바뀝니다.
|
||||
- **무엇을 보여 주나:** 다음에 올 것입니다. 해 뜨기 전엔 오늘 일출, 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 일출도 같은 식이고 구름은 해 뜨는 쪽을 봅니다.
|
||||
- 점수는 지금 하늘이 아니라 **해 질 무렵 예보**로 낸 값입니다.
|
||||
|
||||
**④ 노을 시간표**
|
||||
|
||||
| 항목 | 식 |
|
||||
|---|---|
|
||||
| 골든아워 | 해가 지평선 위 6°로 내려온 때부터 해 질 때까지 |
|
||||
| 해 져요 | 해 고도 −0.833° (해 윗부분이 지평선에 닿는 때) |
|
||||
| 노을 피크 | 해 진 시각 + 10분 + (20km 높은 구름 % ÷ 10)분. 높은 구름이 많을수록 늦게까지 물듦 |
|
||||
| 블루아워 | 해 고도 −4°부터 −6°까지 |
|
||||
|
||||
일출은 순서가 반대이고, 노을 피크는 해 뜨기 같은 시간 전입니다. 해의 위치는 날짜와 구 중심 좌표로 계산합니다(NOAA 근사식).
|
||||
|
||||
### 2-10. 달 (오늘 밤 달 칸, 달 포스트, 별보기각)
|
||||
|
||||
- **모양:** 달과 해가 하늘에서 벌어진 각도(0° 삭 → 180° 보름)로 정합니다. 빛나는 면 = (1 − cos 각도) ÷ 2. 이 각도 구간으로 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달을 정합니다.
|
||||
- '달 밝기 N%'는 쓰지 않습니다. 초승달도 달 자체는 밝게 보여서, 퍼센트는 밝기가 아니라 모양일 뿐이기 때문입니다.
|
||||
- **뜨고 지는 시각:** 19시~다음 날 5시를 10분 간격으로 달 높이를 계산해(Meeus 간이식) 지평선을 넘는 때를 찾습니다.
|
||||
- **잘 보이는지:** 위에서부터 먼저 걸리는 것 하나입니다.
|
||||
|
||||
| 조건 | 문구 |
|
||||
|---|---|
|
||||
| 빛나는 면 3% 미만 (삭 무렵) | 해와 같은 쪽에 있어 안 보여요 |
|
||||
| 19~5시에 한 번도 안 뜸, 차오르는 달 | 해 진 뒤 곧 져서 밤엔 안 보여요 |
|
||||
| 19~5시에 한 번도 안 뜸, 기우는 달 | 새벽 늦게 떠서 밤엔 안 보여요 |
|
||||
| 밤늦게 뜸 | 새벽 2시에 떠요 (뜨는 시각) |
|
||||
| 달이 떠 있는 시간의 하늘 평균(맑음 0 · 구름많음 0.5 · 흐림 1)이 0.6 이상 | 흐려서 구름에 가려요 |
|
||||
| 같은 평균 0.3 이상 | 구름 사이로 보여요 |
|
||||
| 밤사이 짐 | 밤 11시까지 보여요 (지는 시각) |
|
||||
| 그 밖 | 밤새 잘 보여요 |
|
||||
|
||||
### 2-11. 체감온도, 불쾌지수
|
||||
|
||||
- **체감온도, 5~9월 (기상청 여름식):** 습구온도 Tw를 기온·습도로 구한 뒤, −0.2442 + 0.55399 × Tw + 0.45535 × 기온 − 0.0022 × Tw² + 0.00278 × Tw × 기온 + 3.0
|
||||
- **체감온도, 10~4월 (기상청 겨울식):** 기온 10° 이하이고 바람 4.8km/h 이상일 때만 13.12 + 0.6215 × 기온 − 11.37 × V^0.16 + 0.3965 × 기온 × V^0.16 (V는 km/h 바람). 그 밖엔 기온 그대로
|
||||
- **불쾌지수** = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3
|
||||
- 불쾌지수 기준: 68 미만 쾌적, 68~74 보통, 75~79 불쾌, 80 이상 매우 불쾌
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 3. 피드는 어떻게 만들어지나
|
||||
|
||||
### 3-1. 하루 한 번 틀을 만듭니다 (03:00)
|
||||
|
||||
- 매일 03:00에 그날 피드의 **칸 19개**를 정해 둡니다. 피드의 하루는 03:00에 시작해 다음 날 03:00에 끝납니다.
|
||||
- 틀에는 내용(점수, 문장)이 없고 "몇 번째 칸에 무엇이 들어간다"만 있습니다. 내용은 구마다 다르기 때문에 열 때 채웁니다.
|
||||
- 계절 소식, 날씨 상식, 한 문장, 달 칸은 전국이 같은 글입니다. 나머지 칸은 시도마다 따로입니다. 그래서 좋아요·댓글은 같은 시도끼리 같은 글에 쌓입니다.
|
||||
- 03:00 작업이 실패해도, 누가 피드를 열 때 빠진 칸을 다시 만듭니다.
|
||||
|
||||
### 3-2. 누가 열 때 내용을 채웁니다
|
||||
|
||||
1. 그 구의 날씨, 미세먼지, 특보, 노을, 각 점수, 열흘 날씨, 행사를 한꺼번에 모읍니다. 오래된 정보는 이때 새로 받습니다(1-2 참고).
|
||||
2. 칸마다 내용을 채웁니다. **채울 내용이 없거나 조건이 안 맞는 칸은 빠집니다.** 예를 들어 특보가 없으면 특보 칸이, 아침에는 내일 미리보기 칸이 빠집니다.
|
||||
3. 지금 구간에 맞는 순서로 놓고 저장해 둡니다.
|
||||
|
||||
| 칸 | 내용 | 나오는 조건 |
|
||||
|---|---|---|
|
||||
| 오늘·내일 날씨 | 시간별 날씨 | 예보가 있으면 |
|
||||
| 생활 알림 | 기상특보 | 그 구에 특보가 있을 때 |
|
||||
| 오늘의 각 1·2·3위 | 지금 구간 점수 상위 3개 | 점수가 있으면 |
|
||||
| 노을 | 노을 탭과 같은 문장 | 늘 (시간에 따라 노을 또는 일출) |
|
||||
| 내일 미리보기 | 내일 날씨 | 저녁·밤에만 |
|
||||
| 주말 예보, 주말 플랜(토·일) | 주말 날씨와 할 거리 | 주말 예보가 있으면 |
|
||||
| 가까운 행사 (최대 3장) | 7일 안에 열리는 행사 | 있는 만큼 |
|
||||
| 계절 소식, 날씨 상식 | 그날 고른 글 | 늘 |
|
||||
| 한 문장 | 그날 날씨에 맞는 글 | 늘 |
|
||||
| 미세먼지 | 지금 공기 | 측정값이 3시간 안이면 |
|
||||
| 당일치기 | 1~2시간 거리 추천 도시 | 50점 넘는 곳이 있으면 |
|
||||
| 오늘 밤 달 | 달 모양, 잘 보이는지 | 늘 |
|
||||
|
||||
### 3-3. 순서는 시간대마다 다릅니다
|
||||
|
||||
| 구간 | 앞쪽에 오는 것 | 이유 |
|
||||
|---|---|---|
|
||||
| 아침 | 특보 → 미세먼지 → 오늘의 각 | 나가기 전에 볼 것 |
|
||||
| 낮 | 오늘의 각 | 지금 할 거리 |
|
||||
| 저녁 | 노을 → 각 → 달 | 하늘을 볼 시간 |
|
||||
| 밤 | 내일 미리보기 → 달 → 주말 예보 | 내일과 주말 준비 |
|
||||
|
||||
순서에 덧붙는 규칙은 다음과 같습니다.
|
||||
|
||||
- 특보가 있으면 무조건 맨 위에 둡니다.
|
||||
- 금요일 저녁엔 주말 예보를 두 번째로 올립니다.
|
||||
- 해가 진 뒤엔 노을 카드가 세 번째로 내려가고, 블루아워가 끝나면 내일 일출 카드로 바뀝니다.
|
||||
- 같은 종류(각·각·각)가 연달아 나오지 않게 사이에 다른 카드를 끼웁니다.
|
||||
- 행사 카드는 날짜와 구로 정한 자리에 들어가서, 같은 날 같은 구는 늘 같은 자리에 있습니다.
|
||||
- 각 카드 세 장은 지금 시각에 가장 가까운 시간대의 각이 먼저 옵니다.
|
||||
|
||||
### 3-4. 피드는 언제 새로 바뀌나
|
||||
|
||||
만든 피드는 잠깐 저장해 두고 다시 씁니다. 저장은 다음에 내용이 바뀔 시각까지, 최대 1시간입니다.
|
||||
|
||||
| 바뀌는 때 | 무엇이 바뀌나 |
|
||||
|---|---|
|
||||
| 03:00 | 새 날 틀로 바뀝니다 |
|
||||
| 구간이 바뀔 때 (05시, 11시, 해 지기 2시간 전, 해 짐, 해 지고 1시간 뒤) | 순서가 바뀝니다 |
|
||||
| 새 단기예보가 나올 때 (하루 8번) | 각 점수, 순위, 문장이 바뀔 수 있습니다 |
|
||||
| 매시 20분 (미세먼지) | 미세먼지와 관련 점수가 바뀔 수 있습니다 |
|
||||
| 정보 하나라도 못 받았을 때 | 1분 뒤 다시 만듭니다 |
|
||||
|
||||
좋아요·댓글 수는 저장본을 쓰지 않고 매번 새로 읽기 때문에 누르는 즉시 반영됩니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 알아 두실 점
|
||||
|
||||
- **공유 링크:** 지금 그 구의 피드에서 글을 찾기 때문에, 어제 글이나 지금 꺼진 칸의 글은 '없는 글'로 나옵니다.
|
||||
- **예보 기준:** 모든 점수는 그 시점에 받은 예보로 계산합니다. 예보가 바뀌면 점수도 바뀝니다.
|
||||
- **노을 피크 시각:** 해 지는 시각에 10~20분을 더한 어림값이라 실제와 다를 수 있습니다.
|
||||
- **밤 날씨 점수:** 해가 진 뒤엔 햇빛이 0점이라 날씨가 완벽해도 최대 64점입니다 (2-6).
|
||||
- **점수 기준값:** 대부분 경험으로 잡은 값입니다. 실제 분포(예: 노을 점수가 1년에 며칠 붉음인지)는 아직 확인 중입니다.
|
||||
|
||||
---
|
||||
|
||||
## 부록: 각 34개 한눈에 보기
|
||||
|
||||
| 각 | 분류 | 하기 좋은 시간대 | 가장 크게 보는 요소 |
|
||||
|---|---|---|---|
|
||||
| 야장각 | 먹고 마시기 | 18~24시 | 기온 30% · 비 25% |
|
||||
| 피크닉각 | 밖에서 놀기 | 11~16시 | 비 20% · 기온 20% |
|
||||
| 치맥각 | 먹고 마시기 | 18~23시 | 기온 30% · 비 20% |
|
||||
| 산책각 | 밖에서 놀기 | 18~22시 | 기온 30% · 비 25% |
|
||||
| 환기각 | 집안일 | 10~18시 (2시간씩) | 미세먼지 45% · 비 15% |
|
||||
| 등산각 | 밖에서 놀기 | 7~12시 | 비 20% · 기온 20% |
|
||||
| 세차각 | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 비 40% · 햇빛 10% |
|
||||
| 캠핑각 | 밖에서 놀기 | 18시~다음 날 8시 | 기온 30% · 비 25% |
|
||||
| 러닝각 | 밖에서 놀기 | 6~8시 / 19~22시 | 기온 35% · 비 20% |
|
||||
| 별보기각 | 밖에서 놀기 | 21시~다음 날 2시 | 달·시간 45% · 미세먼지 15% |
|
||||
| 짬뽕각 | 먹고 마시기 | 11~14시 / 17~20시 | 기온 40% · 비 25% |
|
||||
| 막걸리각 | 먹고 마시기 | 17~22시 | 비 50% · 습도 15% |
|
||||
| 뜨아각 | 먹고 마시기 | 7~10시 | 기온 50% · 바람 15% |
|
||||
| 빨래각 | 집안일 | 9~16시 | 비 30% · 햇빛 25% |
|
||||
| 자전거각 | 밖에서 놀기 | 9~19시 | 비 20% · 바람 20% |
|
||||
| 멍뭉산책각 | 밖에서 놀기 | 7~9시 / 17~20시 | 기온 40% · 비 25% |
|
||||
| 김서림각 | 생활 고민 | 7~9시 | 기온 50% · 습도 30% |
|
||||
| 화장붕괴각 | 생활 고민 | 10~18시 | 기온 40% · 습도 35% |
|
||||
| 냉면각 | 먹고 마시기 | 11~14시 | 기온 55% · 습도 15% |
|
||||
| 택시대란각 | 생활 고민 | 22시~다음 날 2시 | 비 55% · 시간 15% |
|
||||
| 배달폭주각 | 생활 고민 | 17~21시 | 비 50% · 기온 20% |
|
||||
| 가드닝각 | 집안일 | 7~10시 | 비 25% · 기온 20% |
|
||||
| 사진산책각 | 밖에서 놀기 | 해 지기 앞뒤 1시간 | 시간 30% · 비 25% |
|
||||
| 야구각 | 밖에서 놀기 | 18~22시 | 비 40% · 기온 25% |
|
||||
| 공부각 | 집안일 | 13~18시 | 비 35% · 기온 35% |
|
||||
| 넷플릭스각 | 집안일 | 20~24시 | 비 35% · 기온 30% |
|
||||
| 군밤각 | 먹고 마시기 | 17~21시 | 기온 55% · 비 25% |
|
||||
| 골프각 | 밖에서 놀기 | 7~12시 / 12~17시 | 비 30% · 기온 30% |
|
||||
| 집콕각 | 집안일 | 10~18시 | 비 30% · 기온 30% |
|
||||
| 낚시각 | 밖에서 놀기 | 5~9시 / 16~19시 | 바람 35% · 비 25% |
|
||||
| 드라이브각 | 밖에서 놀기 | 10~17시 | 비 30% · 기온 20% |
|
||||
| 연날리기각 | 밖에서 놀기 | 11~16시 | 바람 45% · 비 25% |
|
||||
| 물놀이각 | 밖에서 놀기 | 11~17시 | 기온 40% · 비 25% |
|
||||
| 김장각 | 집안일 | 9~16시 | 기온 50% · 비 25% |
|
||||
|
||||
- 비 요소는 34개 중 24개가 "비가 안 와야 좋음"입니다. 나머지 10개(짬뽕각, 막걸리각, 뜨아각, 김서림각, 화장붕괴각, 택시대란각, 배달폭주각, 공부각, 넷플릭스각, 집콕각)는 비가 와야 점수가 오릅니다.
|
||||
- 각별 0점 조건과 자세한 기준은 `docs/각_계산기준.md`에 있습니다.
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
# 이벤트 추적 (GA4)
|
||||
|
||||
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08)
|
||||
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx`, `frontend/src/b/install.ts`, `frontend/src/b/installBanner.tsx`, `frontend/src/main.tsx` (2026-10-21)
|
||||
|
||||
## 한 줄 요약
|
||||
|
||||
@@ -25,12 +25,18 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
| `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
|
||||
| `select_content` | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` |
|
||||
| `share` | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` |
|
||||
| `login` | 로그인 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `login` | 로그인 성공 (구글로 처음 들어와 자동 가입된 경우도 `login`) | `method: 'id' \| 'google'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
| `install_banner_view` | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
||||
| `install_click` | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
|
||||
| `install_choice` | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
|
||||
| `install_done` | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
|
||||
| `app_launch` | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
|
||||
|
||||
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
|
||||
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
|
||||
- 설치는 카드 노출 → 누름 → 설치 완료 → 홈 화면 실행 순서로 본다. 아이폰은 설치 완료를 알 수 없어 `app_launch`로 대신 본다.
|
||||
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
|
||||
|
||||
## GA4 설정
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
# 점수 계산식
|
||||
|
||||
화면에 나오는 점수·판정의 계산식을 한곳에 모은 문서입니다. 각별 비중·시간대는 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
|
||||
| 점수 | 화면 | 코드 |
|
||||
|---|---|---|
|
||||
| 지금 날씨 점수 | 오늘 탭 히어로 큰 숫자 | `backend/services/index_service.py` (`WEATHER_SCORE_DEF`) |
|
||||
| 각 점수 | 각 탭, 피드 각 카드 | `backend/services/calc/index_calc.py` (`evaluate`) |
|
||||
| 나들이 점수 | 주말 탭 전국 순위, 당일치기 카드 | `backend/services/calc/index_calc.py` (`outing`) |
|
||||
| 노을 점수·판정 | 노을 탭, 피드 노을 카드, 노을 순위 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py` |
|
||||
| 노을 시각 | 노을 탭 시간표 | `backend/services/calc/sun.py`, `sky_score.py` (`best_times`) |
|
||||
| 달 모양·잘 보이는지 | 밤 히어로, 달 포스트, 별보기각 | `backend/services/calc/moon.py` |
|
||||
| 불쾌지수 | 히어로 칸 | `backend/services/calc/weather_calc.py` |
|
||||
|
||||
## 1. 공통 — 요소 점수와 섞는 법
|
||||
|
||||
오늘 날씨·각·나들이 점수는 모두 같은 방식입니다.
|
||||
|
||||
1. 요소(기온·비·바람·습도·미세먼지·햇빛 등)마다 0~100점을 매깁니다.
|
||||
2. 비중(합 100%)대로 섞습니다.
|
||||
3. 가장 낮은 요소로 깎습니다: **최종 = 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 ÷ 100)**. 비중 0%인 요소는 빼고 봅니다. 한 요소가 0점이면 최대 25% 깎입니다.
|
||||
4. 0점 조건·최대 N점 조건이 있으면 적용합니다.
|
||||
|
||||
그래서 100점은 **비중이 있는 요소가 모두 100점**일 때만 나옵니다.
|
||||
|
||||
### 내려가는 곡선
|
||||
|
||||
만점 구간을 벗어나면 정규분포 곡선 모양으로 내려갑니다. 만점 근처는 천천히, 멀어질수록 빨리 떨어집니다.
|
||||
|
||||
`곡선(t) = (e^(−t²/2) − e^(−0.5)) ÷ (1 − e^(−0.5))` — t=0이면 1, t=1이면 0.
|
||||
|
||||
### 요소별 점수
|
||||
|
||||
| 요소 | 규칙 | 계산 |
|
||||
|---|---|---|
|
||||
| 기온(체감) | 편한 범위 lo~hi, 최적 best | 최적 ± 만점폭(기본 2°, 범위 끝까지 거리의 1/3 넘지 않음)은 100 → 범위 끝에서 85 → 범위 밖은 1°마다 8점 꼴로 곡선을 따라 0 (약 10.6° 벗어나면 0) |
|
||||
| 기온 | 높을수록·낮을수록 | zero에서 0, full에서 100, 사이는 곡선 |
|
||||
| 비 (마른 날이 좋음) | | 비 소식이 있으면 0. 아니면 비 확률 0%=100 → 100%=0, 곡선 |
|
||||
| 비 (비 오면 좋음) | 막걸리·배달폭주각 등 | 비 소식이 있으면 100. 아니면 비 확률 0%=0 → 100%=100 |
|
||||
| 바람 (잔잔할수록) | ok, limit | ok/2 이하 100 → ok에서 85 (직선) → limit에서 0 (곡선). 시간대 중 가장 센 바람 기준 |
|
||||
| 습도 | 편한 범위 | 기온과 같은 모양, 만점폭 5%, 범위 밖은 1%마다 2점 꼴 |
|
||||
| 미세먼지 | | 초미세먼지 15㎍/㎥ 이하 100 → 75 이상 0, 곡선. 집콕각은 거꾸로 |
|
||||
| 자외선·햇빛·가시거리 | zero, full | 직선 대신 곡선으로 zero→full |
|
||||
| 정보 없음 | | 바람·미세먼지·자외선·햇빛·가시거리 정보가 없으면 70점 |
|
||||
|
||||
## 2. 시간대 구간
|
||||
|
||||
| 구간 | 시각 |
|
||||
|---|---|
|
||||
| 아침 | 5~11시 |
|
||||
| 낮 | 11시 ~ 일몰 2시간 전 |
|
||||
| 저녁 | 일몰 2시간 전 ~ 일몰 1시간 뒤 |
|
||||
| 밤 | 일몰 1시간 뒤 ~ 다음 날 5시 (0~5시는 전날 밤 구간) |
|
||||
|
||||
한 시간은 그 시각 30분이 속한 구간에 넣습니다. 피드 카드 순서도 같은 구간을 씁니다 (`backend/services/calc/day_slot.py`).
|
||||
|
||||
## 3. 지금 날씨 점수
|
||||
|
||||
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다.
|
||||
|
||||
| 요소 | 비중 | 100점 조건 |
|
||||
|---|---:|---|
|
||||
| 체감온도 (시간 평균) | 30% | 20.5~21.5° (편한 범위 18~24°, 최적 21°, 만점폭 0.5°) |
|
||||
| 비 | 25% | 비 소식 없음, 비 확률 0%대 |
|
||||
| 바람 (가장 센 값) | 10% | 초속 1m 이하 (2m에서 85점, 10m에서 0점) |
|
||||
| 습도 (시간 평균) | 10% | 45~55% (편한 범위 40~60%) |
|
||||
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
|
||||
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
|
||||
|
||||
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다.
|
||||
|
||||
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
|
||||
|
||||
## 4. 각 점수
|
||||
|
||||
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
|
||||
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다.
|
||||
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다.
|
||||
- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'.
|
||||
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
|
||||
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
|
||||
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
|
||||
|
||||
## 5. 나들이 점수 (주말 순위·당일치기)
|
||||
|
||||
토·일 **10~17시** 기준.
|
||||
|
||||
| 요소 | 비중 | 계산 |
|
||||
|---|---:|---|
|
||||
| 비 | 40% | 마른 날 규칙 (1 참고) |
|
||||
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° |
|
||||
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 |
|
||||
| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 |
|
||||
|
||||
- 1처럼 가장 낮은 요소로 깎습니다.
|
||||
- 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**.
|
||||
- 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다.
|
||||
- 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다.
|
||||
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다.
|
||||
|
||||
## 6. 노을 점수
|
||||
|
||||
해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **20km(머리 위)**와 **100km(먼 쪽)** 두 지점에서 봅니다. 예보 모델마다 계산해 평균합니다.
|
||||
|
||||
### 구름 점수
|
||||
|
||||
- 물들 구름 = 20km 지점의 중층·상층 구름 중 큰 값(%)
|
||||
- **물들 정도** = 물들 구름 0%면 0.2 → 50%에서 1.0까지 직선 → 100%에서 0까지 직선
|
||||
- **머리 위 막힘** = 1 − 0.8 × 20km 낮은 구름 ÷ 100
|
||||
- **빛 들어옴** = 1 − min(100km 낮은 구름 + 0.5 × 100km 중층 구름, 100) ÷ 100
|
||||
- **구름 점수 = 100 × (0.75 × 물들 정도 + 0.25 × 머리 위 막힘) × (0.25 + 0.75 × 빛 들어옴)**
|
||||
|
||||
### 공기 보정 (곱함)
|
||||
|
||||
| 조건 | 배수 |
|
||||
|---|---|
|
||||
| 가시거리 (Open-Meteo) | 40km 이상 1.0 → 5km 이하 0.6, 사이 직선 |
|
||||
| 습도 | 50% 이하 1.0 → 90% 이상 0.75, 사이 직선 |
|
||||
| 비 갠 뒤 | 해 지기 2~6시간 전 비 확률 60% 이상이고 그 시각 40% 미만이면 × 1.15 |
|
||||
|
||||
**노을 점수 = min(100, 모델 평균 구름 점수 × 공기 보정)**. 값이 없는 보정은 건너뜁니다.
|
||||
|
||||
### 등급·판정
|
||||
|
||||
- 등급: 80↑ 붉음 · 60↑ 고움 · 40↑ 은은함 · 그 아래 잿빛
|
||||
- 하늘 상황 (모델 평균 구름으로, 위에서부터 먼저 걸리는 것):
|
||||
|
||||
| 상황 | 조건 | 판정 |
|
||||
|---|---|---|
|
||||
| 구름에 가려요 | 100km 낮은 구름 + 0.5 × 중층 ≥ 60 | 쉬어요 |
|
||||
| 낮은 구름이 덮어요 | 20km 낮은 구름 ≥ 60 | 쉬어요 |
|
||||
| 구름이 적어 짧게 끝나요 | 물들 구름 < 25 | 애매해요 |
|
||||
| 구름이 두꺼워 색이 약해요 | 물들 구름 > 75 | 애매해요 |
|
||||
| 하늘이 넓게 물들 수 있어요 | 그 밖 (25~75) | 나가 볼 만해요 |
|
||||
|
||||
- **무엇을 보여 주나**: 다음에 오는 것. 오늘 해 뜨기 전엔 오늘 일출, 그 뒤 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 피드 노을 카드도 같습니다. 일출도 같은 식으로 계산합니다(구름은 해 뜨는 쪽).
|
||||
- 노을 탭 히어로는 답만 보여 줍니다: '오늘은 애매해요'(결론), '18:10쯤 가장 붉어요', 쉬운 말 이유 한 줄(예: 구름은 좋은데 공기가 뿌예서 색이 흐릴 거예요). 더 나은 날이 있으면 바로 아래, 점수·구름·예보 모델 수는 '자세히'에 접어 둡니다.
|
||||
- 점수는 **지금 하늘이 아니라 해 질(뜰) 무렵 예보**로 낸 값입니다. 노을 탭에 "해 질 무렵(18시) 예보 기준"으로 적습니다.
|
||||
- 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**이고, **공기 보정이 0.7배 미만이면 한 단계 낮춥니다.** 이때 이유에 숫자 없이 "먼 건물이 흐릿할 만큼 공기가 뿌옇고 습해서 노을 색이 바래 보일 거예요"(가시거리 20km 미만 = 먼 건물이 흐릿함, 습도 70% 이상 = 습함)를 붙이고, 히어로·피드 카드의 상황 줄도 이 말로 바꿉니다. 예) 분당구 10/12: 구름 57점 × 공기 0.50(가시거리 6.5km 0.62 · 습도 80% 0.81) = 29점 잿빛 → '하늘이 넓게 물들 수 있어요'였던 결론이 '애매해요'로. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요).
|
||||
- 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음.
|
||||
- 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다.
|
||||
|
||||
## 7. 노을 시각
|
||||
|
||||
| 시각 | 정의 |
|
||||
|---|---|
|
||||
| 골든아워 | 해 고도가 **6°**로 내려온 때부터 해 질 때까지. 햇빛이 낮게 비쳐 금빛으로 보이는 시간 |
|
||||
| 해 져요 | 일몰 |
|
||||
| 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 |
|
||||
| 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 |
|
||||
|
||||
노을 시간표는 골든아워 → 해 져요 → 가장 붉을 때 → 블루아워, 일출 시간표는 블루아워(해 뜨기 전 해 고도 −6°) → 가장 붉을 때 → 해 떠요 → 골든아워(해 고도 6°까지 올라오는 때)입니다. 해 짐·뜸은 해 고도 −0.833°, 모두 구 중심 좌표와 날짜로 계산(NOAA 근사식)합니다. '가장 붉을 때'는 해 뜨기 10분 + (상층 구름 % ÷ 10)분 전입니다.
|
||||
|
||||
## 8. 달 모양·잘 보이는지
|
||||
|
||||
'달 밝기 N%'는 쓰지 않습니다. 초승달도 달 자체는 밝게 보이므로, 퍼센트는 밝기가 아니라 모양(빛나는 면)일 뿐이기 때문입니다.
|
||||
|
||||
- **모양**: 달과 해의 황경 차이(0° 삭 → 180° 보름)로 정합니다. 빛나는 면 = (1 − cos 황경 차이) ÷ 2, 모양 이름은 차이 구간으로(삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달). 히어로 달 그림에 씁니다.
|
||||
- **뜨고 지는 시각**: 그날 19시~다음 날 5시를 10분 간격으로 달 고도(Meeus 간이식, 지표 기준)를 계산해 −0.83°를 넘나드는 때.
|
||||
- **잘 보이는지** (위에서부터 먼저 걸리는 것):
|
||||
|
||||
| 조건 | 문구 |
|
||||
|---|---|
|
||||
| 빛나는 면 3% 미만 (삭 무렵) | 해와 같은 쪽에 있어 안 보여요 |
|
||||
| 19시~5시에 한 번도 안 뜸, 차오르는 달 | 해 진 뒤 곧 져서 밤엔 안 보여요 |
|
||||
| 19시~5시에 한 번도 안 뜸, 기우는 달 | 새벽 늦게 떠서 밤엔 안 보여요 |
|
||||
| 저녁 7~9시 사이가 아니라 밤늦게 뜸 | 새벽 2시에 떠요 |
|
||||
| 달이 떠 있는 시각의 하늘이 흐림 쪽 (맑음 0 · 구름많음 0.5 · 흐림 1의 평균 0.6 이상) | 흐려서 구름에 가려요 |
|
||||
| 같은 평균 0.3 이상 | 구름 사이로 보여요 |
|
||||
| 밤사이 짐 | 밤 11시까지 보여요 |
|
||||
| 그 밖 | 밤새 잘 보여요 |
|
||||
|
||||
- 히어로 '오늘 밤 달' 칸: '모양, 잘 보이는지' (예: 상현달, 밤 11시까지 보여요).
|
||||
- 달 포스트: 모양 + 잘 보이는지 + 달 뜸·짐 시각.
|
||||
- 별보기각 '시간' 요소: 달이 비추는 정도 = 빛나는 면 × 21~26시 중 달이 떠 있는 비율, 점수 = 20 + 80 × (1 − 그 값). 근거 문구는 '모양, 잘 보이는지'(구름 제외).
|
||||
|
||||
## 9. 불쾌지수
|
||||
|
||||
- **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3**
|
||||
- 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌
|
||||
@@ -0,0 +1,102 @@
|
||||
# 지역별 예보 HTML 설계
|
||||
|
||||
목표: `/weather/{지역}` 주소로 접속했을 때 서버가 처음 보내는 HTML 본문에 그 지역의 실제 예보가 들어가게 한다.
|
||||
상태: 설계만 했다. 코드는 아직 바꾸지 않았다.
|
||||
|
||||
## 결론
|
||||
|
||||
Next.js로 바꾸거나 Node 서버를 늘 띄워 둘 필요 없다.
|
||||
이미 돌고 있는 Python 백엔드가 요청을 받을 때 HTML을 만들고, 만든 HTML은 Redis에 캐시한다.
|
||||
3시간마다 256개 지역의 HTML 파일을 미리 다시 만드는 방식은 쓰지 않는다. 이유는 다음과 같다.
|
||||
|
||||
- 아무도 보지 않는 지역까지 매번 만들게 된다. 단기예보만 쳐도 하루 약 1,800회(224칸 × 8회) 기상청을 불러야 한다.
|
||||
- worker와 frontend 컨테이너가 같은 폴더를 함께 써야 하고, 다시 만들다 실패했을 때 처리할 일이 따로 생긴다.
|
||||
- 요청할 때 만들면 피드와 같은 캐시 키를 쓰므로, 사용자가 보는 숫자와 HTML 숫자가 같다.
|
||||
|
||||
## 지금 구조 (확인한 것)
|
||||
|
||||
| 항목 | 위치 | 내용 |
|
||||
|---|---|---|
|
||||
| 첫 HTML | `frontend/index.html:105` | `<main>` 안에 정해진 소개 글만 있고, 불러오는 화면(`#boot`)이 그 위를 덮는다 |
|
||||
| 화면 그리기 | `frontend/src/main.tsx:17` | `createRoot`가 `#root`를 통째로 바꾼다. 이어 붙이는 방식(hydrate)이 아니다 |
|
||||
| 예보 데이터 | `frontend/src/b/TodayPage.tsx:350` | 브라우저가 `/v1/feed`, `/v1/weather/today`를 따로 불러온다 |
|
||||
| 지역 | `frontend/src/b/region.tsx:29` | localStorage에 저장된 지역 → 현재 위치 → 마포구 순으로 정한다. 주소에는 지역이 없다 |
|
||||
| 라우트 | `frontend/src/App.tsx:19` | 없는 주소도 `*`가 받아 200으로 오늘 화면을 보여 준다(가짜 404) |
|
||||
| 피드 캐시 | `backend/services/feed_service.py:304`, `:155` | 지역별로 요청이 오면 그때 만들고 `feed:{code}:{slot}`에 저장한다. 저장 기간은 다음 예보 갱신까지, 최대 1시간 |
|
||||
| 지역 수 | `backend/seed/region.csv` | 구 256개, 기상청 격자 224칸 |
|
||||
|
||||
## 동작 흐름
|
||||
|
||||
1. nginx가 `/weather/{code}`와 `/sitemap-regions.xml` 요청을 백엔드로 넘긴다.
|
||||
2. 백엔드는 다음 순서로 HTML을 만든다.
|
||||
- `FeedService.feed()`와 오늘 날씨 데이터를 가져온다. 피드와 같은 서비스, 같은 캐시를 쓴다.
|
||||
- 프론트 빌드 결과인 `index.html`을 틀로 쓴다. 틀은 frontend 컨테이너에서 받아 메모리에 5분 동안 캐시한다.
|
||||
- 틀에서 title, description, og, canonical, `<main>` 부분을 바꾼다.
|
||||
- 페이지 데이터를 `<script type="application/json" id="ssr-data">`에 넣는다.
|
||||
3. `<main>`에 들어갈 내용
|
||||
- H1: "서울 마포구 오늘 날씨"
|
||||
- 날짜, 최저·최고 기온, 강수확률
|
||||
- 3시간 단위 예보 표
|
||||
- 오늘의 각 1~10위와 점수
|
||||
- "10월 13일 14:00 발표 기준" 같은 기준 시각(`issued_at`)
|
||||
- 같은 시·도에 있는 다른 구 링크, 그리고 `/gak`, `/sky`, `/week` 링크
|
||||
4. 지역 페이지에는 `#boot` 덮개를 넣지 않는다. 실제 예보라서 사용자에게 그대로 보여도 된다.
|
||||
5. 브라우저 쪽
|
||||
- React Query가 `ssr-data`를 첫 데이터로 쓴다. 그래서 처음 그린 화면의 숫자가 HTML과 같다. 그 뒤에는 원래 주기대로 새로 불러온다.
|
||||
- 지역은 주소에 있는 지역을 쓴다. 위치 권한은 묻지 않고, 저장해 둔 지역도 덮어쓰지 않는다.
|
||||
- 사용자가 지역을 바꾸면 그 지역의 `/weather/{code}`로 이동한다.
|
||||
- 화면은 지금처럼 `createRoot`가 통째로 바꾸므로 hydration 불일치가 생기지 않는다.
|
||||
|
||||
## 주소, 검색 태그, 404
|
||||
|
||||
- 주소는 `/weather/{region.code}` 형식이다(예: `/weather/1144000000`). 지역 이름은 겹치기 때문이다("중구"가 6곳). 읽기 쉬운 영문 주소가 필요하면 나중에 `region.csv`에 `slug` 칸을 추가한다.
|
||||
- 검색 태그
|
||||
- title: `서울 마포구 오늘 날씨 · 세차각·빨래각 점수 | 날씨각`
|
||||
- description: 오늘 기온, 강수확률, 1위 각을 한 문장으로 쓴다.
|
||||
- canonical: 자기 주소를 가리킨다.
|
||||
- 없는 코드로 들어오면 404 상태 코드와 함께 안내 HTML을 보낸다.
|
||||
- `/sitemap-regions.xml`에 256개 주소를 넣고, `robots.txt`에 `Sitemap:` 줄을 하나 더 추가한다.
|
||||
- 홈 첫 HTML에 시·도별 지역 링크를 넣어 크롤러가 지역 페이지를 찾게 한다.
|
||||
|
||||
## 실패와 기준 시각
|
||||
|
||||
- HTML을 정상적으로 만들 때마다 `ssr:last:{code}`에 만료 없이 저장한다.
|
||||
- 예보를 받아 오거나 계산하다 실패하면 이 마지막 정상본을 보낸다. 마지막 정상본에도 발표 기준 시각이 들어 있다.
|
||||
- 캐시가 비어 있고 첫 요청이 느리면(기상청 응답 대기 1~3초) 마지막 정상본을 먼저 보내고, 새로 만드는 일은 뒤에서 한다.
|
||||
|
||||
## 비용
|
||||
|
||||
- 기상청 호출은 지금 사용자 요청과 같은 경로라서, 늘어나는 건 크롤러가 연 지역만큼이다.
|
||||
- 최악의 경우는 256곳의 캐시가 하루 24번 모두 만료되는 경우다. 이때 단기예보 약 1,800회, 초단기예보 약 5,400회를 부른다.
|
||||
- 저장 공간은 30KB × 256 ≒ 8MB다.
|
||||
|
||||
## 수정할 파일
|
||||
|
||||
| 파일 | 할 일 |
|
||||
|---|---|
|
||||
| `backend/router/ssr.py` (새 파일) | `/weather/{code}`와 `/sitemap-regions.xml` 처리, 404 응답 |
|
||||
| `backend/router/router.py` | 위 라우터 등록 |
|
||||
| `backend/services/region_page.py` (새 파일) | 피드와 오늘 날씨로 HTML 만들기, 틀 캐시, 마지막 정상본 저장과 대체 |
|
||||
| `frontend/nginx.conf` | 위 두 주소를 백엔드로 넘기기 |
|
||||
| `frontend/public/robots.txt` | 지역 sitemap 줄 추가 |
|
||||
| `frontend/index.html` | 시·도별 지역 링크 |
|
||||
| `frontend/src/App.tsx` | `weather/:code` 라우트 추가 |
|
||||
| `frontend/src/b/region.tsx` | 주소의 지역을 먼저 쓰고, 위치 권한 묻기 생략 |
|
||||
| `frontend/src/main.tsx` | `ssr-data`를 React Query 첫 데이터로 넣기 |
|
||||
| `backend/tests/test_region_page.py` (새 파일) | 정상 생성, 404, 실패했을 때 마지막 정상본 테스트 |
|
||||
|
||||
## 위험과 검증
|
||||
|
||||
| 위험 | 검증 |
|
||||
|---|---|
|
||||
| 캐시가 비었을 때 첫 응답이 느림 | `curl -w %{time_total}`로 측정한다. 1초가 넘으면 마지막 정상본을 먼저 보내는지 확인한다 |
|
||||
| HTML과 화면의 숫자가 다름 | `curl`로 받은 본문과 로컬 화면 스크린샷을 비교한다 |
|
||||
| 기상청 하루 호출 한도 | data.go.kr 신청 내역에서 한도를 확인한다(아직 확인 안 함) |
|
||||
| 효과 확인 | 서치 콘솔 "URL 검사 → 크롤링된 페이지 HTML"에 예보 숫자가 있는지 본다. `site:weather.o2o.kr/weather`로 색인된 수를 본다 |
|
||||
|
||||
이 작업으로 순위가 오른다는 보장은 없다. 바뀌는 건 두 가지다. 지역마다 고유한 주소와 본문이 생긴다. 크롤러가 JS를 실행하지 않아도 예보 본문을 읽을 수 있다.
|
||||
|
||||
## 범위 밖 (남은 이슈)
|
||||
|
||||
- `App.tsx`의 `*` 라우트가 없는 주소를 200으로 응답한다(가짜 404).
|
||||
- 지역 주소를 영문(slug)으로 바꿀지 정해야 한다.
|
||||
@@ -0,0 +1,73 @@
|
||||
# 태그·키워드 정의서
|
||||
|
||||
검색 등록을 위해 넣은 HTML 태그, 검색어, 해시태그 사전을 정리한 문서입니다. (10/8 회의 결정: 넣은 태그·키워드는 정의서로 정리해 대표 보고)
|
||||
|
||||
- 기준: 2026년 10월 12일
|
||||
- 적용 파일: `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml`
|
||||
- 상태: ○ 들어가 있음 · △ 문구 검토 중 · ✕ 없음
|
||||
|
||||
## 1. 검색·공유용 HTML 태그
|
||||
|
||||
| 태그 | 내용 | 상태 |
|
||||
|---|---|:---:|
|
||||
| `<title>` | 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 | ○ |
|
||||
| description | 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요. | ○ |
|
||||
| keywords | 2장의 검색어 15개, 쉼표로 구분 | △ |
|
||||
| canonical | https://weather.o2o.kr/ | ○ |
|
||||
| og:site_name | 날씨각 | ○ |
|
||||
| og:title / og:description | title, description과 같음 | ○ |
|
||||
| og:type / og:locale | website / ko_KR | ○ |
|
||||
| og:url | https://weather.o2o.kr/ | ○ |
|
||||
| og:image (+ 크기) | /og.png, 1200×630 | ○ |
|
||||
| og:image:alt | 날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스 | △ |
|
||||
| twitter:card | summary_large_image | ○ |
|
||||
| twitter:title / description / image | og 값과 같음 | △ |
|
||||
| 구글 소유 확인 | google-site-verification | ○ |
|
||||
| 네이버 소유 확인 | naver-site-verification | ○ |
|
||||
| theme-color | #d6ebff | ○ |
|
||||
| manifest | 이름 '날씨각', 색 #d6ebff | △ |
|
||||
|
||||
## 2. 검색어 (keywords 메타)
|
||||
|
||||
검색엔진이 사이트 주제를 파악하는 데 참고합니다. 구글은 거의 보지 않고 다음 등 일부가 참고합니다.
|
||||
|
||||
날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달
|
||||
|
||||
## 3. 해시태그 사전
|
||||
|
||||
서비스 주제를 분류하는 기준 단어입니다. HTML 태그와는 별개이며, SNS 게시물, 블로그 글, 검색 광고 키워드, 앞으로 만들 검색용 페이지 이름에 같은 말을 씁니다. 2장 검색어는 이 사전에서 골랐습니다.
|
||||
|
||||
| 분류 | 해시태그 |
|
||||
|---|---|
|
||||
| 기본 | #날씨각 #오늘날씨 #동네날씨 #날씨지수 |
|
||||
| 오늘의 각 | #세차각 #빨래각 #러닝각 #피크닉각 #산책각 #캠핑각 #등산각 #야장각 #치맥각 #별보기각 |
|
||||
| 노을·하늘 | #오늘노을 #노을시간 #일몰시간 #노을명소 #골든아워 #블루아워 #오늘밤달 |
|
||||
| 주말·행사 | #주말날씨 #주말나들이 #당일치기 #이번주말축제 #전시 #공연 #팝업스토어 |
|
||||
| 생활 날씨 | #미세먼지 #체감온도 #불쾌지수 #기상특보 |
|
||||
| 계절·상식 | #계절소식 #날씨상식 |
|
||||
|
||||
총 34개. 각은 34개 중 검색이 많을 만한 10개만 넣었습니다(전체 목록은 `docs/각_계산기준.md`).
|
||||
|
||||
## 4. 구조화 데이터 (JSON-LD)
|
||||
|
||||
검색엔진과 AI가 사이트를 정확히 이해하도록 넣는 데이터입니다. 화면에는 보이지 않습니다.
|
||||
|
||||
| 종류 | 내용 | 상태 |
|
||||
|---|---|:---:|
|
||||
| WebSite | 이름 날씨각, 주소, 한국어 | ○ |
|
||||
| WebApplication | 날씨 분류, 무료, 한국어 | △ |
|
||||
| Organization | 운영사 이름(날씨각 또는 회사명, 결정 필요), 주소 | △ |
|
||||
| FAQPage | `/faq` 정적 페이지에만 넣음. 원본 `frontend/seo/faq.json` (날씨별 추천·각 기준·이용 안내 20개). 지역 페이지는 본문에 지역 FAQ 5개만 넣고 구조화 데이터는 안 넣음 (앱이 뜨면 사람에겐 안 보이는 글이라) | ○ |
|
||||
|
||||
## 5. 로봇용 소개 본문
|
||||
|
||||
네이버 로봇과 AI 크롤러는 화면을 그리는 스크립트를 실행하지 않아 메타 태그만 읽습니다. 그래서 앱이 뜨기 전 HTML에 서비스 소개 글(오늘의 각, 노을, 주말·행사, 계절·상식)을 넣고, 앱이 뜨면 화면으로 바뀌게 합니다. 상태: △
|
||||
|
||||
## 6. 검색 등록 현황
|
||||
|
||||
| 할 일 | 상태 |
|
||||
|---|:---:|
|
||||
| robots.txt (모든 로봇 허용, sitemap 위치) | ○ |
|
||||
| sitemap.xml (메인 주소 한 줄) | ○ |
|
||||
| 구글 서치 콘솔 등록·sitemap 제출 | 배포 뒤 |
|
||||
| 네이버 서치어드바이저 소유 확인·sitemap 제출 | 배포 뒤 |
|
||||
@@ -0,0 +1,155 @@
|
||||
# 피드 포스트 배경 제작 지시문 (Codex 이미지 생성용)
|
||||
|
||||
- 작성: 2026-10-20
|
||||
- 쓰는 법: 아래 **공통 규격** + **스타일** + 만들 목록(표에서 id와 장면만 골라서)을 합쳐 Codex에 붙여 넣습니다. 한 번에 5~10장씩 나눠 요청합니다.
|
||||
- 실행 예: 저장소 루트에서 `codex exec --sandbox workspace-write -i frontend/public/icons/bike.png "<지시문>"`
|
||||
- `-i` 로 3D 아이콘 한두 장을 **스타일 참고**로 붙이면 질감이 맞춰집니다.
|
||||
- 쓰는 곳: 피드 슬라이드(4:5) 뒤 배경. 위 왼쪽에 작은 머리글+큰 제목, 아래 왼쪽에 큰 주황 점수·이름·주황 버튼, 오른쪽 가운데에 각 3D 아이콘이 올라갑니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 공통 규격 (모든 요청에 붙여 넣기)
|
||||
|
||||
```
|
||||
너는 한국 날씨 웹서비스 '날씨각'의 일러스트레이터야. 아래 목록마다 피드 포스트 배경 그림을 한 장씩 만들어 줘.
|
||||
|
||||
규격
|
||||
- 1080 × 1350 PNG (세로 4:5), 불투명 배경
|
||||
- 글자, 숫자, 로고, 워터마크 넣지 않기
|
||||
- 그 각의 대표 사물(아이콘에 그려진 것)은 그리지 않기. 아이콘은 나중에 위에 따로 얹는다
|
||||
- 사람 얼굴 넣지 않기. 사람이 꼭 필요하면 아주 작은 뒷모습 실루엣까지만
|
||||
- 실존 브랜드·간판 그리지 않기
|
||||
|
||||
글자 자리(꼭 지키기)
|
||||
- 위 왼쪽 약 40%(가로 60% × 세로 40%): 하늘·여백처럼 낮은 대비, 작은 디테일 없음
|
||||
- 아래 왼쪽 약 35%(가로 60% × 세로 35%): 바닥·언덕처럼 평평하고 차분하게
|
||||
- 오른쪽 가운데(가로 55~100%, 세로 30~70%): 비워 두기. 큰 오브젝트 놓지 않기
|
||||
- 장면의 볼거리는 오른쪽 위·오른쪽 아래·가장자리로 보낸다
|
||||
|
||||
결과물
|
||||
- 파일 이름: 아래 목록의 id 그대로 (예: bike.png). 변형이 여럿이면 bike-a.png, bike-b.png …
|
||||
- 행사·포스트 종류 배경은 event-a.png, sunset.png 처럼 표의 id 그대로
|
||||
- 모든 결과를 한 장에 모은 미리보기(contact-sheet.png)
|
||||
- 저장 위치: ./generated-images/post-bg/
|
||||
- 실제로 쓴 프롬프트를 ./generated-images/post-bg/prompts.txt 에 남기기
|
||||
```
|
||||
|
||||
## 2. 스타일 (공통 규격 바로 아래에 붙여 넣기)
|
||||
|
||||
```
|
||||
스타일: 말랑한 파스텔 3D 디오라마 배경
|
||||
- 참고: 붙인 아이콘 이미지는 질감·빛 참고용. 주제는 따라 하지 않기
|
||||
- 재질: 무광 클레이·매끈한 새틴. 둥근 모서리, 단순한 큰 면, 부드러운 그라데이션. 외곽선·사실적 질감 금지
|
||||
- 빛: 왼쪽 위에서 오는 부드러운 빛, 그림자는 옅게
|
||||
- 색: 밝은 파스텔 한 가지 바탕(라일락 #D8CFFC, 하늘 #BFE3FF, 민트 #BFECD6, 버터 #FFE7A0, 피치 #FFD2BB 중 장면에 맞는 것) + 포인트 2~3색. 주황(#FF7A45)은 점수 색과 겹치니 넓게 쓰지 않기
|
||||
- 밤 장면(행사·밤 각): 짙은 남색 #1F2658 → #3D3F86 바탕, 포인트는 노랑·분홍·하늘 빛
|
||||
- 디테일은 적게. 피드에서 작게 보여도 장면이 한눈에 읽히게
|
||||
```
|
||||
|
||||
## 3. 변형 4종 (대표 각·행사에만)
|
||||
|
||||
| 변형 | 낮 각 (예: 자전거각) | 행사 (밤) |
|
||||
|---|---|---|
|
||||
| a | 대표 풍경 (라일락 언덕과 굽은 길) | 도시 야경 스카이라인과 불꽃놀이 |
|
||||
| b | 하늘·물가 (하늘색 강·다리, 해와 구름) | 보라·파랑 빛의 물결 |
|
||||
| c | 지도 느낌 (옅은 지도 위 경로 핀·나무) | 색종이 꽃가루 |
|
||||
| d | 추상 (파스텔 원 겹침) | 어두운 바탕 추상 원 |
|
||||
|
||||
## 4. 각 목록 (68개)
|
||||
|
||||
| id | 각 | 배경 장면 |
|
||||
|---|---|---|
|
||||
| yajang | 야장각 | 저녁 골목, 오른쪽 위 전구 줄과 따뜻한 창 불빛, 남보라 하늘 |
|
||||
| picnic | 피크닉각 | 민트 잔디 언덕과 둥근 나무, 오른쪽 아래 작은 꽃밭, 맑은 하늘 |
|
||||
| chimaek | 치맥각 | 초저녁 강변 공원, 오른쪽 위 가로등과 별 하나 |
|
||||
| walk | 산책각 | 해 진 뒤 가로수길, 둥근 가로등이 이어지는 길 |
|
||||
| vent | 환기각 | 하늘색 바탕에 흩날리는 커튼 자락과 바람 줄기(오른쪽 위) |
|
||||
| hiking | 등산각 | 아침 빛 겹겹이 이어지는 둥근 산 능선, 오른쪽 위 봉우리 |
|
||||
| carwash | 세차각 | 맑게 갠 하늘과 물방울 반짝임, 바닥에 옅은 물웅덩이 |
|
||||
| camping | 캠핑각 | 해 질 녘 숲가 언덕, 오른쪽 아래 소나무 실루엣, 첫 별 |
|
||||
| running | 러닝각 | 아침 강변 트랙이 오른쪽 아래로 휘어 나가는 풍경 |
|
||||
| stars | 별보기각 | 짙은 남색 밤하늘 은하수, 아래 어두운 둥근 언덕 |
|
||||
| jjamppong | 짬뽕각 | 비 오는 창밖 흐린 거리, 유리창 빗방울 |
|
||||
| makgeolli | 막걸리각 | 비 내리는 한옥 처마 끝 빗줄기, 회청색 하늘 |
|
||||
| iced_hot | 뜨아각 | 반은 여름 하늘, 반은 가을 단풍으로 나뉜 하늘 |
|
||||
| laundry | 빨래각 | 쨍한 하늘과 둥실한 흰 구름, 오른쪽 위 작은 해 |
|
||||
| bike | 자전거각 | 라일락 언덕 사이로 굽이치는 길 (변형 4종은 3절) |
|
||||
| dog | 멍뭉산책각 | 민트 잔디 공원 산책로와 둥근 덤불 |
|
||||
| glasses | 김서림각 | 추운 겨울 거리, 따뜻한 가게 창 김 서린 빛 |
|
||||
| makeup | 화장붕괴각 | 후텁지근한 한여름 아지랑이 하늘, 노란 햇빛 |
|
||||
| naengmyeon | 냉면각 | 한여름 쨍한 하늘과 반짝이는 얼음 결정 무늬 |
|
||||
| taxi | 택시대란각 | 비 오는 밤 도시 대로, 번지는 신호등 불빛 |
|
||||
| delivery | 배달폭주각 | 비 오는 밤 아파트 단지 창 불빛 |
|
||||
| garden | 가드닝각 | 버터색 햇살 비치는 작은 텃밭 이랑 |
|
||||
| photo | 사진산책각 | 노을빛 골목길, 피치·라일락 하늘 |
|
||||
| baseball | 야구각 | 저녁 야구장 조명탑 불빛과 초록 잔디(관중 없이) |
|
||||
| study | 공부각 | 비 오는 창가 책상 너머 흐린 바깥 |
|
||||
| netflix | 넷플릭스각 | 어두운 거실 창밖 빗줄기, 은은한 화면 빛 |
|
||||
| chestnut | 군밤각 | 초겨울 저녁 길거리, 노점 불빛 번짐 |
|
||||
| golf | 골프각 | 부드러운 초록 페어웨이 언덕과 맑은 하늘 |
|
||||
| jipkok | 집콕각 | 창밖 잿빛 비, 안쪽은 따뜻한 피치색 방 |
|
||||
| fishing | 낚시각 | 새벽 안개 낀 잔잔한 호수와 둥근 산 |
|
||||
| drive | 드라이브각 | 해안 도로가 오른쪽으로 휘어 가는 맑은 날 |
|
||||
| kite | 연날리기각 | 넓은 하늘색 하늘과 낮은 들판, 바람 줄기 |
|
||||
| waterplay | 물놀이각 | 맑은 바다 물결과 모래사장 가장자리 |
|
||||
| kimjang | 김장각 | 늦가을 시골 마당 장독대(오른쪽 아래), 맑은 하늘 |
|
||||
| flower | 꽃구경각 | 벚꽃 가로수 길, 분홍 꽃잎 흩날림 |
|
||||
| blanket | 이불빨래각 | 옥상 너머 쨍한 하늘과 바람에 흔들리는 구름 |
|
||||
| bingsu | 빙수각 | 한여름 버터색 햇빛과 아지랑이 하늘 |
|
||||
| indoordry | 실내건조각 | 비 오는 날 창 안쪽 흐린 빛, 습한 공기 |
|
||||
| riverwind | 한강밤바람각 | 밤 강가, 다리 불빛이 물에 비친 남색 장면 |
|
||||
| foliage | 단풍각 | 붉고 노란 둥근 단풍 산 |
|
||||
| silvergrass | 억새각 | 해 질 녘 은빛 억새 언덕 |
|
||||
| sweetpotato | 군고구마각 | 초겨울 해 질 녘 골목, 연기 한 줄기 |
|
||||
| sunrise | 해돋이각 | 새벽 바다 수평선 위로 떠오르는 해 빛(오른쪽 위) |
|
||||
| snowman | 눈사람각 | 눈 덮인 둥근 언덕과 흰 하늘 |
|
||||
| bungeoppang | 붕어빵각 | 초겨울 저녁 거리, 노점 따뜻한 불빛 |
|
||||
| tangerine | 귤까먹기각 | 겨울밤 창밖 눈, 안쪽은 따뜻한 방 빛 |
|
||||
| umbrella | 우산각 | 회청색 하늘과 비스듬한 빗줄기 |
|
||||
| pajeon | 파전각 | 비 오는 처마 밑 빗줄기, 따뜻한 창 불빛 |
|
||||
| mood_song | 감성노래각 | 빗방울 맺힌 유리창 너머 번지는 불빛 |
|
||||
| trot | 트로트각 | 봄 나들이 길, 꽃 핀 가로수와 맑은 하늘 |
|
||||
| singing_rain | 싱잉인더레인각 | 비 오는 거리 바닥 물웅덩이에 비친 가로등 |
|
||||
| umbrella_lost | 우산분실각 | 비 그친 뒤 갠 하늘, 물웅덩이와 작은 무지개 |
|
||||
| traffic | 교통체증각 | 비 오는 출근길 도로, 멀리 번지는 차 불빛 |
|
||||
| hangang | 한강각 | 넓은 강과 아치 다리, 강가 잔디, 오후 빛 |
|
||||
| themepark | 놀이공원각 | 멀리 관람차·회전목마 실루엣(오른쪽 위), 맑은 하늘 |
|
||||
| date | 데이트각 | 노을 무렵 강변 산책로와 가로등 |
|
||||
| frizz | 곱슬머리각 | 습한 안개 낀 아침 거리 |
|
||||
| boiler | 보일러각 | 겨울밤 아파트 창 불빛과 서리 |
|
||||
| sunscreen | 선크림각 | 강한 한낮 해와 하얀 모래, 하늘색 바다 |
|
||||
| mosquito | 모기각 | 여름밤 풀숲과 반딧불 같은 작은 빛 |
|
||||
| tennis | 테니스각 | 아침 빛 야외 코트 가장자리 철망과 나무 |
|
||||
| hyodo | 효도각 | 맑은 날 수목원 산책길과 둥근 나무 |
|
||||
| thanks | 감사각 | 저녁 창가, 따뜻한 노을빛 하늘 |
|
||||
| gift | 선물각 | 봄 오후 꽃집 골목, 파스텔 차양 |
|
||||
| party | 파티각 | 저녁 실내 창가, 전구 줄과 남보라 밤하늘 |
|
||||
| game | 게임각 | 어두운 방 창밖 밤 도시, 은은한 보라 빛 |
|
||||
| selfie | 셀카각 | 자연광 가득한 창가, 피치색 햇살 |
|
||||
| sentimental | 센치각 | 저녁 비 그친 골목, 라일락·남색 하늘 |
|
||||
|
||||
## 5. 포스트 종류 배경 (각이 아닌 슬라이드)
|
||||
|
||||
| id | 포스트 종류 | 배경 장면 |
|
||||
|---|---|---|
|
||||
| event-a~d | 가까운 행사 | 3절 행사 변형 4종 (짙은 남색) |
|
||||
| weather | 오늘 날씨 | 하늘색 하늘과 둥근 구름 몇 개 |
|
||||
| sunset | 노을 | 라일락→분홍→주황 노을 하늘, 아래 낮은 도시 실루엣 |
|
||||
| season | 계절 소식 | 계절 나무가 늘어선 둥근 언덕(가을 단풍 기본) |
|
||||
| tip | 날씨 상식 | 하늘색 추상 구름·바람 줄기 |
|
||||
| week | 주말 예보 | 민트 바탕, 멀리 이어지는 언덕 길 |
|
||||
| alert | 생활 알림 | 라일락 바탕 흐린 하늘, 옅은 빗줄기 |
|
||||
| tomorrow | 내일 미리보기 | 해 진 직후 남보라 하늘과 첫 별 |
|
||||
| quote | 오늘의 한 문장 | 피치 바탕 추상 파스텔 원 |
|
||||
| weekend_plan | 주말 플랜 | 버터색 바탕, 나들이 길과 둥근 나무 |
|
||||
| air | 미세먼지 | 맑은 민트 하늘과 바람 줄기 |
|
||||
| day_trip | 당일치기 | 기찻길이 오른쪽 아래로 이어지는 들판 |
|
||||
| moon | 오늘 밤 달 | 짙은 남색 밤하늘, 오른쪽 위 달빛 번짐(달은 작게) |
|
||||
| uv | 자외선 | 강한 버터색 햇살과 하늘 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 받은 뒤 할 일
|
||||
|
||||
- Claude가 확인: 글자 없음, 글자 자리 비어 있음, 오른쪽 가운데 비어 있음, 세트 통일감, 파일 이름·크기
|
||||
- 마음에 안 드는 것만 id로 골라 "bike-c, event-b만 같은 규칙으로 다시" 처럼 다시 요청
|
||||
+7
-7
@@ -35,7 +35,7 @@
|
||||
| 1 | 오늘·내일 날씨 | | 오늘 예보가 있으면 |
|
||||
| 2 | 생활 알림(특보) | | 그 구에 특보가 있을 때 |
|
||||
| 3~5 | 오늘의 각 | 1·2·3위 | 각 점수가 있으면 |
|
||||
| 6 | 노을 | | 노을 계산이 있으면. 하늘 상황으로 말하고, 결론이 '쉬어요'(구름에 가려요·낮은 구름이 덮어요)면 한 줄 카드 |
|
||||
| 6 | 노을 | | 노을 탭 결론과 같은 것(해 뜨기 전·블루아워 뒤엔 일출, 그 사이엔 노을). 하늘 상황으로 말하고, 결론이 '쉬어요'(구름에 가려요·낮은 구름이 덮어요)면 한 줄 카드 |
|
||||
| 7 | 내일 미리보기 | | 저녁·밤에만 |
|
||||
| 8 | 주말 예보 | | 주말 예보가 있으면 |
|
||||
| 9, 13, 14 | 가까운 행사 | 1·2·3번째 | 7일 안에 열리는 행사가 그만큼 있으면 |
|
||||
@@ -45,7 +45,7 @@
|
||||
| 15·16 | 주말 플랜 | 토·일 | 주말 예보가 있으면 |
|
||||
| 17 | 미세먼지 | | 측정값이 3시간 안이면 |
|
||||
| 18 | 당일치기 | | 1~2시간 거리 후보 도시 1위가 있으면 |
|
||||
| 19 | 오늘 밤 달 | | 늘 켜짐. 보름·삭인 밤이면 그 이야기, 아니면 달 모양·밝기·다음 보름 |
|
||||
| 19 | 오늘 밤 달 | | 늘 켜짐. 보름·삭인 밤이면 그 이야기, 아니면 달 모양·잘 보이는지(구름·뜨고 지는 시각)·다음 보름 |
|
||||
|
||||
## 2. 칸 채우기 (누가 열 때, 구마다)
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
**기본 순서 위에 덧붙는 규칙**
|
||||
1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위.
|
||||
2. **금요일 저녁**엔 주말 예보를 노을 바로 다음(2번째)으로 올린다.
|
||||
3. **저녁에 해가 진 뒤**엔 노을 카드가 내일 노을로 바뀌고, 맨 위에서 세 번째로 내려간다.
|
||||
3. **저녁에 해가 진 뒤**엔 노을 카드가 맨 위에서 세 번째로 내려가고, 블루아워가 끝나면 내일 일출 카드로 바뀐다.
|
||||
4. **밤**엔 한 문장을 맨 끝으로.
|
||||
5. **같은 종류가 붙으면** 뒤에서 다른 종류를 당겨 끼운다(각·각·각이 연달아 나오지 않게).
|
||||
6. **행사 카드(최대 3장)**는 위 순서와 따로, "날짜+구"를 씨앗으로 고른 자리에 끼운다. 같은 날 같은 구는 시간대가 바뀌어도 늘 같은 몇 번째 자리에 들어간다.
|
||||
@@ -107,13 +107,13 @@
|
||||
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
|
||||
|
||||
**히어로·띠의 순서**
|
||||
- 오늘의 각 줄(27개)과 띠의 각 순위(5개): 오늘 점수 높은 순.
|
||||
- 히어로 1위 각: 오늘 점수 1위.
|
||||
- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤) 점수 높은 순. 각 시간대가 지금 구간과 안 겹치는 각은 맨 뒤에 '지금 아님'으로.
|
||||
- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 지금 구간에 해당하는 각만, 지금 구간 점수 순.
|
||||
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
|
||||
|
||||
### 같이 만드는 것
|
||||
- 히어로: 지금 기온·체감, 불쾌지수, 날씨 점수, 1위 각, 말풍선, 오늘 밤 달 모양·밝기
|
||||
- 오늘의 각 줄: 27개 이름·점수·순위
|
||||
- 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지
|
||||
- 오늘의 각 줄: 34개 이름·점수·순위 (지금 구간에 안 맞는 각은 '지금 아님')
|
||||
- 띠: 행사 4개, 각 순위 5개, 계절 소식
|
||||
|
||||
## 3. 저장과 갱신
|
||||
|
||||
+72
-5
@@ -15,17 +15,62 @@
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#d6ebff" />
|
||||
<meta name="description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<title>날씨각</title>
|
||||
<meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
|
||||
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="날씨각" />
|
||||
<meta property="og:title" content="날씨각" />
|
||||
<meta property="og:description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
|
||||
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||
<meta property="og:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||
<meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
||||
<meta property="og:locale" content="ko_KR" />
|
||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||
<meta name="naver-site-verification" content="9b97570f87046a31676e01747caf3f527b39ec6d" />
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@graph": [
|
||||
{
|
||||
"@type": "WebSite",
|
||||
"@id": "%VITE_SITE_URL%/#website",
|
||||
"name": "날씨각",
|
||||
"alternateName": ["날씨 각", "Nalssigak"],
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"inLanguage": "ko-KR",
|
||||
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
|
||||
},
|
||||
{
|
||||
"@type": "Organization",
|
||||
"@id": "%VITE_SITE_URL%/#organization",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"logo": "%VITE_SITE_URL%/apple-touch-icon.png"
|
||||
},
|
||||
{
|
||||
"@type": "WebApplication",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
|
||||
"applicationCategory": "WeatherApplication",
|
||||
"operatingSystem": "All",
|
||||
"inLanguage": "ko-KR",
|
||||
"image": "%VITE_SITE_URL%/og.png",
|
||||
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "KRW" },
|
||||
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
|
||||
}
|
||||
]
|
||||
}
|
||||
</script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
@@ -40,7 +85,29 @@
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
|
||||
<div id="boot" data-nosnippet role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
|
||||
<img src="/icons/rabbit.png" alt="" width="88" height="88" />
|
||||
<p style="margin:0">날씨 불러오는 중…</p>
|
||||
</div>
|
||||
<!-- 검색 결과 요약은 화면 글 대신 description 을 쓰게 한다 (지역 페이지는 서버가 오늘 날씨로 채움) -->
|
||||
<div id="root" data-nosnippet>
|
||||
<main>
|
||||
<h1>날씨각</h1>
|
||||
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
||||
<h2><a href="/gak">오늘의 각</a></h2>
|
||||
<p>세차각, 빨래각, 러닝각, 우산각, 파전각처럼 오늘 하고 싶은 일을 지금 동네 날씨로 점수 매겨요. 아침, 낮, 저녁, 밤마다 따로 알려 드려요.</p>
|
||||
<h2><a href="/sky">노을</a></h2>
|
||||
<p>오늘 노을이 얼마나 붉게 물들지, 몇 시에 가장 붉은지, 가까운 노을 명소는 어디인지 알려 드려요. 사흘 치를 미리 볼 수 있어요.</p>
|
||||
<h2><a href="/week">주말·행사</a></h2>
|
||||
<p>이번 주말 날씨와 나들이하기 좋은 곳, 가까운 축제와 전시, 공연을 모아 드려요.</p>
|
||||
<h2><a href="/season">계절·상식</a></h2>
|
||||
<p>지금 계절에 볼 만한 소식과 알아 두면 좋은 날씨 상식을 읽을 수 있어요.</p>
|
||||
<h2><a href="/faq">자주 묻는 질문</a></h2>
|
||||
<p>비 오는 날, 맑은 날, 미세먼지 나쁜 날 뭐 하면 좋을지와 지역별 오늘 날씨 보는 법을 정리했어요.</p>
|
||||
<p>기상청 예보와 에어코리아 미세먼지 정보로 매일 새로 계산해요.</p>
|
||||
</main>
|
||||
</div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user