diff --git a/TODO.md b/TODO.md index b880681..cbb1b63 100644 --- a/TODO.md +++ b/TODO.md @@ -136,7 +136,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` | @@ -144,7 +144,7 @@ | [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`) | -| [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` | +| [x] | 달: '밝기 %' 표시 뺌 → 모양 + 잘 보이는지(구름·뜨고 지는 시각). 모양은 실제 해·달 황경 차이로(예전 계산은 보름을 반나절 일찍 판정). 별보기각은 빛나는 면 × 떠 있는 비율 (사용자 결정) | 10/8 회의 | `backend/services/calc/moon.py` | | [x] | 노을: 점수 강조(히어로에 점수 크게) + 골든아워·블루아워 설명. 결론은 다음에 오는 것(해 뜨기 전·밤엔 일출, 그 사이엔 노을)으로, 피드 노을 카드도 같이 (사용자 결정 '각·노을도 지금 기준') | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` | | [ ] | 주말 예보 UI 개선 — 회의에서 구체 내용 없음 | 10/8 회의 | `frontend/src/b/WeekPage.tsx` | | [ ] | AEO·SEO 메타데이터 + 구글·네이버 검색 등록 (금일 핵심 업무), 넣은 태그·키워드 정의서 작성, 매시간 갱신 콘텐츠 노출 방식 정리 → 대표 보고. 도메인은 별도 유지 | 10/8 회의 결정 | `frontend/index.html`, `docs/` | diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index f5d3d74..667ef6c 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -155,7 +155,7 @@ class Hero(WebPacketProtocol): 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") + moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)") stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저") diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 80e8978..5416f66 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -54,6 +54,7 @@ class Context: sunset_score: Optional[int] wind_warning: bool lookahead_rain_prob: int + moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 @dataclass(frozen=True) @@ -197,7 +198,7 @@ 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}점으로 둬요" diff --git a/backend/services/calc/moon.py b/backend/services/calc/moon.py index 84e9d12..cf4b140 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,96 @@ 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 + 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), 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 or not m.up_hours: + return "달이 안 보여요" + 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/feed_service.py b/backend/services/feed_service.py index a84a49e..2831cb6 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -27,7 +27,7 @@ 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.moon import MoonNight, nearest, night, view_line from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE from services.calc.sun import sun_times from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label @@ -134,7 +134,9 @@ 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 [] @@ -145,7 +147,7 @@ def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: O 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, - moon=phase_name(_tonight(now)), + moon=moon, ) @@ -375,7 +377,7 @@ class FeedService: items = board.items 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, @@ -422,7 +424,7 @@ class FeedService: return float(rows[0].uv_index) 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: + 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: @@ -434,8 +436,9 @@ class FeedService: 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))], + 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(_hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None))], ) @staticmethod @@ -511,24 +514,25 @@ 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 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}" @@ -536,14 +540,14 @@ class FeedService: line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요" caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY 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: @@ -747,7 +751,22 @@ 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 _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/index_service.py b/backend/services/index_service.py index 3246232..0e8608e 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -18,7 +18,7 @@ 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 @@ -27,6 +27,7 @@ from services.weather_service import WeatherService # 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다. DAYS = 3 _LOOKAHEAD_HOURS = (9, 18) +_STARS_HOURS = range(21, 26) # 달빛이 별보기를 가리는지 보는 시각 (별보기각 시간대) _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") # 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도. @@ -348,8 +349,9 @@ class IndexService: 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)), + 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), lookahead_rain_prob=0, **base_ctx, ) for d in defs: diff --git a/backend/tests/test_moon.py b/backend/tests/test_moon.py index a686495..c8dd895 100644 --- a/backend/tests/test_moon.py +++ b/backend/tests/test_moon.py @@ -1,9 +1,9 @@ -from datetime import datetime, timezone +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 altitude, nearest, night, phase_name, view_line from services.feed_service import FeedService, _tonight @@ -27,7 +27,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 +38,38 @@ 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) == "달이 안 보여요" + + +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/docs/점수_계산식.md b/docs/점수_계산식.md index 4de80eb..6546fe3 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -9,7 +9,7 @@ | 나들이 점수 | 주말 탭 전국 순위, 당일치기 카드 | `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/moon.py` | | 불쾌지수 | 히어로 칸 | `backend/services/calc/weather_calc.py` | ## 1. 공통 — 요소 점수와 섞는 법 @@ -150,10 +150,26 @@ 일출 시간표는 블루아워(해 뜨기 전 해 고도 −6°) → 해 떠요 → 골든아워(해 고도 6°까지 올라오는 때)입니다. '가장 붉을 때'는 해 뜨기 10분 + (상층 구름 % ÷ 10)분 전입니다. -## 8. 달 밝기 +## 8. 달 모양·잘 보이는지 -- **밝기 = (1 − cos(2π × 삭에서 지난 비율)) ÷ 2**. 0이면 그믐(안 보임), 1이면 보름입니다. 삭 시각은 Meeus 계산(오차 2분 안)입니다. -- 달 모양에서 **빛나는 면의 비율**일 뿐, 구름·달 고도·월출 시각은 반영하지 않습니다. +'달 밝기 N%'는 쓰지 않습니다. 초승달도 달 자체는 밝게 보이므로, 퍼센트는 밝기가 아니라 모양(빛나는 면)일 뿐이기 때문입니다. + +- **모양**: 달과 해의 황경 차이(0° 삭 → 180° 보름)로 정합니다. 빛나는 면 = (1 − cos 황경 차이) ÷ 2, 모양 이름은 차이 구간으로(삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달). 히어로 달 그림에 씁니다. +- **뜨고 지는 시각**: 그날 19시~다음 날 5시를 10분 간격으로 달 고도(Meeus 간이식, 지표 기준)를 계산해 −0.83°를 넘나드는 때. +- **잘 보이는지** (위에서부터 먼저 걸리는 것): + +| 조건 | 문구 | +|---|---| +| 빛나는 면 3% 미만이거나 밤새 안 뜸 | 달이 안 보여요 | +| 저녁 7~9시 사이가 아니라 밤늦게 뜸 | 새벽 2시에 떠요 | +| 달이 떠 있는 시각의 하늘이 흐림 쪽 (맑음 0 · 구름많음 0.5 · 흐림 1의 평균 0.6 이상) | 구름에 가려요 | +| 같은 평균 0.3 이상 | 구름 사이로 보여요 | +| 밤사이 짐 | 밤 11시까지 보여요 | +| 그 밖 | 밤새 잘 보여요 | + +- 히어로 '오늘 밤 달' 칸: '모양, 잘 보이는지' (예: 상현달, 밤 11시까지 보여요). +- 달 포스트: 모양 + 잘 보이는지 + 달 뜸·짐 시각. +- 별보기각 '시간' 요소: 달이 비추는 정도 = 빛나는 면 × 21~26시 중 달이 떠 있는 비율, 점수 = 20 + 80 × (1 − 그 값). 근거 문구는 '모양, 잘 보이는지'(구름 제외). ## 9. 불쾌지수