From cac6ea236f45301539bc2d9484978457ea0b8538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Mon, 12 Oct 2026 14:41:09 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EA=B5=AC=20=EC=A4=91=EC=8B=AC=2020km?= =?UTF-8?q?=20=EC=95=88=EC=97=90=20=EC=84=9C=EC=AA=BD=EC=9D=B4=20=ED=8A=B8?= =?UTF-8?q?=EC=9D=B8=20=EB=85=B8=EC=9D=84=20=EB=AA=85=EC=86=8C=EA=B0=80=20?= =?UTF-8?q?=EC=9E=88=EC=9C=BC=EB=A9=B4=20=EB=85=B8=EC=9D=84=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=20=EA=B0=80=EC=82=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/crud/sky_crud.py | 4 ++++ backend/docs/openmeteo-data.md | 1 + backend/services/calc/sky_score.py | 5 +++++ backend/services/sky_service.py | 20 ++++++++++++++++---- backend/tests/test_sky_api.py | 27 +++++++++++++++++++++++++++ backend/tests/test_sky_score.py | 5 +++++ 6 files changed, 58 insertions(+), 4 deletions(-) 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/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index be49e6f..ab8999d 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -52,6 +52,7 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100 - 가시거리(`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 이상 은은함, 그 미만 흐림. diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index 63dfaf0..dcf4dc4 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -9,6 +9,8 @@ DISTANCES_KM = (20, 100) _CLEAR_CANVAS = 0.4 # 해 지기(뜨기) 이만큼 전 사이에 비가 왔다가 그 시각엔 개면 공기가 맑고 구름이 남아 더 붉다. RAIN_BEFORE_HOURS = (2, 6) +# 서쪽이 바다·강·전망대로 트여 해가 지평선까지 보이는 곳은 산·건물에 가리지 않아 노을이 더 잘 보인다. +OPEN_WEST_BONUS = 1.1 @dataclass(frozen=True) @@ -25,6 +27,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: @@ -60,6 +63,8 @@ def air_factor(air: Air) -> float: 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 diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py index bf8f023..3bcfd03 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, replace from datetime import date, datetime, timedelta, timezone from typing import Optional @@ -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() @@ -171,11 +172,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): @@ -193,7 +202,7 @@ 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 {})))) + value = min(100, round(statistics.mean(per_model) * air_factor(replace(_air(region.code, sun_at, hourly or {}, om or {}), open_west=open_west and kind is SkyType.SUNSET)))) 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, @@ -362,7 +371,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/tests/test_sky_api.py b/backend/tests/test_sky_api.py index c8be86e..7d1a628 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -169,3 +169,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 5fd277e..8f1b6b7 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -34,6 +34,11 @@ def test_air_factor_centers_on_usual_air_and_clearing_rain_raises(): 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