diff --git a/TODO.md b/TODO.md index db12527..f213860 100644 --- a/TODO.md +++ b/TODO.md @@ -94,7 +94,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 +118,9 @@ | [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) | +| [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,7 +142,7 @@ | [ ] | 각 문서: 강풍 특보 조건이 "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` | @@ -147,4 +155,15 @@ | [ ] | **[결정 필요]** 노을 알림 재검토 — 10/2에 제외했지만 토스 알림은 정보성만 허용돼 "오늘 노을 좋음"이 가장 맞는 알림. 토스판 핵심 후보 | 토스판 전략 검토 | | | [ ] | **[결정 필요]** 히어로 숫자 5개(기온·체감·불쾌지수·날씨 점수·1위 각 점수) — 불쾌지수 여름만, 날씨 점수 유지 여부 | 토스판 전략 검토 | `frontend/src/b/TodayPage.tsx` | | [x] | 토스판 방식 — WebView로 결정(10/12). 별도 프로젝트 없이 `frontend/`에 토스 빌드 모드 추가, RN은 독립 앱만 | 토스판 전략 검토 | `frontend/` | -| [ ] | 앱인토스 appName 정식 이름으로 교체 — 지금은 콘솔 테스트 앱 `weather-gak-test`. 정식 앱 등록 후 두 곳을 같이 바꾸고 `npm run build:toss` 다시 실행 | 콘솔 테스트 앱으로 먼저 등록 | `frontend/apps-in-toss.config.ts`, `frontend/src/lib/platform.ts` | +| [x] | 앱인토스 appName 정식 이름으로 교체 — 콘솔 앱 `nalssigak`으로 맞춤(10/13). 정식 앱 등록 후 두 곳을 같이 바꾸고 `npm run build:toss` 다시 실행 | 콘솔 테스트 앱으로 먼저 등록 | `frontend/apps-in-toss.config.ts`, `frontend/src/lib/platform.ts` | +| [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`) | diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index d28d756..3e2bca0 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.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)) diff --git a/backend/common/utils/text.py b/backend/common/utils/text.py index 7032577..c9ed9db 100644 --- a/backend/common/utils/text.py +++ b/backend/common/utils/text.py @@ -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 문자 참조를 다 푼다. 두 번 인코딩돼 오는 출처도 있어("&lt;") 더 안 바뀔 때까지.""" + while (u := html.unescape(s)) != s: + s = u + return s diff --git a/backend/crud/index_crud.py b/backend/crud/index_crud.py index d408aab..ce43105 100644 --- a/backend/crud/index_crud.py +++ b/backend/crud/index_crud.py @@ -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 diff --git a/backend/crud/sky_crud.py b/backend/crud/sky_crud.py index 0938bf9..cc39202 100644 --- a/backend/crud/sky_crud.py +++ b/backend/crud/sky_crud.py @@ -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()) diff --git a/backend/crud/week_crud.py b/backend/crud/week_crud.py index 80a7a0a..b2ae989 100644 --- a/backend/crud/week_crud.py +++ b/backend/crud/week_crud.py @@ -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"], diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 30eab53..ab8999d 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -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시간 구간을 계산 창에 연결하는 규칙 diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index ce5c456..14452c1 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -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 ( @@ -289,12 +292,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 ( diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index 032d6e8..29e2ceb 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -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): @@ -64,6 +65,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 +84,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 +142,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 +159,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): diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py index 543bc03..c62aef5 100644 --- a/backend/router/v1/index/index.py +++ b/backend/router/v1/index/index.py @@ -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="지수 계산 근거") diff --git a/backend/router/v1/index/protocol.py b/backend/router/v1/index/protocol.py index ae5cdba..1c1ac86 100644 --- a/backend/router/v1/index/protocol.py +++ b/backend/router/v1/index/protocol.py @@ -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] = [] diff --git a/backend/router/v1/sky/protocol.py b/backend/router/v1/sky/protocol.py index b718566..6481ae6 100644 --- a/backend/router/v1/sky/protocol.py +++ b/backend/router/v1/sky/protocol.py @@ -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): diff --git a/backend/router/v1/sky/sky.py b/backend/router/v1/sky/sky.py index e73945c..519b30a 100644 --- a/backend/router/v1/sky/sky.py +++ b/backend/router/v1/sky/sky.py @@ -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], ) diff --git a/backend/router/v1/watch/protocol.py b/backend/router/v1/watch/protocol.py index b957944..4c4d551 100644 --- a/backend/router/v1/watch/protocol.py +++ b/backend/router/v1/watch/protocol.py @@ -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 diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py index ff82612..d66c17e 100644 --- a/backend/router/v1/watch/watch.py +++ b/backend/router/v1/watch/watch.py @@ -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] diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index 37f60de..a14384d 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -52,10 +52,15 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", - "value": 80 + "value": 70 }, { "field": "wind_ms", @@ -71,7 +76,8 @@ "80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻" }, "sort_order": 1, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "picnic", @@ -88,13 +94,13 @@ "to": 16 } ], - "weight_temp": 25, - "weight_rain": 25, + "weight_temp": 20, + "weight_rain": 20, "weight_wind": 15, "weight_humidity": 5, "weight_air": 10, "weight_uv": 10, - "weight_sun": 0, + "weight_sun": 10, "weight_view": 0, "weight_time": 10, "factor_rules": { @@ -127,9 +133,18 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -144,7 +159,15 @@ "80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺" }, "sort_order": 2, - "priority": 1 + "priority": 1, + "months": [ + 3, + 4, + 5, + 9, + 10, + 11 + ] }, { "code": "chimaek", @@ -198,6 +221,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "feels_c", "op": "<", @@ -206,7 +234,7 @@ { "field": "rain_prob", "op": ">=", - "value": 80 + "value": 70 } ], "limit_description": "야구 경기 같은 이벤트는 아직 반영하지 못해요", @@ -217,7 +245,8 @@ "80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗" }, "sort_order": 3, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "walk", @@ -269,10 +298,15 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", - "value": 90 + "value": 70 }, { "field": "pm25", @@ -288,7 +322,8 @@ "80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶" }, "sort_order": 4, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "vent", @@ -320,8 +355,8 @@ "weight_temp": 10, "weight_rain": 15, "weight_wind": 15, - "weight_humidity": 10, - "weight_air": 45, + "weight_humidity": 20, + "weight_air": 35, "weight_uv": 0, "weight_sun": 0, "weight_view": 0, @@ -350,10 +385,27 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "pm25", "op": ">=", "value": 75 + }, + { + "field": "rain_prob", + "op": ">=", + "value": 70, + "cap": 20 + }, + { + "field": "humidity", + "op": ">=", + "value": 85, + "cap": 40 } ], "limit_description": "집 방향과 주변 공사 먼지는 반영하지 못해요", @@ -364,7 +416,8 @@ "80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️" }, "sort_order": 5, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "hiking", @@ -381,13 +434,13 @@ "to": 12 } ], - "weight_temp": 25, - "weight_rain": 25, - "weight_wind": 20, + "weight_temp": 20, + "weight_rain": 20, + "weight_wind": 15, "weight_humidity": 5, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 5, "weight_time": 5, "factor_rules": { @@ -425,9 +478,18 @@ "view": { "zero": 5, "full": 20 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -447,7 +509,15 @@ "80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️" }, "sort_order": 6, - "priority": 1 + "priority": 1, + "months": [ + 3, + 4, + 5, + 9, + 10, + 11 + ] }, { "code": "carwash", @@ -466,12 +536,12 @@ } ], "weight_temp": 5, - "weight_rain": 60, + "weight_rain": 40, "weight_wind": 10, "weight_humidity": 10, "weight_air": 10, - "weight_uv": 0, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -494,9 +564,22 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -512,7 +595,8 @@ "80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨" }, "sort_order": 7, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "camping", @@ -529,10 +613,10 @@ "to": 32 } ], - "weight_temp": 30, + "weight_temp": 40, "weight_rain": 25, "weight_wind": 15, - "weight_humidity": 15, + "weight_humidity": 5, "weight_air": 10, "weight_uv": 0, "weight_sun": 0, @@ -563,6 +647,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -587,7 +676,15 @@ "80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥" }, "sort_order": 8, - "priority": 1 + "priority": 1, + "months": [ + 4, + 5, + 6, + 9, + 10, + 11 + ] }, { "code": "running", @@ -612,8 +709,8 @@ "weight_rain": 20, "weight_wind": 10, "weight_humidity": 15, - "weight_air": 10, - "weight_uv": 5, + "weight_air": 15, + "weight_uv": 0, "weight_sun": 0, "weight_view": 0, "weight_time": 5, @@ -637,13 +734,14 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "feels_c", "op": ">=", @@ -652,7 +750,7 @@ { "field": "rain_prob", "op": ">=", - "value": 90 + "value": 70 } ], "limit_description": "노면 상태는 반영하지 못해요", @@ -663,7 +761,8 @@ "80": "8~18°에 공기 보송, 기록 갱신각 🏃" }, "sort_order": 9, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "stars", @@ -715,10 +814,20 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "cloudy_ratio", "op": ">=", "value": 80 + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60 } ], "limit_description": "도시 불빛은 지역 평균으로만 반영해요", @@ -729,7 +838,15 @@ "80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨" }, "sort_order": 10, - "priority": 2 + "priority": 2, + "months": [ + 9, + 10, + 11, + 12, + 1, + 2 + ] }, { "code": "jjamppong", @@ -739,20 +856,16 @@ "is_fun": true, "is_core": false, "has_detail": true, - "description": "뜨끈한 국물이 당기는 정도", + "description": "오전 9시~자정, 뜨끈한 국물이 당기는 정도", "windows": [ { - "from": 11, - "to": 14 - }, - { - "from": 17, - "to": 20 + "from": 9, + "to": 24 } ], - "weight_temp": 40, + "weight_temp": 50, "weight_rain": 25, - "weight_wind": 15, + "weight_wind": 5, "weight_humidity": 10, "weight_air": 5, "weight_uv": 0, @@ -788,7 +901,8 @@ "80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜" }, "sort_order": 11, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "makgeolli", @@ -798,16 +912,16 @@ "is_fun": true, "is_core": false, "has_detail": true, - "description": "비 오는 날 파전에 막걸리가 당기는 정도", + "description": "오전 9시~자정, 비 오는 날 파전에 막걸리가 당기는 정도", "windows": [ { - "from": 17, - "to": 22 + "from": 9, + "to": 24 } ], "weight_temp": 15, - "weight_rain": 50, - "weight_wind": 10, + "weight_rain": 55, + "weight_wind": 5, "weight_humidity": 15, "weight_air": 5, "weight_uv": 0, @@ -845,7 +959,8 @@ "80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶" }, "sort_order": 12, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "iced_hot", @@ -862,11 +977,11 @@ "to": 10 } ], - "weight_temp": 50, - "weight_rain": 10, - "weight_wind": 15, - "weight_humidity": 10, - "weight_air": 5, + "weight_temp": 90, + "weight_rain": 0, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, "weight_uv": 0, "weight_sun": 0, "weight_view": 0, @@ -900,7 +1015,8 @@ "80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕" }, "sort_order": 13, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "laundry", @@ -951,6 +1067,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -965,7 +1086,8 @@ "80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️" }, "sort_order": 14, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "bike", @@ -982,13 +1104,13 @@ "to": 19 } ], - "weight_temp": 25, - "weight_rain": 25, - "weight_wind": 25, + "weight_temp": 20, + "weight_rain": 20, + "weight_wind": 20, "weight_humidity": 5, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -1021,9 +1143,18 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -1048,7 +1179,8 @@ "80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲" }, "sort_order": 15, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "dog", @@ -1069,12 +1201,12 @@ "to": 20 } ], - "weight_temp": 35, + "weight_temp": 40, "weight_rain": 25, "weight_wind": 10, "weight_humidity": 5, "weight_air": 15, - "weight_uv": 5, + "weight_uv": 0, "weight_sun": 0, "weight_view": 0, "weight_time": 5, @@ -1101,13 +1233,14 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "feels_c", "op": ">=", @@ -1122,6 +1255,12 @@ "field": "ground_c", "op": ">=", "value": 45 + }, + { + "field": "rain_prob", + "op": ">=", + "value": 70, + "cap": 20 } ], "limit_description": "지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요", @@ -1132,7 +1271,8 @@ "80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶" }, "sort_order": 16, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "glasses", @@ -1149,10 +1289,10 @@ "to": 9 } ], - "weight_temp": 50, + "weight_temp": 70, "weight_rain": 10, - "weight_wind": 5, - "weight_humidity": 30, + "weight_wind": 0, + "weight_humidity": 15, "weight_air": 0, "weight_uv": 0, "weight_sun": 0, @@ -1187,7 +1327,8 @@ "80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓" }, "sort_order": 17, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "makeup", @@ -1204,9 +1345,9 @@ "to": 18 } ], - "weight_temp": 40, - "weight_rain": 10, - "weight_wind": 10, + "weight_temp": 55, + "weight_rain": 5, + "weight_wind": 0, "weight_humidity": 35, "weight_air": 0, "weight_uv": 0, @@ -1242,7 +1383,8 @@ "80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠" }, "sort_order": 18, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "naengmyeon", @@ -1259,10 +1401,10 @@ "to": 14 } ], - "weight_temp": 55, + "weight_temp": 65, "weight_rain": 15, "weight_wind": 5, - "weight_humidity": 15, + "weight_humidity": 5, "weight_air": 5, "weight_uv": 0, "weight_sun": 0, @@ -1299,7 +1441,12 @@ "80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶" }, "sort_order": 19, - "priority": 3 + "priority": 3, + "months": [ + 6, + 7, + 8 + ] }, { "code": "taxi", @@ -1316,10 +1463,10 @@ "to": 26 } ], - "weight_temp": 15, - "weight_rain": 55, - "weight_wind": 10, - "weight_humidity": 5, + "weight_temp": 20, + "weight_rain": 65, + "weight_wind": 0, + "weight_humidity": 0, "weight_air": 0, "weight_uv": 0, "weight_sun": 0, @@ -1328,7 +1475,7 @@ "factor_rules": { "temp": { "type": "lower", - "zero": 15, + "zero": 25, "full": -5 }, "rain": { @@ -1356,7 +1503,8 @@ "80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕" }, "sort_order": 20, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "delivery", @@ -1374,19 +1522,19 @@ } ], "weight_temp": 20, - "weight_rain": 50, - "weight_wind": 10, - "weight_humidity": 5, - "weight_air": 5, + "weight_rain": 65, + "weight_wind": 5, + "weight_humidity": 0, + "weight_air": 0, "weight_uv": 0, "weight_sun": 0, "weight_view": 0, "weight_time": 10, "factor_rules": { "temp": { - "type": "lower", - "zero": 22, - "full": 0 + "type": "away", + "lo": 10, + "hi": 25 }, "rain": { "dir": "wet" @@ -1414,7 +1562,8 @@ "80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵" }, "sort_order": 21, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "garden", @@ -1431,13 +1580,13 @@ "to": 10 } ], - "weight_temp": 25, - "weight_rain": 30, + "weight_temp": 20, + "weight_rain": 25, "weight_wind": 10, - "weight_humidity": 15, + "weight_humidity": 10, "weight_air": 10, - "weight_uv": 5, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -1467,9 +1616,18 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -1484,7 +1642,8 @@ "80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱" }, "sort_order": 22, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "photo", @@ -1539,10 +1698,15 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", - "value": 80 + "value": 70 } ], "limit_description": "장소 혼잡도는 반영하지 못해요", @@ -1553,7 +1717,8 @@ "80": "노을 점수 높고 공기 맑음, 인생샷 각 📸" }, "sort_order": 23, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "baseball", @@ -1570,10 +1735,10 @@ "to": 22 } ], - "weight_temp": 25, - "weight_rain": 40, + "weight_temp": 35, + "weight_rain": 35, "weight_wind": 10, - "weight_humidity": 5, + "weight_humidity": 0, "weight_air": 10, "weight_uv": 0, "weight_sun": 0, @@ -1606,6 +1771,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -1620,7 +1790,17 @@ "80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾" }, "sort_order": 24, - "priority": 3 + "priority": 3, + "months": [ + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10 + ] }, { "code": "study", @@ -1630,16 +1810,16 @@ "is_fun": true, "is_core": false, "has_detail": true, - "description": "오후 1~6시, 밖에 나가기 싫어서 공부가 잘되는 정도", + "description": "오전 9시~자정, 밖에 나가기 싫어서 공부가 잘되는 정도", "windows": [ { - "from": 13, - "to": 18 + "from": 9, + "to": 24 } ], - "weight_temp": 35, + "weight_temp": 40, "weight_rain": 35, - "weight_wind": 10, + "weight_wind": 5, "weight_humidity": 5, "weight_air": 5, "weight_uv": 0, @@ -1667,6 +1847,10 @@ "sun": 50, "holiday": 50, "default": 100 + }, + "air": { + "zero": 15, + "full": 75 } }, "zero_rules": [], @@ -1678,7 +1862,8 @@ "80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚" }, "sort_order": 25, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "netflix", @@ -1688,17 +1873,17 @@ "is_fun": true, "is_core": false, "has_detail": true, - "description": "밤 8시~자정, 집에서 영화 보기 좋은 정도", + "description": "오전 9시~자정, 집에서 영화 보기 좋은 정도", "windows": [ { - "from": 20, + "from": 9, "to": 24 } ], "weight_temp": 30, - "weight_rain": 35, - "weight_wind": 15, - "weight_humidity": 5, + "weight_rain": 50, + "weight_wind": 5, + "weight_humidity": 0, "weight_air": 0, "weight_uv": 0, "weight_sun": 0, @@ -1735,7 +1920,8 @@ "80": "비 오는 주말 앞 밤, 정주행 시작각 🍿" }, "sort_order": 26, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "chestnut", @@ -1752,9 +1938,9 @@ "to": 21 } ], - "weight_temp": 55, + "weight_temp": 60, "weight_rain": 25, - "weight_wind": 10, + "weight_wind": 5, "weight_humidity": 0, "weight_air": 5, "weight_uv": 0, @@ -1781,7 +1967,14 @@ "value": 100 } }, - "zero_rules": [], + "zero_rules": [ + { + "field": "feels_c", + "op": ">=", + "value": 18, + "cap": 20 + } + ], "limit_description": "군밤 노점이 있는지는 반영하지 못해요", "sentences": { "0": "아직 18° 넘어요. 군밤은 조금 더 추워지면!", @@ -1790,7 +1983,14 @@ "80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰" }, "sort_order": 27, - "priority": 3 + "priority": 3, + "months": [ + 10, + 11, + 12, + 1, + 2 + ] }, { "code": "golf", @@ -1849,6 +2049,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -1873,7 +2078,8 @@ "80": "15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳" }, "sort_order": 28, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "jipkok", @@ -1883,16 +2089,16 @@ "is_fun": true, "is_core": false, "has_detail": true, - "description": "오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도", + "description": "오전 9시~자정, 나가기 싫어 집에 있고 싶은 정도", "windows": [ { - "from": 10, - "to": 18 + "from": 9, + "to": 24 } ], - "weight_temp": 30, + "weight_temp": 35, "weight_rain": 30, - "weight_wind": 10, + "weight_wind": 5, "weight_humidity": 5, "weight_air": 20, "weight_uv": 0, @@ -1935,7 +2141,8 @@ "80": "비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️" }, "sort_order": 29, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "fishing", @@ -1991,6 +2198,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -2015,7 +2227,8 @@ "80": "12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣" }, "sort_order": 30, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "drive", @@ -2074,10 +2287,15 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", - "value": 70, + "value": 60, "cap": 20 } ], @@ -2089,7 +2307,8 @@ "80": "공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗" }, "sort_order": 31, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "kite", @@ -2139,6 +2358,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -2154,6 +2378,12 @@ "op": "<", "value": 1, "cap": 30 + }, + { + "field": "wind_ms", + "op": ">=", + "value": 8, + "cap": 50 } ], "limit_description": "전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요", @@ -2164,7 +2394,8 @@ "80": "초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁" }, "sort_order": 32, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "waterplay", @@ -2221,6 +2452,11 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "rain_prob", "op": ">=", @@ -2240,7 +2476,12 @@ "80": "30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️" }, "sort_order": 33, - "priority": 2 + "priority": 2, + "months": [ + 6, + 7, + 8 + ] }, { "code": "kimjang", @@ -2293,10 +2534,21 @@ } }, "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, { "field": "feels_c", "op": ">=", "value": 18 + }, + { + "field": "rain_prob", + "op": ">=", + "value": 70, + "cap": 40 } ], "limit_description": "배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요", @@ -2307,6 +2559,1176 @@ "80": "0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬" }, "sort_order": 34, - "priority": 3 + "priority": 3, + "months": [ + 11, + 12 + ] + }, + { + "code": "flower", + "name": "꽃구경각", + "icon": "flower", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 10시~오후 5시, 꽃 보러 나들이 가기 좋은 정도", + "windows": [ + { + "from": 10, + "to": 17 + } + ], + "weight_temp": 20, + "weight_rain": 25, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 15, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 5, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 14, + "hi": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 10 + }, + "humidity": { + "type": "ignore" + }, + "sun": { + "zero": 0.2, + "full": 0.8 + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "꽃이 피었는지(개화 시기)는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 꽃구경은 다음 맑은 날로!", + "30": "쌀쌀하거나 공기가 탁해요. 잠깐 보고 오기 좋아요.", + "60": "꽃 보러 나가기 괜찮은 날이에요.", + "80": "햇살 좋고 바람 잔잔, 꽃길 걷기 딱 좋아요 🌸" + }, + "sort_order": 35, + "priority": 2, + "months": [ + 3, + 4, + 5 + ] + }, + { + "code": "blanket", + "name": "이불빨래각", + "icon": "blanket", + "category": 3, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "이불처럼 두꺼운 빨래가 하루 만에 마르는 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 10, + "weight_rain": 30, + "weight_wind": 15, + "weight_humidity": 15, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 0, + "weight_time": 0, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 8, + "full": 22 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "lower" + }, + "sun": { + "zero": 0.3, + "full": 0.9 + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 40 + } + ], + "limit_description": "베란다 방향·햇빛 드는 시간은 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 이불은 다음에!", + "30": "두꺼운 건 덜 마를 수 있어요. 얇은 이불만!", + "60": "이불 널기 괜찮은 날이에요. 오후에 한 번 뒤집어요.", + "80": "햇볕 쨍쨍에 바람 솔솔, 이불 빨래하는 날 ☀️" + }, + "sort_order": 36, + "priority": 2, + "months": [ + 3, + 4, + 5, + 6, + 9, + 10, + 11 + ] + }, + { + "code": "bingsu", + "name": "빙수각", + "icon": "bingsu", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 1~6시, 시원한 빙수가 당기는 정도", + "windows": [ + { + "from": 13, + "to": 18 + } + ], + "weight_temp": 70, + "weight_rain": 10, + "weight_wind": 5, + "weight_humidity": 10, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 22, + "full": 33 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "higher" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "아직 선선해요. 빙수는 더운 날에!", + "30": "시원한 게 살짝 당기는 정도예요.", + "60": "오후가 덥네요. 빙수 한 그릇 생각나요!", + "80": "푹푹 찌는 오후, 팥빙수 확정 🍧" + }, + "sort_order": 37, + "priority": 3, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "indoordry", + "name": "실내건조각", + "icon": "indoordry", + "category": 3, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "밖에 못 너는 날, 집 안에서 빨래 말리기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 21 + } + ], + "weight_temp": 15, + "weight_rain": 60, + "weight_wind": 0, + "weight_humidity": 20, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 15, + "full": 28 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "lower" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": "<", + "value": 40, + "cap": 20 + } + ], + "limit_description": "집 안 습도·환기·제습기 여부는 반영하지 못해요", + "sentences": { + "0": "밖에 널어도 되는 날이에요. 빨래각을 봐요!", + "30": "눅눅해서 실내에서도 잘 안 말라요. 선풍기를 같이 틀어요.", + "60": "비 와도 실내에선 그럭저럭 말라요.", + "80": "비는 오지만 덜 습해서, 실내 건조로 충분해요 👕" + }, + "sort_order": 38, + "priority": 3, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "riverwind", + "name": "한강밤바람각", + "icon": "riverwind", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "저녁 7~11시, 강가에서 밤바람 쐬기 좋은 정도", + "windows": [ + { + "from": 19, + "to": 23 + } + ], + "weight_temp": 30, + "weight_rain": 30, + "weight_wind": 20, + "weight_humidity": 10, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 20, + "hi": 28, + "best": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "range", + "lo": 40, + "hi": 75, + "best": 55 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "강가 모기·혼잡도는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 오늘 밤은 집에서!", + "30": "바람이 없거나 너무 눅눅해요. 잠깐만 나가요.", + "60": "밤바람 쐬러 나가기 괜찮아요.", + "80": "선선한 바람 솔솔, 강가 돗자리 각 🌙" + }, + "sort_order": 39, + "priority": 2, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "foliage", + "name": "단풍각", + "icon": "maple", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 9시~오후 4시, 단풍 구경 가기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 15, + "weight_rain": 25, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 15, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 10, + "hi": 22 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "ignore" + }, + "sun": { + "zero": 0.2, + "full": 0.8 + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "단풍이 얼마나 물들었는지는 반영하지 못해요. 계절 소식의 단풍 시기를 같이 봐요", + "sentences": { + "0": "비 소식이 있어요. 단풍은 다음 맑은 날로!", + "30": "하늘이 흐리거나 뿌예서 색이 덜 살아요.", + "60": "단풍 보러 가기 괜찮은 날이에요.", + "80": "하늘 맑고 멀리까지 잘 보여요, 단풍 나들이 각 🍁" + }, + "sort_order": 40, + "priority": 2, + "months": [ + 10, + 11 + ] + }, + { + "code": "silvergrass", + "name": "억새각", + "icon": "sheaf", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "해 지기 전후, 억새밭 걷기 좋은 정도", + "windows": [ + { + "around": "sunset", + "hours": 2 + } + ], + "weight_temp": 10, + "weight_rain": 25, + "weight_wind": 15, + "weight_humidity": 0, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 10, + "weight_time": 30, + "factor_rules": { + "temp": { + "type": "range", + "lo": 10, + "hi": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "ignore" + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "sunset_score" + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 70 + } + ], + "limit_description": "억새밭 위치·개화 정도는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 억새는 다음에!", + "30": "노을이 약하거나 하늘이 흐려요. 낮에 잠깐 보고 와요.", + "60": "해 질 무렵 억새 보러 가기 괜찮아요.", + "80": "바람에 일렁이는 억새에 노을까지, 사진 각 🌾" + }, + "sort_order": 41, + "priority": 3, + "months": [ + 9, + 10, + 11 + ] + }, + { + "code": "sweetpotato", + "name": "군고구마각", + "icon": "sweet_potato", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 4~9시, 따끈한 군고구마가 당기는 정도", + "windows": [ + { + "from": 16, + "to": 21 + } + ], + "weight_temp": 65, + "weight_rain": 20, + "weight_wind": 5, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 18, + "full": 2 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "아직 포근해요. 군고구마는 더 추워지면!", + "30": "저녁이 선선해졌어요. 군고구마가 슬슬 생각나요.", + "60": "쌀쌀한 저녁, 군고구마 한 봉지 어때요?", + "80": "찬 바람 부는 저녁, 호호 불어 먹는 군고구마 🍠" + }, + "sort_order": 42, + "priority": 3, + "months": [ + 10, + 11, + 12, + 1, + 2 + ] + }, + { + "code": "sunrise", + "name": "해돋이각", + "icon": "sunset", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "해 뜰 무렵, 해돋이 보러 가기 좋은 정도", + "windows": [ + { + "around": "sunrise", + "hours": 1 + } + ], + "weight_temp": 10, + "weight_rain": 20, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 15, + "weight_time": 40, + "factor_rules": { + "temp": { + "type": "higher", + "zero": -15, + "full": 5, + "label": "덜 추움" + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "ignore" + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "sunrise_score" + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes" + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "바다·산처럼 동쪽이 트인 곳인지는 반영하지 못해요", + "sentences": { + "0": "비나 눈 소식이 있어요. 해돋이는 다음에!", + "30": "구름이 많아 해가 가려질 수 있어요.", + "60": "해돋이 보러 가기 괜찮아요. 따뜻하게 입어요.", + "80": "하늘 맑고 멀리까지 보여요, 해돋이 각 🌅" + }, + "sort_order": 43, + "priority": 2, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "snowman", + "name": "눈사람각", + "icon": "snow", + "category": 1, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "눈 온 날 낮, 눈사람 만들기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 50, + "weight_rain": 10, + "weight_wind": 20, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 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": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "snow", + "op": "==", + "value": "no" + }, + { + "field": "feels_c", + "op": ">=", + "value": 4, + "cap": 30 + }, + { + "field": "feels_c", + "op": "<", + "value": -10, + "cap": 40 + } + ], + "limit_description": "쌓인 눈의 양은 반영하지 못해요. 눈 오는 시간만 봐요", + "sentences": { + "0": "눈 소식이 없어요. 눈사람은 눈 오는 날에!", + "30": "눈은 오지만 너무 춥거나 녹아서 잘 안 뭉쳐요.", + "60": "눈사람 만들기 괜찮아요. 장갑 꼭 챙겨요.", + "80": "포슬포슬 잘 뭉쳐지는 눈, 눈사람 각 ⛄" + }, + "sort_order": 44, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "bungeoppang", + "name": "붕어빵각", + "icon": "bungeoppang", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 3~9시, 붕어빵이 당기는 정도", + "windows": [ + { + "from": 15, + "to": 21 + } + ], + "weight_temp": 70, + "weight_rain": 15, + "weight_wind": 5, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 12, + "full": -5 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "붕어빵 노점이 있는지는 반영하지 못해요", + "sentences": { + "0": "아직 덜 추워요. 붕어빵은 더 추워지면!", + "30": "쌀쌀해졌어요. 붕어빵 노점이 생각나요.", + "60": "손이 시려요. 붕어빵 한 봉지 어때요?", + "80": "꽁꽁 언 오후, 따끈한 붕어빵 확정 🐟" + }, + "sort_order": 45, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "tangerine", + "name": "귤까먹기각", + "icon": "tangerine", + "category": 3, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "저녁 7시~자정, 이불 속에서 귤 까먹고 싶은 정도", + "windows": [ + { + "from": 19, + "to": 24 + } + ], + "weight_temp": 75, + "weight_rain": 5, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 12, + "full": -5 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "밤이 포근해요. 산책이라도 나가 봐요!", + "30": "살짝 쌀쌀한 밤, 귤 한두 개 생각나요.", + "60": "추운 밤이에요. 이불 속 귤 까먹기 좋아요.", + "80": "바람 쌩쌩 추운 밤, 귤 한 상자 각 🍊" + }, + "sort_order": 46, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "umbrella", + "name": "우산각", + "icon": "umbrella", + "category": 4, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 6시~자정, 밖에 나갈 때 우산을 챙겨야 하는 정도", + "windows": [ + { + "from": 6, + "to": 24 + } + ], + "weight_temp": 0, + "weight_rain": 90, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 10, + "factor_rules": { + "temp": { + "type": "range", + "lo": 0, + "hi": 40 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "소나기처럼 갑자기 오는 비는 놓칠 수 있어요", + "sentences": { + "0": "하늘이 말짱해요. 우산은 두고 가도 돼요.", + "30": "비 소식이 조금 있어요. 작은 우산 하나 챙기면 든든해요.", + "60": "비가 와요. 우산 꼭 챙기세요.", + "80": "비가 제법 쏟아져요. 큰 우산에 신발도 신경 써요." + }, + "sort_order": 47, + "priority": 2, + "months": [] + }, + { + "code": "pajeon", + "name": "파전각", + "icon": "pajeon", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오전 9시~자정, 비 오는 날 파전이 당기는 정도", + "windows": [ + { + "from": 9, + "to": 24 + } + ], + "weight_temp": 20, + "weight_rain": 70, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 10, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 26, + "full": 10 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "실제 판매량으로 검증하기 전이에요", + "sentences": { + "0": "맑은 날엔 파전보다 바깥 나들이!", + "30": "꾸물꾸물한 하늘, 파전 생각이 슬슬 나요.", + "60": "빗소리 들리면 파전 부칠 시간이에요.", + "80": "지글지글 빗소리, 오늘은 무조건 파전!" + }, + "sort_order": 48, + "priority": 3, + "months": [] + }, + { + "code": "mood_song", + "name": "감성노래각", + "icon": "rain", + "category": 3, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오전 9시~자정, 비 오는 날 감성 노래 듣기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 24 + } + ], + "weight_temp": 25, + "weight_rain": 60, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 15, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 26, + "full": 8 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "음악 취향은 반영하지 못해요", + "sentences": { + "0": "쨍한 날엔 신나는 노래가 더 어울려요.", + "30": "구름 낀 하늘, 잔잔한 노래 한 곡 어때요?", + "60": "창밖에 빗소리, 플레이리스트 꺼낼 시간이에요.", + "80": "빗소리에 옛날 노래까지, 감성 가득한 밤이에요." + }, + "sort_order": 49, + "priority": 3, + "months": [] + }, + { + "code": "trot", + "name": "트로트각", + "icon": "trot", + "category": 1, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오전 10시~오후 5시, 나들이 가며 트로트 크게 틀고 싶은 정도", + "windows": [ + { + "from": 10, + "to": 17 + } + ], + "weight_temp": 30, + "weight_rain": 25, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 15, + "weight_view": 0, + "weight_time": 30, + "factor_rules": { + "temp": { + "type": "range", + "lo": 15, + "hi": 25 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "sun": { + "zero": 0.2, + "full": 0.9 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 40 + } + }, + "zero_rules": [ + { + "field": "rain", + "op": "==", + "value": "yes", + "cap": 20 + } + ], + "limit_description": "노래 취향은 반영하지 못해요", + "sentences": { + "0": "오늘은 조용히 집에서 쉬어요.", + "30": "날은 그럭저럭, 흥얼흥얼 한 곡만.", + "60": "볕 좋은 날, 꺾기 한 소절 나와요.", + "80": "관광버스 부르는 날씨, 트로트 메들리 시작!" + }, + "sort_order": 50, + "priority": 3, + "months": [] + }, + { + "code": "singing_rain", + "name": "싱잉인더레인각", + "icon": "singing_rain", + "category": 1, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오전 6시~자정, 비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도", + "windows": [ + { + "from": 6, + "to": 24 + } + ], + "weight_temp": 30, + "weight_rain": 50, + "weight_wind": 15, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 15, + "hi": 25 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "calm", + "ok": 3, + "limit": 10 + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "빗길 미끄러움은 반영하지 못해요", + "sentences": { + "0": "비가 없어요. 노래는 다음 비 오는 날에!", + "30": "빗방울은 조금, 콧노래 정도만.", + "60": "우산 들고 첨벙첨벙 걷기 좋은 비예요.", + "80": "포근한 빗속, 우산 돌리며 노래하고 싶은 날!" + }, + "sort_order": 51, + "priority": 3, + "months": [] } -] \ No newline at end of file +] diff --git a/backend/services/calc/day_slot.py b/backend/services/calc/day_slot.py new file mode 100644 index 0000000..b15cf4e --- /dev/null +++ b/backend/services/calc/day_slot.py @@ -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 diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 6a54a30..4dcc185 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -54,6 +54,8 @@ class Context: sunset_score: Optional[int] wind_warning: bool lookahead_rain_prob: int + moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 + sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각) @dataclass(frozen=True) @@ -115,7 +117,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 +199,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 +229,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 +249,19 @@ 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 "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면" base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}" return f"{base}이라", f"{base}이거나", f"{base}이면" @@ -332,6 +342,8 @@ 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)), } reason, cap = _zero(definition.zero_rules, agg) if reason is not None: @@ -350,7 +362,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 +392,9 @@ 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"} + 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] diff --git a/backend/services/calc/moon.py b/backend/services/calc/moon.py index 84e9d12..040d4a1 100644 --- a/backend/services/calc/moon.py +++ b/backend/services/calc/moon.py @@ -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}시" diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index 9cfb0f6..7cb9c6b 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -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] + diff --git a/backend/services/calc/sun.py b/backend/services/calc/sun.py index 8c81eee..ca57015 100644 --- a/backend/services/calc/sun.py +++ b/backend/services/calc/sun.py @@ -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), ) diff --git a/backend/services/external/kma.py b/backend/services/external/kma.py index 76c3c52..d933c52 100644 --- a/backend/services/external/kma.py +++ b/backend/services/external/kma.py @@ -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 ] diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 2e5b9d8..9e57a41 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -11,9 +11,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 +21,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 @@ -88,7 +88,6 @@ _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory _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 +117,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 +131,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 +152,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) @@ -247,7 +236,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: @@ -371,7 +361,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 +373,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 +418,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 @@ -503,7 +498,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 +517,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 +629,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 +647,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) @@ -757,7 +755,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: diff --git a/backend/services/hero_stats.py b/backend/services/hero_stats.py index 02b501c..cfb75f8 100644 --- a/backend/services/hero_stats.py +++ b/backend/services/hero_stats.py @@ -10,10 +10,12 @@ from services.air_service import GRADE_LABEL Tone = Literal["normal", "warn", "rain"] UV_HIGH = 6.0 +MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값 +DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다 +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 +40,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]: + """히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 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 and x.now.month in DISCOMFORT_MONTHS: + 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 +85,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 +99,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] = [] diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 97d3b9a..d586207 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -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,65 @@ 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 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 +299,71 @@ 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 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 +382,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) + 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, **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 diff --git a/backend/services/now_service.py b/backend/services/now_service.py index a835064..3e53cdf 100644 --- a/backend/services/now_service.py +++ b/backend/services/now_service.py @@ -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) diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py index e963618..8b20637 100644 --- a/backend/services/sky_service.py +++ b/backend/services/sky_service.py @@ -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), diff --git a/backend/services/weather_service.py b/backend/services/weather_service.py index 045d073..44ec8c4 100644 --- a/backend/services/weather_service.py +++ b/backend/services/weather_service.py @@ -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,14 +15,14 @@ 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 @@ -31,6 +32,14 @@ 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 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 5857661..4b433f2 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -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", diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py new file mode 100644 index 0000000..b34f7bb --- /dev/null +++ b/backend/tests/test_day_slot.py @@ -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) diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index cac8684..78cb188 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -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 @@ -261,7 +275,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 +285,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 +294,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(): @@ -367,6 +384,9 @@ 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 diff --git a/backend/tests/test_hero_stats.py b/backend/tests/test_hero_stats.py index d7b0cc0..4749aff 100644 --- a/backend/tests/test_hero_stats.py +++ b/backend/tests/test_hero_stats.py @@ -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,28 @@ 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_only_june_to_september(): + """불쾌지수는 더위 지표라 10월 비 오는 날에도 '쾌적'이 나온다. 기상청처럼 6~9월에만.""" + 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)) == [] diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 5dbbdc0..936788d 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -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, diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 8c144a6..ff95e2f 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -259,7 +259,52 @@ 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 + + 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": "덜 추움"}}) == "덜 추움" diff --git a/backend/tests/test_index_season.py b/backend/tests/test_index_season.py new file mode 100644 index 0000000..623b176 --- /dev/null +++ b/backend/tests/test_index_season.py @@ -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]] + diff --git a/backend/tests/test_moon.py b/backend/tests/test_moon.py index a686495..7f3a4c7 100644 --- a/backend/tests/test_moon.py +++ b/backend/tests/test_moon.py @@ -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("에 떠요") diff --git a/backend/tests/test_now_parse.py b/backend/tests/test_now_parse.py index b4e4cc7..09e8d4d 100644 --- a/backend/tests/test_now_parse.py +++ b/backend/tests/test_now_parse.py @@ -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] diff --git a/backend/tests/test_resilience.py b/backend/tests/test_resilience.py index 68651ae..7dab31d 100644 --- a/backend/tests/test_resilience.py +++ b/backend/tests/test_resilience.py @@ -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), diff --git a/backend/tests/test_seoul_culture.py b/backend/tests/test_seoul_culture.py index c430251..d7af6ba 100644 --- a/backend/tests/test_seoul_culture.py +++ b/backend/tests/test_seoul_culture.py @@ -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층") diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py index 6881b3a..659a887 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -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, []) diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index 6bae052..33b08b3 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -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) == "아침 노을이 거의 안 보여요" diff --git a/backend/tests/test_watch.py b/backend/tests/test_watch.py index 9c9ab0a..ebbe43c 100644 --- a/backend/tests/test_watch.py +++ b/backend/tests/test_watch.py @@ -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 diff --git a/backend/tests/test_weather_now.py b/backend/tests/test_weather_now.py index 24137ba..e58402e 100644 --- a/backend/tests/test_weather_now.py +++ b/backend/tests/test_weather_now.py @@ -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) diff --git a/deploy.sh b/deploy.sh index 1987c04..9dadf32 100755 --- a/deploy.sh +++ b/deploy.sh @@ -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:?덤프 파일 경로가 필요합니다}" diff --git a/docs/QA_체크리스트.md b/docs/QA_체크리스트.md index 8115f94..2c52aa1 100644 --- a/docs/QA_체크리스트.md +++ b/docs/QA_체크리스트.md @@ -1,6 +1,6 @@ # 기능 QA 체크리스트 (휴대폰) -아이폰 Safari와 안드로이드 Chrome에서 http://<킹서버>:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다. +아이폰 Safari와 안드로이드 Chrome에서 테스트 서버(:30040) 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다. ## 0. 처음 들어가기 diff --git a/docs/meetings/2026-10-08.md b/docs/meetings/2026-10-08.md new file mode 100644 index 0000000..9dba73b --- /dev/null +++ b/docs/meetings/2026-10-08.md @@ -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개월, 담당 미정) diff --git a/docs/서비스_동작_안내.md b/docs/서비스_동작_안내.md new file mode 100644 index 0000000..036b5fe --- /dev/null +++ b/docs/서비스_동작_안내.md @@ -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`에 있습니다. diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md new file mode 100644 index 0000000..341a8ac --- /dev/null +++ b/docs/점수_계산식.md @@ -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 미만 불쾌 · 그 이상 매우 불쾌 diff --git a/docs/태그_키워드_정의서.md b/docs/태그_키워드_정의서.md new file mode 100644 index 0000000..1d9a38a --- /dev/null +++ b/docs/태그_키워드_정의서.md @@ -0,0 +1,73 @@ +# 태그·키워드 정의서 + +검색 등록을 위해 넣은 HTML 태그, 검색어, 해시태그 사전을 정리한 문서입니다. (10/8 회의 결정: 넣은 태그·키워드는 정의서로 정리해 대표 보고) + +- 기준: 2026년 10월 12일 +- 적용 파일: `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` +- 상태: ○ 들어가 있음 · △ 문구 검토 중 · ✕ 없음 + +## 1. 검색·공유용 HTML 태그 + +| 태그 | 내용 | 상태 | +|---|---|:---:| +| `` | 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 | ○ | +| 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 | 자주 묻는 질문 7개 | △ | + +## 5. 로봇용 소개 본문 + +네이버 로봇과 AI 크롤러는 화면을 그리는 스크립트를 실행하지 않아 메타 태그만 읽습니다. 그래서 앱이 뜨기 전 HTML에 서비스 소개 글(오늘의 각, 노을, 주말·행사, 계절·상식)을 넣고, 앱이 뜨면 화면으로 바뀌게 합니다. 상태: △ + +## 6. 검색 등록 현황 + +| 할 일 | 상태 | +|---|:---:| +| robots.txt (모든 로봇 허용, sitemap 위치) | ○ | +| sitemap.xml (메인 주소 한 줄) | ○ | +| 구글 서치 콘솔 등록·sitemap 제출 | 배포 뒤 | +| 네이버 서치어드바이저 소유 확인·sitemap 제출 | 배포 뒤 | diff --git a/docs/피드_동작방식.md b/docs/피드_동작방식.md index b297b78..1a752ed 100644 --- a/docs/피드_동작방식.md +++ b/docs/피드_동작방식.md @@ -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. 저장과 갱신 diff --git a/frontend/index.html b/frontend/index.html index a82db1c..07663b6 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -15,17 +15,74 @@ <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>날씨각 + + + 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 + - - + + + + + + + + + + + -
+ +
+ +

날씨 불러오는 중…

+
+
+
+

날씨각

+

오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.

+

오늘의 각

+

세차각, 빨래각, 러닝각, 우산각, 파전각처럼 오늘 하고 싶은 일을 지금 동네 날씨로 점수 매겨요. 아침, 낮, 저녁, 밤마다 따로 알려 드려요.

+

노을

+

오늘 노을이 얼마나 붉게 물들지, 몇 시에 가장 붉은지, 가까운 노을 명소는 어디인지 알려 드려요. 사흘 치를 미리 볼 수 있어요.

+

주말·행사

+

이번 주말 날씨와 나들이하기 좋은 곳, 가까운 축제와 전시, 공연을 모아 드려요.

+

계절·상식

+

지금 계절에 볼 만한 소식과 알아 두면 좋은 날씨 상식을 읽을 수 있어요.

+

기상청 예보와 에어코리아 미세먼지 정보로 매일 새로 계산해요.

+
+
diff --git a/frontend/nginx.conf b/frontend/nginx.conf index fbf100e..3c207a6 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -31,9 +31,9 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } - # SPA: /indices, /sky 같은 주소로 새로고침해도 index.html을 돌려준다 + # SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403) location / { add_header Cache-Control "no-cache"; - try_files $uri $uri/ /index.html; + try_files $uri $uri.html /index.html; } } diff --git a/frontend/public/5d75f7cb25f648da8cd5dc1c71f1af66.txt b/frontend/public/5d75f7cb25f648da8cd5dc1c71f1af66.txt new file mode 100644 index 0000000..6ed844e --- /dev/null +++ b/frontend/public/5d75f7cb25f648da8cd5dc1c71f1af66.txt @@ -0,0 +1 @@ +5d75f7cb25f648da8cd5dc1c71f1af66 \ No newline at end of file diff --git a/frontend/public/icons/bingsu.png b/frontend/public/icons/bingsu.png new file mode 100644 index 0000000..d7eb436 Binary files /dev/null and b/frontend/public/icons/bingsu.png differ diff --git a/frontend/public/icons/blanket.png b/frontend/public/icons/blanket.png new file mode 100644 index 0000000..444294e Binary files /dev/null and b/frontend/public/icons/blanket.png differ diff --git a/frontend/public/icons/bungeoppang.png b/frontend/public/icons/bungeoppang.png new file mode 100644 index 0000000..ce08b2a Binary files /dev/null and b/frontend/public/icons/bungeoppang.png differ diff --git a/frontend/public/icons/flower.png b/frontend/public/icons/flower.png new file mode 100644 index 0000000..98cb43c Binary files /dev/null and b/frontend/public/icons/flower.png differ diff --git a/frontend/public/icons/indoordry.png b/frontend/public/icons/indoordry.png new file mode 100644 index 0000000..d55991b Binary files /dev/null and b/frontend/public/icons/indoordry.png differ diff --git a/frontend/public/icons/pajeon.png b/frontend/public/icons/pajeon.png new file mode 100644 index 0000000..3b0b6d2 Binary files /dev/null and b/frontend/public/icons/pajeon.png differ diff --git a/frontend/public/icons/riverwind.png b/frontend/public/icons/riverwind.png new file mode 100644 index 0000000..ef28fa6 Binary files /dev/null and b/frontend/public/icons/riverwind.png differ diff --git a/frontend/public/icons/singing_rain.png b/frontend/public/icons/singing_rain.png new file mode 100644 index 0000000..1e39988 Binary files /dev/null and b/frontend/public/icons/singing_rain.png differ diff --git a/frontend/public/icons/trot.png b/frontend/public/icons/trot.png new file mode 100644 index 0000000..d74d953 Binary files /dev/null and b/frontend/public/icons/trot.png differ diff --git a/frontend/public/manifest.webmanifest b/frontend/public/manifest.webmanifest new file mode 100644 index 0000000..fea580a --- /dev/null +++ b/frontend/public/manifest.webmanifest @@ -0,0 +1,14 @@ +{ + "name": "날씨각", + "short_name": "날씨각", + "description": "오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 이번 주말 가까운 축제까지.", + "lang": "ko-KR", + "start_url": "/", + "display": "standalone", + "background_color": "#d6ebff", + "theme_color": "#d6ebff", + "icons": [ + { "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" }, + { "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png" } + ] +} diff --git a/frontend/public/privacy.html b/frontend/public/privacy.html new file mode 100644 index 0000000..b411cb8 --- /dev/null +++ b/frontend/public/privacy.html @@ -0,0 +1,60 @@ + + + + + +개인정보처리방침 - 날씨각 + + + + +
+

개인정보처리방침

+

시행일: 2026년 10월 13일

+ +

AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹")와 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.

+ +

1. 수집하는 개인정보와 목적

+ + + + + +
구분항목목적
웹 회원가입·로그인아이디, 비밀번호(암호화 저장), 닉네임 / Google 로그인 시 Google 계정 고유 식별자회원 식별, 좋아요·저장·댓글 기능 제공
웹·워치 앱 위치대략적인 위치(위도·경도)가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.
서비스 이용접속 기록(IP 주소, 접속 시각, 브라우저 정보), 선택한 지역서비스 운영, 오류 확인, 이용 통계
+

위치 권한은 선택 사항입니다. 허용하지 않아도 지역을 직접 골라 이용할 수 있습니다. 워치 앱은 회원가입이나 로그인 없이 이용할 수 있습니다.

+ +

2. 보유 및 이용 기간

+

회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.

+ +

3. 제3자 제공 및 처리 위탁

+

회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.

+ +

4. 파기 절차 및 방법

+

보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.

+ +

5. 이용자의 권리

+

이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다.

+ +

6. 안전성 확보 조치

+

비밀번호는 암호화하여 저장하고, 개인정보에 접근할 수 있는 인원을 최소한으로 제한합니다.

+ +

7. 아동의 개인정보

+

회사는 만 14세 미만 아동의 개인정보를 알면서 수집하지 않습니다.

+ +

8. 개인정보 보호책임자

+

운영자: AIO2O
이메일: o2odev@o2o.kr

+ +

9. 변경 안내

+

이 방침이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.

+
+ + diff --git a/frontend/public/robots.txt b/frontend/public/robots.txt new file mode 100644 index 0000000..b550c4b --- /dev/null +++ b/frontend/public/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Allow: / + +Sitemap: https://weather.o2o.kr/sitemap.xml diff --git a/frontend/public/sitemap.xml b/frontend/public/sitemap.xml new file mode 100644 index 0000000..87e7843 --- /dev/null +++ b/frontend/public/sitemap.xml @@ -0,0 +1,8 @@ + + + https://weather.o2o.kr/2026-10-13 + https://weather.o2o.kr/gak2026-10-13 + https://weather.o2o.kr/sky2026-10-13 + https://weather.o2o.kr/week2026-10-13 + https://weather.o2o.kr/season2026-10-13 + diff --git a/frontend/seo/gak.json b/frontend/seo/gak.json new file mode 100644 index 0000000..3693a79 --- /dev/null +++ b/frontend/seo/gak.json @@ -0,0 +1,206 @@ +[ + { + "name": "야장각", + "description": "바깥 자리에 앉기 좋은 정도" + }, + { + "name": "피크닉각", + "description": "낮 동안 돗자리 펴고 쉬기 좋은 정도" + }, + { + "name": "치맥각", + "description": "저녁에 바깥에서 치킨과 맥주가 당기는 정도" + }, + { + "name": "산책각", + "description": "걷기 좋은 정도 (해 진 뒤 기준)" + }, + { + "name": "환기각", + "description": "창문 열어 공기 바꾸기 좋은 정도" + }, + { + "name": "등산각", + "description": "산에 오르기 좋은 정도 (오전 기준)" + }, + { + "name": "세차각", + "description": "세차한 뒤 깨끗함이 오래가는 정도" + }, + { + "name": "캠핑각", + "description": "하룻밤 캠핑하기 좋은 정도" + }, + { + "name": "러닝각", + "description": "뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)" + }, + { + "name": "별보기각", + "description": "밤하늘 별이 잘 보이는 정도" + }, + { + "name": "짬뽕각", + "description": "뜨끈한 국물이 당기는 정도" + }, + { + "name": "막걸리각", + "description": "비 오는 날 파전에 막걸리가 당기는 정도" + }, + { + "name": "뜨아각", + "description": "아이스 대신 따뜻한 커피로 바꿀 때가 된 정도" + }, + { + "name": "빨래각", + "description": "빨래가 잘 마르는 정도" + }, + { + "name": "자전거각", + "description": "자전거 타기 좋은 정도" + }, + { + "name": "멍뭉산책각", + "description": "반려견과 산책하기 좋은 정도" + }, + { + "name": "김서림각", + "description": "안경에 김이 서리기 쉬운 정도" + }, + { + "name": "화장붕괴각", + "description": "화장이 무너지기 쉬운 정도" + }, + { + "name": "냉면각", + "description": "시원한 냉면이 당기는 정도" + }, + { + "name": "택시대란각", + "description": "밤늦게 택시 잡기 어려운 정도" + }, + { + "name": "배달폭주각", + "description": "배달 주문이 몰리는 정도" + }, + { + "name": "가드닝각", + "description": "화분 돌보고 물 주기 좋은 정도" + }, + { + "name": "사진산책각", + "description": "노을 무렵 사진 찍으며 걷기 좋은 정도" + }, + { + "name": "야구각", + "description": "야구장 직관하기 좋은 정도" + }, + { + "name": "공부각", + "description": "밖에 나가기 싫어서 공부가 잘되는 정도" + }, + { + "name": "넷플릭스각", + "description": "집에서 영화 보기 좋은 정도" + }, + { + "name": "군밤각", + "description": "길거리 군밤이 당기는 정도" + }, + { + "name": "골프각", + "description": "필드에서 라운딩하기 좋은 정도" + }, + { + "name": "집콕각", + "description": "나가기 싫어 집에 있고 싶은 정도" + }, + { + "name": "낚시각", + "description": "물가에서 낚시하기 좋은 정도" + }, + { + "name": "드라이브각", + "description": "창문 열고 드라이브하기 좋은 정도" + }, + { + "name": "연날리기각", + "description": "연 날리기 좋은 정도" + }, + { + "name": "물놀이각", + "description": "바다·계곡에서 물놀이하기 좋은 정도" + }, + { + "name": "김장각", + "description": "김장하기 좋은 정도" + }, + { + "name": "꽃구경각", + "description": "꽃 보러 나들이 가기 좋은 정도" + }, + { + "name": "이불빨래각", + "description": "이불처럼 두꺼운 빨래가 하루 만에 마르는 정도" + }, + { + "name": "빙수각", + "description": "시원한 빙수가 당기는 정도" + }, + { + "name": "실내건조각", + "description": "밖에 못 너는 날, 집 안에서 빨래 말리기 좋은 정도" + }, + { + "name": "한강밤바람각", + "description": "강가에서 밤바람 쐬기 좋은 정도" + }, + { + "name": "단풍각", + "description": "단풍 구경 가기 좋은 정도" + }, + { + "name": "억새각", + "description": "해 지기 전후, 억새밭 걷기 좋은 정도" + }, + { + "name": "군고구마각", + "description": "따끈한 군고구마가 당기는 정도" + }, + { + "name": "해돋이각", + "description": "해 뜰 무렵, 해돋이 보러 가기 좋은 정도" + }, + { + "name": "눈사람각", + "description": "눈 온 날 낮, 눈사람 만들기 좋은 정도" + }, + { + "name": "붕어빵각", + "description": "붕어빵이 당기는 정도" + }, + { + "name": "귤까먹기각", + "description": "이불 속에서 귤 까먹고 싶은 정도" + }, + { + "name": "우산각", + "description": "밖에 나갈 때 우산을 챙겨야 하는 정도" + }, + { + "name": "파전각", + "description": "비 오는 날 파전이 당기는 정도" + }, + { + "name": "감성노래각", + "description": "비 오는 날 감성 노래 듣기 좋은 정도" + }, + { + "name": "트로트각", + "description": "나들이 가며 트로트 크게 틀고 싶은 정도" + }, + { + "name": "싱잉인더레인각", + "description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도" + } +] diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 4cd028a..1cb695b 100644 --- a/frontend/src/api/client/@tanstack/react-query.gen.ts +++ b/frontend/src/api/client/@tanstack/react-query.gen.ts @@ -150,7 +150,7 @@ export const getSkyRankingOptions = (options?: Options) => qu export const listIndicesQueryKey = (options: Options) => createQueryKey('listIndices', options); /** - * 지수 목록 (점수순, 1~3위, 오늘 날씨 점수) + * 지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수) */ export const listIndicesOptions = (options: Options) => queryOptions>({ queryFn: async ({ queryKey, signal }) => { diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index 943204f..bb70c7a 100644 --- a/frontend/src/api/client/index.ts +++ b/frontend/src/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; diff --git a/frontend/src/api/client/sdk.gen.ts b/frontend/src/api/client/sdk.gen.ts index feb504e..3e6ebe7 100644 --- a/frontend/src/api/client/sdk.gen.ts +++ b/frontend/src/api/client/sdk.gen.ts @@ -49,7 +49,7 @@ export const getSky = (options: Options(options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/sky/ranking', ...options }); /** - * 지수 목록 (점수순, 1~3위, 오늘 날씨 점수) + * 지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수) */ export const listIndices = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/index/list', ...options }); diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index e28896c..17f3389 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -1,7 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { - baseUrl: `${string}://openapi.gen.json` | (string & {}); + baseUrl: `${string}://${string}` | (string & {}); }; /** @@ -230,6 +230,12 @@ export type BestTime = { * Label */ label: string; + /** + * End + * + * 구간이면 끝 시각 (골든아워·블루아워) + */ + end?: string | null; }; /** @@ -561,8 +567,16 @@ export type Hero = { * Feels C */ feels_c?: number | null; + /** + * Humidity + * + * 지금 습도 %. 히어로에 늘 보인다 + */ + humidity?: number | null; /** * Discomfort + * + * 지금 불쾌지수. 히어로에 늘 보인다 */ discomfort?: number | null; /** @@ -581,6 +595,14 @@ export type Hero = { * Weather Score */ weather_score?: number | null; + /** + * Weather Slots + * + * 오늘 구간별 날씨 점수 {morning·day·evening·night: 점수} + */ + weather_slots?: { + [key: string]: number; + }; top1?: TopIndex | null; /** * Bubble @@ -595,15 +617,21 @@ export type Hero = { /** * Moon Pct * - * 달이 밝게 보이는 비율 0~100 + * 달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님) */ moon_pct?: number | null; /** * Stats * - * 히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저 + * 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저 */ stats?: Array; + /** + * Status + * + * 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로) + */ + status?: Array; }; /** @@ -727,6 +755,18 @@ export type IndexSummary = { * Is Core */ is_core: boolean; + /** + * Season + * + * 지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음 + */ + season?: string | null; + /** + * In Season + * + * false 면 제철이 아니라 순위 밖, 목록 맨 끝 + */ + in_season?: boolean; /** * Score */ @@ -743,6 +783,24 @@ export type IndexSummary = { * Trend */ trend?: Array; + /** + * Active + * + * 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수 + */ + active?: boolean; + /** + * Slot + * + * score 가 어느 구간 점수인지 (지금 구간) + */ + slot?: string | null; + /** + * Slots + * + * 오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음 + */ + slots?: Array; }; /** @@ -1440,6 +1498,8 @@ export type ResIndexList = { day?: string | null; /** * Weather Score + * + * 지금 날씨 점수 (지금 구간 기준) */ weather_score?: number | null; /** @@ -1667,6 +1727,12 @@ export type ResSky = { */ spots?: Array; plan?: SkyPlanData | null; + /** + * Plans + * + * plan 과 같은 종류로 아직 안 끝난 날 최대 3일 (날짜 타일, 누르면 그날로) + */ + plans?: Array; }; /** @@ -1871,6 +1937,12 @@ export type Row = { * 위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다) */ place?: string | null; + /** + * Level + * + * 자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다 + */ + level?: number | null; }; /** @@ -2008,6 +2080,18 @@ export type SkyGrade = typeof SkyGrade[keyof typeof SkyGrade]; * SkyPlanData */ export type SkyPlanData = { + /** + * Kind + * + * 다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을 + */ + kind: 'sunset' | 'sunrise'; + /** + * Title + * + * 하늘이 어떻게 보일지 한 문장 (오늘 노을은 물들긴 하는데 색이 흐릴 거예요). 히어로 제목 + */ + title: string; /** * Day */ @@ -2154,6 +2238,28 @@ export const SkyType = { /** */ export type SkyType = typeof SkyType[keyof typeof SkyType]; +/** + * SlotPoint + */ +export type SlotPoint = { + /** + * Slot + * + * morning / day / evening / night + */ + slot: string; + /** + * Label + * + * 아침 / 낮 / 저녁 / 밤 + */ + label: string; + /** + * Score + */ + score: number; +}; + /** * SlotTone */ @@ -2245,6 +2351,18 @@ export type SunsetSlide = { * 하늘 상황. 앱이 카드 하늘 색을 고른다 */ situation?: SkySituation | null; + /** + * Headline + * + * 결론 (나가 볼 만해요 · 애매해요 · 쉬어요). 카드 맨 위에 크게 + */ + headline?: string | null; + /** + * Peak At + * + * 가장 붉을 때 + */ + peak_at?: string | null; }; /** @@ -2311,6 +2429,28 @@ export type TopIndex = { * Summary */ summary?: string | null; + /** + * Active + * + * 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수 + */ + active?: boolean; + /** + * Slots + * + * 오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음 + */ + slots?: { + [key: string]: number; + }; + /** + * Slot Ranks + * + * 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음 + */ + slot_ranks?: { + [key: string]: number; + }; }; /** @@ -2632,6 +2772,34 @@ export type WeekDay = { * Rain Prob */ rain_prob?: number | null; + /** + * Gaks + * + * 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음 + */ + gaks?: Array; +}; + +/** + * WeekGak + */ +export type WeekGak = { + /** + * Index Id + */ + index_id: number; + /** + * Name + */ + name: string; + /** + * Icon + */ + icon: string; + /** + * Score + */ + score: number; }; /** @@ -2921,7 +3089,7 @@ export type ListIndicesData = { /** * Core * - * 이번 계절 핵심 지수만 + * 지금 제철인 각만 */ core?: boolean; }; diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index b7fe706..9b52c03 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -1,8 +1,10 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { NavLink, Outlet, useLocation } from 'react-router' +import { useIsFetching, useQuery } from '@tanstack/react-query' +import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen' import { SOCIAL } from '../lib/platform' import { cx } from '../lib/utils' -import { kindOfHour, kst, type TimeKind } from './lib' +import { kindOfHour, kst, seasonOf, type TimeKind } from './lib' import './b.css' import { AuthProvider } from './auth' import { RegionProvider } from './region' @@ -12,7 +14,7 @@ import { useSheet } from './sheetContext' import { SheetProvider } from './Sheets' import { SkyContext, useSky } from './skyContext' import { PinIcon, TabIcon } from './svg' -import { Avatar, Skel } from './ui' +import { Avatar, Ic, Skel } from './ui' const TABS = [ { to: '/sky', key: 'sky', label: '노을', title: '노을' }, @@ -23,6 +25,22 @@ const TABS = [ { to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' }, ] as const +/** 로고 옆 계절 칩: 계절 이름과 지금 절기. 누르면 이번 주 절기 창. 좁은 화면에선 절기를 뺀다 */ +function SeasonChip() { + const { open } = useSheet() + const week = useQuery(getSeasonWeekOptions()) + const [month] = useState(() => kst(new Date()).mo) + const [name, icon] = seasonOf(month) + const term = week.data?.term_now?.name + return ( + + ) +} + function TopBar() { const { pathname } = useLocation() const { region, locateStatus } = useRegion() @@ -32,7 +50,8 @@ function TopBar() { return (
- {tab?.title ?

{tab.title}

:

날씨각

} + {tab?.title ?

{tab.title}

:

날씨각

} + ) })} diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 53daf3f..b65fd72 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -131,10 +131,9 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) { return (
{slide.eyebrow} - - - - 노을 점수 {slide.score} + {/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유. 점수는 노을 탭 '자세히'에 */} + {slide.headline ?? slide.grade_label} + {slide.line &&

{slide.line}

}
{slide.cuts.map((c, i) => (
@@ -154,7 +153,8 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) { -
+ {/* 칸은 제목 바로 아래, 팁만 맨 아래로. 칸을 바닥에 붙이면 가운데가 비어 덜 그려진 화면처럼 보인다 */} +
{slide.days.map((d) => (
@@ -167,10 +167,22 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) { 비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`} + {d.gaks && d.gaks.length > 0 && ( +
    +
  • 이날 할 만한 각
  • + {d.gaks.map((g) => ( +
  • + + {g.name} + {g.score} +
  • + ))} +
+ )}
))}
- {slide.tip &&

{slide.tip}

} + {slide.tip &&

{slide.tip}

}
) if (slide.kind === 'plan') { diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 673720b..840f950 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -158,6 +158,8 @@ function Swap({ labels, at }: { labels: readonly ReactNode[]; at: number }) { /* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */ const N3 = [0, 1, 2] const N4 = [0, 1, 2, 3] +const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const +const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const const N6 = [0, 1, 2, 3, 4, 5] const N14 = Array.from({ length: 14 }, (_, i) => i) @@ -349,8 +351,9 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)

{g.name}

{d.description &&

{d.description}

}
- {g.score} + {g.score}
+ {!g.active &&

지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.

} {now && (

{now.low}~{now.high}점 @@ -358,6 +361,23 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)

)} {factors.length > 2 && } + {g.slots && g.slots.length > 0 && ( +
+ {SLOT_KEYS.map((k) => { + const s = g.slots?.find((x) => x.slot === k) + const cur = g.active && g.slot === k + return ( +
+ + {SLOT_NAMES[k]} + {cur && ' · 지금'} + + {s ? s.score : '–'} +
+ ) + })} +
+ )} {g.trend && g.trend.length > 0 && (
{g.trend.map((t) => ( @@ -386,7 +406,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
{f.label} - + 비중 {f.weight}%

{f.note}

diff --git a/frontend/src/b/SkyPage.tsx b/frontend/src/b/SkyPage.tsx index ebefac8..ed68999 100644 --- a/frontend/src/b/SkyPage.tsx +++ b/frontend/src/b/SkyPage.tsx @@ -1,5 +1,5 @@ import { useQuery } from '@tanstack/react-query' -import type { ReactNode } from 'react' +import { useState, type ReactNode } from 'react' import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen' import type { BestTime, SkyPlanData } from '../api/client/types.gen' import { cx } from '../lib/utils' @@ -31,48 +31,104 @@ function LiSkel({ ghost = false }: { ghost?: boolean }) { // 다른 탭 히어로보다 짧게. 배경은 하늘 상황별 색(b-sit-1~5), 아래에 동네 실루엣 const HERO = 'relative mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px-5 pt-5 pb-14 text-white' const THREE = [0, 1, 2] +const FOUR = [0, 1, 2, 3] const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i) -/** 히어로엔 해 지는 시각과 하늘 상황 한 줄만. 결론·이유는 아래 카드로 */ -function HeroBody({ plan, sunset }: { plan?: SkyPlanData; sunset?: string }) { +/** 점수 등급별 하늘색: 히어로 배경과 3일 타일이 같은 색. b-keep-bg 는 밤 화면에서도 이 색을 지킨다 */ +const GRADE_SKY: Record = { + 잿빛: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#6f7690,#9aa0b4_55%,#b9b4c0)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#8f8aa5,#b9b0bf)]' }, + 은은함: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4b5aa8,#7f86c6_40%,#e9b9a8_78%,#ffb27a)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#7f86c6,#e9b9a8_70%,#f6b07a)]' }, + 고움: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#5b3f9e,#c2559a_45%,#ff7a6a_78%,#ffb35c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#5b3f9e,#c2559a_55%,#ff7a6a)]' }, + 붉음: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4a2a8a,#b0306a_40%,#ff4a3a_72%,#ff9a3c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#4a2a8a,#b0306a_50%,#ff4a3a)]' }, +} +const skyOf = (p?: SkyPlanData) => GRADE_SKY[p?.grade_label ?? ''] ?? GRADE_SKY['은은함'] + +/** 히어로엔 답만: 등급에 따라 노을 피크 시각과 어떻게 물드는지, 잿빛이면 왜 안 보이는지 */ +function HeroBody({ plan }: { plan?: SkyPlanData }) { const v = (node: ReactNode, w: string) => (plan ? node : ) return (
-

{v(sunset && clockShort(sunset), 'w-[150px]')}

-

{v(plan?.situation_label ?? plan?.headline, 'w-[190px]')}

+

{v(plan?.title, 'w-[230px]')}

+ {(!plan || plan.situation_label) &&

{v(plan?.situation_label, 'w-[180px]')}

}
) } -/** 결론과 이유, 예보 모델이 얼마나 같은 예보를 냈는지, 점수(작게) */ -function Verdict({ plan }: { plan?: SkyPlanData }) { - const v = (node: ReactNode, w: string) => (plan ? node : ) - const agree = plan?.models_total ? `예보 모델 ${plan.models_total}개 중 ${plan.models_agree}개가 같은 예보` : '' +/** 오늘·내일·모레를 그날 예상 하늘색 타일로. 누르면 그날로 */ +function DayTiles({ plans, day, onPick }: { plans: SkyPlanData[]; day?: string; onPick: (day: string) => void }) { return ( -
-

- {v(plan?.headline, 'w-20')} - {v(plan?.reason, 'w-[220px]')} +

+ {plans.map((p) => ( + + ))} +
+ ) +} + +/** 노을 점수 뜻. 지금 하늘이 아니라 해 질(뜰) 무렵 예보라는 것도 */ +function ScoreHelp({ plan }: { plan: SkyPlanData }) { + const sunAt = plan.timeline?.find((t) => t.kind === 'sun')?.at + return ( +
+ + 노을 점수 100점 만점 · 높을수록 붉어요 + ? + +

+ 80점 넘으면 붉게, 60점 넘으면 곱게, 40점 넘으면 은은하게 물들어요. + {sunAt && ` 해 ${plan.kind === 'sunrise' ? '뜰' : '질'} 무렵(${new Date(sunAt).getHours()}시) 날씨 예보로 계산했고, 노을 피크 시각은 해 ${plan.kind === 'sunrise' ? '뜨기 10~20분 전' : '지고 10~20분 뒤'}로 어림한 거라 실제와 다를 수 있어요.`}

- {v(plan && [agree, `노을 점수 ${plan.score}`].filter(Boolean).join(' · '), 'w-48')} -
+ ) } -/** 골든아워 → 해 짐 → 블루아워 */ -function Timeline({ rows }: { rows?: BestTime[] }) { +/** 언제 보면 좋을까: 왼쪽 세로 줄 색이 그 시각 하늘색, 노을 피크만 강조. 용어 뜻은 ?를 눌러야 */ +function Timeline({ rows, kind = 'sunset' }: { rows?: BestTime[]; kind?: SkyPlanData['kind'] }) { + const rail = kind === 'sunrise' ? 'bg-[linear-gradient(180deg,#2d3f8f,#8c5aa6_25%,#e8506a_45%,#f6844e_60%,#f2b84b)]' : 'bg-[linear-gradient(180deg,#f2b84b,#f6844e_45%,#e8506a_62%,#8c5aa6_82%,#2d3f8f)]' return ( -
-
    -
+
+ {rows && ( +
+ + ?골든아워·블루아워가 뭐예요 + +

+ 골든아워 해가 {kind === 'sunrise' ? '뜬 뒤' : '지기 전'}, 햇빛이 금빛으로 물드는 시간 +
+ 블루아워 해가 {kind === 'sunrise' ? '뜨기 전' : '진 뒤'}, 하늘이 짙은 파랑으로 남는 시간 +

+
+ )}
) } @@ -121,39 +177,36 @@ export function SkyPage() { const ranking = useQuery(getSkyRankingOptions()) const load = loadOf(sky) const rankLoad = loadOf(ranking) - const plan = sky.data?.plan ?? undefined + const plans = sky.data?.plans ?? [] + const [picked, setPicked] = useState() + // 타일을 누르면 그날, 아니면 다음에 오는 날 + const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined const spots = (sky.data?.spots ?? []).slice(0, 3) const items = (ranking.data?.items ?? []).slice(0, 8) - const target = sky.data?.days?.find((d) => d.day === plan?.day) - const sunset = plan?.timeline?.find((t) => t.kind === 'sun')?.at + const rise = plan?.kind === 'sunrise' return (
{/* 히어로 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */} -
+