From e059e294d03d0d76a88e4fa3cfb41a84987a38d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Thu, 8 Oct 2026 10:57:11 +0900 Subject: [PATCH 01/68] =?UTF-8?q?feat:=20=EB=82=AE=20=EC=95=BC=EC=99=B8=20?= =?UTF-8?q?=ED=99=9C=EB=8F=99=20=EC=A7=80=EC=88=98=EC=97=90=20=ED=96=87?= =?UTF-8?q?=EB=B9=9B=C2=B7=EC=9E=90=EC=99=B8=EC=84=A0=20=EA=B0=99=EC=9D=80?= =?UTF-8?q?=20=EB=B9=84=EC=A4=91=EC=9C=BC=EB=A1=9C,=20=EB=9F=AC=EB=8B=9D?= =?UTF-8?q?=C2=B7=EB=A9=8D=EB=AD=89=EC=82=B0=EC=B1=85=EC=9D=80=20=EC=9E=90?= =?UTF-8?q?=EC=99=B8=EC=84=A0=20=EC=A0=9C=EC=99=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/docs/openmeteo-data.md | 16 +++--- backend/seed/index_definition.json | 86 ++++++++++++++++++------------ 2 files changed, 62 insertions(+), 40 deletions(-) diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 30eab53..c128c29 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -140,17 +140,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/seed/index_definition.json b/backend/seed/index_definition.json index 7cefcc5..461d842 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -87,13 +87,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": { @@ -126,6 +126,10 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -376,13 +380,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": { @@ -420,6 +424,10 @@ "view": { "zero": 5, "full": 20 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -460,12 +468,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": { @@ -488,6 +496,14 @@ "time": { "type": "fixed", "value": 100 + }, + "uv": { + "zero": 8, + "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -604,8 +620,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, @@ -629,10 +645,6 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ @@ -968,13 +980,13 @@ "to": 19 } ], - "weight_temp": 25, - "weight_rain": 25, - "weight_wind": 30, + "weight_temp": 20, + "weight_rain": 20, + "weight_wind": 20, "weight_humidity": 5, "weight_air": 10, - "weight_uv": 0, - "weight_sun": 0, + "weight_uv": 10, + "weight_sun": 10, "weight_view": 0, "weight_time": 5, "factor_rules": { @@ -1003,6 +1015,14 @@ "sun": 100, "holiday": 100, "default": 70 + }, + "uv": { + "zero": 8, + "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ @@ -1050,12 +1070,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, @@ -1082,10 +1102,6 @@ "time": { "type": "fixed", "value": 100 - }, - "uv": { - "zero": 8, - "full": 2 } }, "zero_rules": [ @@ -1406,13 +1422,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": { @@ -1442,6 +1458,10 @@ "uv": { "zero": 8, "full": 2 + }, + "sun": { + "zero": 0.2, + "full": 0.8 } }, "zero_rules": [ From cd6769ccefd699a666fc89ed284fdab3995d73c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Thu, 8 Oct 2026 11:37:09 +0900 Subject: [PATCH 02/68] =?UTF-8?q?feat:=20=EB=85=B8=EC=9D=84=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=20=EB=A7=91=EC=9D=80=20=ED=95=98=EB=8A=98=2055?= =?UTF-8?q?=EC=A0=90=EC=9C=BC=EB=A1=9C=20=EC=98=AC=EB=A6=AC=EA=B3=A0=20?= =?UTF-8?q?=EA=B3=B5=EA=B8=B0=20=EB=B3=B4=EC=A0=95=EC=9D=80=20=EC=95=84?= =?UTF-8?q?=EC=A3=BC=20=EB=BF=8C=EC=98=87=EA=B1=B0=EB=82=98=20=EC=8A=B5?= =?UTF-8?q?=ED=95=9C=20=EB=82=A0=EB=A7=8C=20=EA=B9=8E=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=99=84=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/docs/openmeteo-data.md | 8 ++++---- backend/services/calc/sky_score.py | 8 ++++---- backend/tests/test_sky_api.py | 2 +- backend/tests/test_sky_score.py | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index c128c29..015f3dc 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -40,17 +40,17 @@ 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%에서 점수가 오히려 떨어졌다. +- 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 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. + - 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 20km 이상 ×1.0 ~ 5km 이하 ×0.8. 뿌연 공기는 색을 흐린다. + - 습도(`weather_hourly.humidity`, 가장 가까운 정시): 70% 이하 ×1.0 ~ 90% 이상 ×0.85. 평소 날씨는 깎지 않고 아주 뿌옇거나 습한 날만 깎는다. - 비 갠 뒤: 2~6시간 전 비 확률 60% 이상이고 그 시각 비 확률 40% 미만이면 ×1.15. - 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다. - 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림. diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index 9cfb0f6..701b923 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -5,8 +5,8 @@ from datetime import datetime, timedelta 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) @@ -46,9 +46,9 @@ 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 *= _ramp(air.visibility_km, 5, 20, 0.8) if air.humidity is not None: - f *= _ramp(air.humidity, 90, 50, 0.75) + f *= _ramp(air.humidity, 90, 70, 0.85) if air.rain_before is not None and air.rain_before >= 60 and (air.rain_now or 0) < 40: f *= 1.15 return f diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py index 6acc19b..c5fc60b 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -160,7 +160,7 @@ 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) + assert hazy == round(plain * 0.8 * 0.85) rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)} assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15)) diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index 6bae052..056f2a8 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -26,9 +26,9 @@ def test_score_rises_steadily_with_a_few_clouds(): def test_air_factor_hazy_humid_lowers_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=70)) == 1.0 + assert air_factor(Air(visibility_km=5)) == 0.8 and air_factor(Air(humidity=90)) == 0.85 + assert 0.8 < air_factor(Air(visibility_km=12.5)) < 1.0 assert air_factor(Air(rain_before=70, rain_now=10)) == 1.15 assert air_factor(Air(rain_before=70, rain_now=60)) == 1.0 # 아직 비 오는 중이면 가산 없음 From 3857ef8d14ea0b208e4fadc1827e3d6717749473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Thu, 8 Oct 2026 11:59:08 +0900 Subject: [PATCH 03/68] =?UTF-8?q?feat:=20=EB=85=B8=EC=9D=84=20=EA=B3=B5?= =?UTF-8?q?=EA=B8=B0=20=EB=B3=B4=EC=A0=95=EC=9D=84=20=ED=8F=89=EC=86=8C=20?= =?UTF-8?q?=EA=B3=B5=EA=B8=B0=20=EA=B8=B0=EC=A4=80=EC=A0=90=20=EC=A4=91?= =?UTF-8?q?=EC=8B=AC=EC=9C=BC=EB=A1=9C=20=EB=B0=94=EA=BF=94=20=EB=A7=91?= =?UTF-8?q?=EC=9D=80=20=EB=82=A0=20=EC=A0=90=EC=88=98=EA=B0=80=20=ED=95=9C?= =?UTF-8?q?=20=EC=A0=90=EC=97=90=20=EB=AA=B0=EB=A6=AC=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EA=B2=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/docs/openmeteo-data.md | 6 +++--- backend/services/calc/sky_score.py | 23 ++++++++++++++++------- backend/tests/test_sky_api.py | 2 +- backend/tests/test_sky_score.py | 7 ++++--- 4 files changed, 24 insertions(+), 14 deletions(-) diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md index 015f3dc..be49e6f 100644 --- a/backend/docs/openmeteo-data.md +++ b/backend/docs/openmeteo-data.md @@ -48,9 +48,9 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100 ``` - 맑은 하늘(구름 0%)은 55점(은은함)이고, 구름이 몇 %만 있어도 점수가 갈린다. 예전에는 10% 미만을 0.3으로 고정해 맑은 날 전국이 48점에 몰리고, 10%에서 점수가 오히려 떨어졌다. -- 공기 보정 (`air_factor`, 구 중심 해 질·뜰 무렵 값. 값이 없으면 ×1.0): - - 가시거리(`openmeteo_hourly.visibility_m`, 가장 가까운 3시간 구간): 20km 이상 ×1.0 ~ 5km 이하 ×0.8. 뿌연 공기는 색을 흐린다. - - 습도(`weather_hourly.humidity`, 가장 가까운 정시): 70% 이하 ×1.0 ~ 90% 이상 ×0.85. 평소 날씨는 깎지 않고 아주 뿌옇거나 습한 날만 깎는다. +- 공기 보정 (`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. - 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음. 신뢰도는 공기 보정 전 구름 점수로 본다. - 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림. diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index 701b923..63dfaf0 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -36,19 +36,28 @@ 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, 20, 0.8) + f *= _interp(air.visibility_km, _VISIBILITY_FACTOR) if air.humidity is not None: - f *= _ramp(air.humidity, 90, 70, 0.85) + 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 return f diff --git a/backend/tests/test_sky_api.py b/backend/tests/test_sky_api.py index c5fc60b..c8be86e 100644 --- a/backend/tests/test_sky_api.py +++ b/backend/tests/test_sky_api.py @@ -161,7 +161,7 @@ def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air(): 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.8 * 0.85) - rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)} + 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)) diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index 056f2a8..5fd277e 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -24,11 +24,12 @@ 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=20, humidity=70)) == 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 0.8 < air_factor(Air(visibility_km=12.5)) < 1.0 + 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 # 아직 비 오는 중이면 가산 없음 From 76a640feab385e305b469c4a38c5b6ead642ee8c Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 16:52:10 +0900 Subject: [PATCH 04/68] =?UTF-8?q?feat:=20=EC=98=A4=EB=8A=98=20=EB=82=A0?= =?UTF-8?q?=EC=94=A8=20=EC=A0=90=EC=88=98=20=EA=B8=B0=EC=A4=80=20=EA=B0=95?= =?UTF-8?q?=ED=99=94=20=E2=80=94=20100=EC=A0=90=EC=9D=80=20=EC=B2=B4?= =?UTF-8?q?=EA=B0=90=2021=C2=B10.5=C2=B0=C2=B7=EC=8A=B5=EB=8F=84=2045~55%?= =?UTF-8?q?=C2=B7=ED=96=87=EB=B9=9B=C2=B7=EB=B0=94=EB=9E=8C=201m/s=C2=B7?= =?UTF-8?q?=EC=B4=88=EB=AF=B8=EC=84=B8=EB=A8=BC=EC=A7=80=2010=20=EC=9D=B4?= =?UTF-8?q?=ED=95=98=EA=B0=80=20=EB=AA=A8=EB=91=90=20=EB=A7=9E=EC=9D=84=20?= =?UTF-8?q?=EB=95=8C=EB=A7=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/services/calc/index_calc.py | 2 +- backend/services/index_service.py | 7 ++++--- backend/tests/test_index_calc.py | 11 +++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 6a54a30..80e8978 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -115,7 +115,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)) diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 97d3b9a..cddde85 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -30,10 +30,11 @@ _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}], ) diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 8c144a6..fa0c774 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -263,3 +263,14 @@ 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 From 91deb28ec351baec3e4130c21d7e33910f8a9c37 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 16:53:21 +0900 Subject: [PATCH 05/68] =?UTF-8?q?docs:=20=EC=A0=90=EC=88=98=20=EA=B3=84?= =?UTF-8?q?=EC=82=B0=EC=8B=9D=20=EC=A0=95=EB=A6=AC=20=E2=80=94=20=EC=98=A4?= =?UTF-8?q?=EB=8A=98=20=EB=82=A0=EC=94=A8=C2=B7=EA=B0=81=C2=B7=EB=82=98?= =?UTF-8?q?=EB=93=A4=EC=9D=B4=C2=B7=EB=85=B8=EC=9D=84=C2=B7=EB=85=B8?= =?UTF-8?q?=EC=9D=84=20=EC=8B=9C=EA=B0=81=C2=B7=EB=8B=AC=20=EB=B0=9D?= =?UTF-8?q?=EA=B8=B0=C2=B7=EB=B6=88=EC=BE=8C=EC=A7=80=EC=88=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/점수_계산식.md | 145 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/점수_계산식.md diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md new file mode 100644 index 0000000..36ad77a --- /dev/null +++ b/docs/점수_계산식.md @@ -0,0 +1,145 @@ +# 점수 계산식 + +화면에 나오는 점수·판정의 계산식을 한곳에 모은 문서입니다. 각별 비중·시간대는 [각_계산기준.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. 오늘 날씨 점수 + +오늘 낮 **9~21시**가 밖에 나가기 좋은 정도. 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점 미만. + +## 3. 각 점수 + +- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다. +- **시간대가 여러 개면 그중 가장 좋은 시간대 점수**를 그날 점수로 씁니다. 그래서 하루 동안 바뀌지 않습니다. +- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다. +- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다. + +## 4. 나들이 점수 (주말 순위·당일치기) + +토·일 **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점 미만이면 카드를 보이지 않습니다. + +## 5. 노을 점수 + +해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **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) | 나가 볼 만해요 | + +- 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**입니다. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요). +- 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음. +- 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다. + +## 6. 노을 시각 + +| 시각 | 정의 | +|---|---| +| 골든아워 | 해 고도가 **6°**로 내려온 때부터 해 질 때까지. 햇빛이 낮게 비쳐 금빛으로 보이는 시간 | +| 해 져요 | 일몰 | +| 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 | +| 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 | + +일출은 순서가 거꾸로입니다(블루아워 → 가장 붉을 때 → 해 떠요). + +## 7. 달 밝기 + +- **밝기 = (1 − cos(2π × 삭에서 지난 비율)) ÷ 2**. 0이면 그믐(안 보임), 1이면 보름입니다. 삭 시각은 Meeus 계산(오차 2분 안)입니다. +- 달 모양에서 **빛나는 면의 비율**일 뿐, 구름·달 고도·월출 시각은 반영하지 않습니다. + +## 8. 불쾌지수 + +- **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3** +- 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌 From 7b5d90529833c3b475a27ad6e8a575ece59b4282 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 16:53:49 +0900 Subject: [PATCH 06/68] =?UTF-8?q?feat:=20=EB=85=B8=EC=9D=84=20=ED=83=AD=20?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=ED=91=9C=20=EC=95=84=EB=9E=98=20=EA=B3=A8?= =?UTF-8?q?=EB=93=A0=EC=95=84=EC=9B=8C=C2=B7=EB=B8=94=EB=A3=A8=EC=95=84?= =?UTF-8?q?=EC=9B=8C=20=EC=84=A4=EB=AA=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 12 +++++++++++- frontend/src/b/SkyPage.tsx | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index b407209..e2c0ef7 100644 --- a/TODO.md +++ b/TODO.md @@ -112,7 +112,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단계: 탭 5개 메타 — 빌드 때 탭별 HTML(`sky.html` 등)에 title·description·og·canonical을 따로 넣고, `robots.txt`·`sitemap.xml` 생성 | 지금 SPA라 HTML이 하나뿐이어서 모든 주소가 같은 메타. 기대 효과는 브랜드 검색("날씨각", "날씨각 노을") | `frontend/src/pageMeta.ts`, `frontend/vite.config.ts`, `frontend/nginx.conf`, `frontend/src/b/BLayout.tsx` | +| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) | +| [ ] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 | 등록·제출 없으면 새 도메인은 색인이 늦음 | 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` | @@ -139,3 +141,11 @@ | [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) | | [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` | | [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` | +| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 2) | 10/8 회의 결정 | `backend/services/index_service.py:203` | +| [ ] | 각 점수를 아침·낮·저녁·밤 시간대별로 — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` | +| [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | +| [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` | +| [ ] | 노을: 하늘 상황 문구 대신 점수 강조(10/7 다시 기획에서 되돌림). 골든아워·블루아워 설명은 시간표 아래에 넣음 | 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/` | +| [ ] | `docs/콘텐츠_구현기획.md` 2-1의 오늘 날씨 점수 식이 예전 기준(기온 40·비 30·바람 15·미세먼지 15) — 새 기준은 `docs/점수_계산식.md` | 점수 계산식 정리 중 발견 (10/8) | `docs/콘텐츠_구현기획.md` | diff --git a/frontend/src/b/SkyPage.tsx b/frontend/src/b/SkyPage.tsx index ebefac8..ef06ab5 100644 --- a/frontend/src/b/SkyPage.tsx +++ b/frontend/src/b/SkyPage.tsx @@ -73,6 +73,22 @@ function Timeline({ rows }: { rows?: BestTime[] }) { ))} + {rows && ( +
+ {rows.some((t) => t.kind === 'golden') && ( +
+
골든아워
+
해가 낮게 떠 햇빛이 금빛으로 물드는 시간, 해 지기 전 약 30분~1시간
+
+ )} + {rows.some((t) => t.kind === 'blue') && ( +
+
블루아워
+
해가 진 뒤 하늘이 짙은 푸른빛으로 남는 시간, 적힌 시각쯤 어두워져요
+
+ )} +
+ )} ) } From ffc330d4788dc7c83c22edb5ca9ec9d7453a8df8 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:05:40 +0900 Subject: [PATCH 07/68] =?UTF-8?q?feat:=20=EA=B2=80=EC=83=89=20=EA=B8=B0?= =?UTF-8?q?=EB=B3=B8=20=EB=A9=94=ED=83=80=20=E2=80=94=20title=C2=B7descrip?= =?UTF-8?q?tion=20=EB=B3=B4=EA=B0=95,=20canonical=C2=B7og:locale=C2=B7WebS?= =?UTF-8?q?ite=20JSON-LD=C2=B7=EA=B5=AC=EA=B8=80=20=EC=86=8C=EC=9C=A0=20?= =?UTF-8?q?=ED=99=95=EC=9D=B8,=20robots.txt=C2=B7sitemap.xml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 2 +- frontend/index.html | 20 ++++++++++++++++---- frontend/public/robots.txt | 4 ++++ frontend/public/sitemap.xml | 4 ++++ 4 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 frontend/public/robots.txt create mode 100644 frontend/public/sitemap.xml diff --git a/TODO.md b/TODO.md index e2c0ef7..14d06d5 100644 --- a/TODO.md +++ b/TODO.md @@ -112,7 +112,7 @@ | [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`) | -| [x] | 검색 노출 1단계: 탭 5개 메타 — 빌드 때 탭별 HTML(`sky.html` 등)에 title·description·og·canonical을 따로 넣고, `robots.txt`·`sitemap.xml` 생성 | 지금 SPA라 HTML이 하나뿐이어서 모든 주소가 같은 메타. 기대 효과는 브랜드 검색("날씨각", "날씨각 노을") | `frontend/src/pageMeta.ts`, `frontend/vite.config.ts`, `frontend/nginx.conf`, `frontend/src/b/BLayout.tsx` | +| [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) | | [ ] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 | 등록·제출 없으면 새 도메인은 색인이 늦음 | 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` | diff --git a/frontend/index.html b/frontend/index.html index a82db1c..192fa91 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -15,17 +15,29 @@ - - 날씨각 + + 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 - - + + + + + + + + https://weather.o2o.kr/ + From d6525f592cc7c2b71f277d2c9e7fcb9437fc9edd Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:07:26 +0900 Subject: [PATCH 08/68] =?UTF-8?q?feat:=20=EA=B0=81=20=EC=A0=90=EC=88=98?= =?UTF-8?q?=EB=A5=BC=20=EC=95=84=EC=B9=A8=C2=B7=EB=82=AE=C2=B7=EC=A0=80?= =?UTF-8?q?=EB=85=81=C2=B7=EB=B0=A4=20=EA=B5=AC=EA=B0=84=EB=B3=84=EB=A1=9C?= =?UTF-8?q?=20=E2=80=94=20=EC=A7=80=EA=B8=88=20=EA=B5=AC=EA=B0=84=20?= =?UTF-8?q?=EC=A0=90=EC=88=98=EB=A1=9C=20=EC=88=9C=EC=9C=84,=20=EA=B5=AC?= =?UTF-8?q?=EA=B0=84=EC=9D=B4=20=EC=95=88=20=EA=B2=B9=EC=B9=98=EB=8A=94=20?= =?UTF-8?q?=EA=B0=81=EC=9D=80=20=EC=88=9C=EC=9C=84=C2=B7=ED=94=BC=EB=93=9C?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=B9=BC=EA=B3=A0=20=EB=AA=A9=EB=A1=9D=20?= =?UTF-8?q?=EB=81=9D=EC=97=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/common/database/model/models.py | 1 + backend/crud/index_crud.py | 9 +- backend/postgres-init/init.sql | 2 + backend/router/v1/feed/protocol.py | 1 + backend/router/v1/index/index.py | 9 +- backend/router/v1/index/protocol.py | 11 ++- backend/router/v1/watch/watch.py | 2 +- backend/services/calc/day_slot.py | 27 ++++++ backend/services/feed_service.py | 22 ++--- backend/services/index_service.py | 109 ++++++++++++++++++++---- backend/tests/test_day_slot.py | 63 ++++++++++++++ backend/tests/test_index_api.py | 10 ++- 12 files changed, 226 insertions(+), 40 deletions(-) create mode 100644 backend/services/calc/day_slot.py create mode 100644 backend/tests/test_day_slot.py diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index d28d756..5a7be6f 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -206,6 +206,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/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/postgres-init/init.sql b/backend/postgres-init/init.sql index ce5c456..9ebce24 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -153,12 +153,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 ( diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index 032d6e8..b495804 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -131,6 +131,7 @@ class TopIndex(WebPacketProtocol): score: int rank: int summary: Optional[str] = None + active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수") class HeroStat(WebPacketProtocol): diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py index 543bc03..efcbc6f 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 @@ -18,10 +19,11 @@ def _summary(i: IndexItem, today: date) -> 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, 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), @@ -32,8 +34,9 @@ async def list_indices( if err is not ErrorType.SUCCESS: return Res_IndexList(result=error_info(err)) items = [_summary(i, board.day) for i in board.items] + 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.is_core)] - return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered) + 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..29f3296 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 @@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol): 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/watch/watch.py b/backend/router/v1/watch/watch.py index ff82612..b2dc72e 100644 --- a/backend/router/v1/watch/watch.py +++ b/backend/router/v1/watch/watch.py @@ -97,7 +97,7 @@ async def get_watch_summary( 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/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/feed_service.py b/backend/services/feed_service.py index 2e5b9d8..18cb55c 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -25,6 +25,7 @@ from router.v1.feed.protocol import ( ) 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 @@ -88,7 +89,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 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸 @@ -154,22 +154,12 @@ 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·예보·미세먼지 갱신 중 가장 빠른 쪽.""" 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, + 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)] air = now.replace(minute=20, second=0, microsecond=0) changes.append(air if air > now else air + timedelta(hours=1)) @@ -247,7 +237,7 @@ 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) 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: @@ -391,7 +381,7 @@ class FeedService: 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) @@ -434,7 +424,7 @@ class FeedService: 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 + 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 "오늘은 쉬어 가요" diff --git a/backend/services/index_service.py b/backend/services/index_service.py index cddde85..3246232 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 @@ -16,6 +16,7 @@ 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.sun import sun_times @@ -28,7 +29,7 @@ DAYS = 3 _LOOKAHEAD_HOURS = (9, 18) _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") -# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도. +# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도. WEATHER_SCORE_DEF = SimpleNamespace( weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0, factor_rules={ @@ -36,7 +37,7 @@ WEATHER_SCORE_DEF = SimpleNamespace( "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}], ) @@ -46,6 +47,9 @@ class IndexItem: score: IndexScore rank: int trend: list[IndexScore] + slot: Optional[str] = None + slots: dict[str, int] = field(default_factory=dict) + active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 @dataclass @@ -55,6 +59,11 @@ class IndexBoard: weather_score: Optional[int] items: list[IndexItem] + @property + def ranked(self) -> list[IndexItem]: + """지금 구간에 해당하는 각만 (순위·피드용).""" + return [i for i in self.items if i.active] + def _hour(r: WeatherHourly) -> Hour: return Hour( @@ -119,13 +128,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( @@ -136,6 +149,44 @@ def windows_for( return out +EARLY = "early" # 0~5시: 전날 밤 구간 + + +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 slot_results( + defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, +) -> dict[str, Result]: + """그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다.""" + parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()} + parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR))) + out = {} + for key, windows in parts.items(): + result = evaluate(defn, windows, ctx) + if result is not None: + out[key] = result + return out + + +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, @@ -205,20 +256,44 @@ class IndexService: 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) - ] + # 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다 + 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_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)} + 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={k: parts[k] for k in SLOTS if k in parts}, + )) + 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_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False, + )) return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items) async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]: @@ -251,7 +326,8 @@ class IndexService: 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_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at)) 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 @@ -259,8 +335,9 @@ class IndexService: inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values())) 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()): + 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_result.score if weather_result else None err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s)) @@ -279,10 +356,12 @@ class IndexService: 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) 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 diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py new file mode 100644 index 0000000..ffd6b4f --- /dev/null +++ b/backend/tests/test_day_slot.py @@ -0,0 +1,63 @@ +from datetime import date, datetime, timedelta +from types import SimpleNamespace + +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, current_slot, slot_results + +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": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET) + assert set(parts) == {"evening", "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} diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 5dbbdc0..73b4c86 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -60,8 +60,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes): assert body["result"]["success"] is True assert len(body["items"]) == 34 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"]) + for group in (True, False): + weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group] + 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)] @@ -123,7 +127,7 @@ 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))) From 5a5f585bdac9726824b0194a18658e9589badfd8 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:09:12 +0900 Subject: [PATCH 09/68] =?UTF-8?q?feat:=20=EA=B0=81=20=ED=83=AD=C2=B7?= =?UTF-8?q?=EC=8A=A4=ED=86=A0=EB=A6=AC=C2=B7=EA=B0=81=20=EC=83=81=EC=84=B8?= =?UTF-8?q?=EC=97=90=20=EC=A7=80=EA=B8=88=20=EA=B5=AC=EA=B0=84=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=EC=99=80=20=EC=95=84=EC=B9=A8=C2=B7=EB=82=AE=C2=B7?= =?UTF-8?q?=EC=A0=80=EB=85=81=C2=B7=EB=B0=A4=20=EC=B9=B8,=20=ED=9E=88?= =?UTF-8?q?=EC=96=B4=EB=A1=9C=20'=EC=A7=80=EA=B8=88=20=EB=82=A0=EC=94=A8?= =?UTF-8?q?=20=EC=A0=90=EC=88=98'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 4 +- docs/meetings/2026-10-08.md | 36 +++++++++++++ docs/점수_계산식.md | 36 +++++++++---- .../api/client/@tanstack/react-query.gen.ts | 2 +- frontend/src/api/client/index.ts | 2 +- frontend/src/api/client/sdk.gen.ts | 2 +- frontend/src/api/client/types.gen.ts | 50 ++++++++++++++++++- frontend/src/b/GakPage.tsx | 10 ++-- frontend/src/b/Sheets.tsx | 22 +++++++- frontend/src/b/TodayPage.tsx | 14 ++++-- 10 files changed, 152 insertions(+), 26 deletions(-) create mode 100644 docs/meetings/2026-10-08.md diff --git a/TODO.md b/TODO.md index 14d06d5..5cedabd 100644 --- a/TODO.md +++ b/TODO.md @@ -141,8 +141,8 @@ | [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) | | [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` | | [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` | -| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 2) | 10/8 회의 결정 | `backend/services/index_service.py:203` | -| [ ] | 각 점수를 아침·낮·저녁·밤 시간대별로 — 지금은 하루 중 가장 좋은 시간대 점수로 하루 고정이라 비가 와도 안 바뀜 | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` | +| [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` | | [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | | [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` | | [ ] | 노을: 하늘 상황 문구 대신 점수 강조(10/7 다시 기획에서 되돌림). 골든아워·블루아워 설명은 시간표 아래에 넣음 | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` | 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 index 36ad77a..0079e6c 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -4,7 +4,7 @@ | 점수 | 화면 | 코드 | |---|---|---| -| 오늘 날씨 점수 | 오늘 탭 히어로 큰 숫자 | `backend/services/index_service.py` (`WEATHER_SCORE_DEF`) | +| 지금 날씨 점수 | 오늘 탭 히어로 큰 숫자 | `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` | @@ -43,9 +43,20 @@ | 자외선·햇빛·가시거리 | zero, full | 직선 대신 곡선으로 zero→full | | 정보 없음 | | 바람·미세먼지·자외선·햇빛·가시거리 정보가 없으면 70점 | -## 2. 오늘 날씨 점수 +## 2. 시간대 구간 -오늘 낮 **9~21시**가 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. +| 구간 | 시각 | +|---|---| +| 아침 | 5~11시 | +| 낮 | 11시 ~ 일몰 2시간 전 | +| 저녁 | 일몰 2시간 전 ~ 일몰 1시간 뒤 | +| 밤 | 일몰 1시간 뒤 ~ 다음 날 5시 (0~5시는 전날 밤 구간) | + +한 시간은 그 시각 30분이 속한 구간에 넣습니다. 피드 카드 순서도 같은 구간을 씁니다 (`backend/services/calc/day_slot.py`). + +## 3. 지금 날씨 점수 + +**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다. | 요소 | 비중 | 100점 조건 | |---|---:|---| @@ -56,18 +67,21 @@ | 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) | | 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 | -여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며, 실제로 1년에 며칠 나오는지는 확인하지 않았습니다. +여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다. 예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만. -## 3. 각 점수 +## 4. 각 점수 - 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다. -- **시간대가 여러 개면 그중 가장 좋은 시간대 점수**를 그날 점수로 씁니다. 그래서 하루 동안 바뀌지 않습니다. +- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다. +- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다. +- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'. +- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다. - 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다. - 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다. -## 4. 나들이 점수 (주말 순위·당일치기) +## 5. 나들이 점수 (주말 순위·당일치기) 토·일 **10~17시** 기준. @@ -84,7 +98,7 @@ - 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다. - 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. -## 5. 노을 점수 +## 6. 노을 점수 해 지는(뜨는) 시각에 가장 가까운 정시의 구름을, 해 지는 방향 **20km(머리 위)**와 **100km(먼 쪽)** 두 지점에서 봅니다. 예보 모델마다 계산해 평균합니다. @@ -123,7 +137,7 @@ - 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음. - 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다. -## 6. 노을 시각 +## 7. 노을 시각 | 시각 | 정의 | |---|---| @@ -134,12 +148,12 @@ 일출은 순서가 거꾸로입니다(블루아워 → 가장 붉을 때 → 해 떠요). -## 7. 달 밝기 +## 8. 달 밝기 - **밝기 = (1 − cos(2π × 삭에서 지난 비율)) ÷ 2**. 0이면 그믐(안 보임), 1이면 보름입니다. 삭 시각은 Meeus 계산(오차 2분 안)입니다. - 달 모양에서 **빛나는 면의 비율**일 뿐, 구름·달 고도·월출 시각은 반영하지 않습니다. -## 8. 불쾌지수 +## 9. 불쾌지수 - **불쾌지수 = 0.81 × 기온 + 0.01 × 습도 × (0.99 × 기온 − 14.3) + 46.3** - 68 미만 쾌적 · 75 미만 보통 · 80 미만 불쾌 · 그 이상 매우 불쾌 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..38fbfa9 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 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..83a0b87 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 & {}); }; /** @@ -743,6 +743,24 @@ export type IndexSummary = { * Trend */ trend?: Array; + /** + * Active + * + * 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수 + */ + active?: boolean; + /** + * Slot + * + * score 가 어느 구간 점수인지 (지금 구간) + */ + slot?: string | null; + /** + * Slots + * + * 오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음 + */ + slots?: Array; }; /** @@ -1440,6 +1458,8 @@ export type ResIndexList = { day?: string | null; /** * Weather Score + * + * 지금 날씨 점수 (지금 구간 기준) */ weather_score?: number | null; /** @@ -2154,6 +2174,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 */ @@ -2311,6 +2353,12 @@ export type TopIndex = { * Summary */ summary?: string | null; + /** + * Active + * + * 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수 + */ + active?: boolean; }; /** diff --git a/frontend/src/b/GakPage.tsx b/frontend/src/b/GakPage.tsx index f1b1787..e35261c 100644 --- a/frontend/src/b/GakPage.tsx +++ b/frontend/src/b/GakPage.tsx @@ -124,12 +124,16 @@ export function GakPage() {
{items.map((g) => { return ( - ) })} diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 0ae9759..8250f0d 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -157,6 +157,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) @@ -348,8 +350,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}점 @@ -357,6 +360,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) => ( diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 5bb3de9..584fca8 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -125,7 +125,7 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) { )} - {failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'} + {failed(feedLoad) ? '점수를 못 불러왔어요' : '지금 날씨 점수'} {heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}
@@ -185,15 +185,19 @@ function Stories({ items }: { items: TopIndex[] }) { return ( {items.map((g, i) => ( - ))} From 5c4f23c01a3f9ba8b88c1ddf07a272f71ace25e8 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:15:22 +0900 Subject: [PATCH 10/68] =?UTF-8?q?feat:=20=EB=85=B8=EC=9D=84=20=EA=B2=B0?= =?UTF-8?q?=EB=A1=A0=EC=9D=84=20=EB=8B=A4=EC=9D=8C=EC=97=90=20=EC=98=A4?= =?UTF-8?q?=EB=8A=94=20=EA=B2=83=EC=9C=BC=EB=A1=9C=20=E2=80=94=20=ED=95=B4?= =?UTF-8?q?=20=EB=9C=A8=EA=B8=B0=20=EC=A0=84=C2=B7=EB=B0=A4=EC=97=94=20?= =?UTF-8?q?=EC=9D=BC=EC=B6=9C,=20=EA=B7=B8=20=EC=82=AC=EC=9D=B4=EC=97=94?= =?UTF-8?q?=20=EB=85=B8=EC=9D=84.=20=ED=94=BC=EB=93=9C=20=EB=85=B8?= =?UTF-8?q?=EC=9D=84=20=EC=B9=B4=EB=93=9C=EB=8F=84=20=EA=B0=99=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/router/v1/sky/protocol.py | 1 + backend/router/v1/sky/sky.py | 1 + backend/services/calc/sky_score.py | 13 ++++-- backend/services/calc/sun.py | 2 + backend/services/feed_service.py | 29 +++++++------ backend/services/sky_service.py | 65 ++++++++++++++++++++---------- backend/tests/test_sky_score.py | 26 ++++++++++++ 7 files changed, 98 insertions(+), 39 deletions(-) diff --git a/backend/router/v1/sky/protocol.py b/backend/router/v1/sky/protocol.py index b718566..9ca1cdd 100644 --- a/backend/router/v1/sky/protocol.py +++ b/backend/router/v1/sky/protocol.py @@ -42,6 +42,7 @@ class PlanSpot(WebPacketProtocol): class SkyPlanData(WebPacketProtocol): + kind: Literal["sunset", "sunrise"] = Field(description="다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을") day: date when: str verdict: Literal["go", "maybe", "rest"] diff --git a/backend/router/v1/sky/sky.py b/backend/router/v1/sky/sky.py index e73945c..82feb48 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", 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, diff --git a/backend/services/calc/sky_score.py b/backend/services/calc/sky_score.py index 9cfb0f6..9f5b035 100644 --- a/backend/services/calc/sky_score.py +++ b/backend/services/calc/sky_score.py @@ -131,10 +131,11 @@ 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 "낮은 구름이 머리 위를 덮어 붉은빛을 가려요" canvas = round(max(near20.mid, near20.high)) @@ -143,10 +144,16 @@ def reason(near20: Layers, far100: Layers) -> str: if canvas > 85: return f"중·높은 구름이 {canvas}%로 두꺼워 빛이 덜 비쳐요" if 25 <= canvas <= 75: - return f"중·높은 구름이 {canvas}% 알맞게 깔리고 해 지는 쪽이 트였어요" + return f"중·높은 구름이 {canvas}% 알맞게 깔리고 {side}이 트였어요" return f"물들 중·높은 구름이 {canvas}%로 {'적은' if canvas < 25 else '많은'} 편이에요" +def sunrise_timeline(blue_at: datetime, sun_at: datetime, golden_end_at: datetime) -> list[dict]: + """해 뜨기 전 블루아워 → 해 뜸 → 골든아워 끝. 분 아래는 버린다.""" + rows = [("blue", "블루아워", blue_at), ("sun", "해 떠요", sun_at), ("golden", "골든아워", golden_end_at)] + return [{"at": at.replace(second=0, microsecond=0).isoformat(), "kind": kind, "label": label} for kind, label, at in rows] + + 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)] diff --git a/backend/services/calc/sun.py b/backend/services/calc/sun.py index 8c81eee..7a68189 100644 --- a/backend/services/calc/sun.py +++ b/backend/services/calc/sun.py @@ -16,6 +16,7 @@ class SunTimes: dawn_start_at: datetime sunrise_azimuth: int golden_start_at: datetime + golden_end_at: datetime # 아침에 해 고도가 골든아워 높이까지 올라오는 때 def _solar(d: date, lon: float) -> tuple[float, float]: @@ -54,4 +55,5 @@ 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), ) diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 18cb55c..90e5ed9 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -11,7 +11,7 @@ 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.text import compass, day_range, hour_label, short_day @@ -35,7 +35,6 @@ 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 @@ -649,29 +648,29 @@ class FeedService: 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()) + better = plan.outlook 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}"]) + return PostData(**base, size="line", title=f"{when} {word}은 쉬어요", icon=icon, caption=f"{line}." + (f" {better}" if better else ""), + slides=[], share_messages=[f"{when} {word}은 쉬어요, {line}"]) 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, + slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} {word} · {c.region.name}", line=line, score=target.score, grade_label=line, cuts=cuts, situation=sit)] - if c.sky.spots: + 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"{when} 일출, {line} 🌅 {sun_at:%H:%M}에 해 떠요" if rise else f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요" + return PostData(**base, title=f"{when} {word} · {line}", icon=icon, caption=caption, slides=slides, share_messages=[share]) def _tomorrow(self, base: dict, c: "_Ctx") -> PostData: tomorrow = c.now.date() + timedelta(days=1) diff --git a/backend/services/sky_service.py b/backend/services/sky_service.py index e963618..36f7bbb 100644 --- a/backend/services/sky_service.py +++ b/backend/services/sky_service.py @@ -21,7 +21,7 @@ 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, + confidence, grade, mean_layers, reason, 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 @@ -43,7 +43,9 @@ class Spot: @dataclass class SkyPlan: - """노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로.""" + """노을 탭 맨 위 결론: 나가 볼 만한지, 왜, 몇 시에 어디로. 다음에 오는 일출 또는 노을.""" + kind: SkyType + target: SkyScore day: date when: str verdict: str @@ -119,23 +121,45 @@ def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str: return f"{_subject(_word(best.score_date, today))} 더 나아요 · {line}" -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( - day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v], - reason=reason(*layers) if layers else _FALLBACK_REASON[v], + kind=kind, target=target, day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v], + reason=reason(*layers, kind) if layers else _FALLBACK_REASON[v], score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)], situation_label=SITUATION_LINE[SkySituation(target.situation)] if target.situation else None, 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.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), None, 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 _slot(now: datetime) -> str: """노을은 13시, 일출은 21시 이후 예보로 다시 계산한다.""" return "am" if now.hour < 13 else "pm" if now.hour < 21 else "night" @@ -248,7 +272,8 @@ 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( region=region, sunset_azimuth=first.sunset_azimuth, @@ -259,26 +284,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)) diff --git a/backend/tests/test_sky_score.py b/backend/tests/test_sky_score.py index 6bae052..25814f4 100644 --- a/backend/tests/test_sky_score.py +++ b/backend/tests/test_sky_score.py @@ -101,3 +101,29 @@ 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.sunrise_at, sun.golden_end_at) + assert [r["kind"] for r in rows] == ["blue", "sun", "golden"] + assert sun.dawn_start_at < sun.sunrise_at < sun.golden_end_at From 97ebfe2d36253e3964b8cdf7d2c3a11c7337920d Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:16:16 +0900 Subject: [PATCH 11/68] =?UTF-8?q?feat:=20=EB=85=B8=EC=9D=84=20=ED=83=AD=20?= =?UTF-8?q?=ED=9E=88=EC=96=B4=EB=A1=9C=EC=97=90=20=EC=A0=90=EC=88=98=20?= =?UTF-8?q?=ED=81=AC=EA=B2=8C,=20=EC=9D=BC=EC=B6=9C=EC=9D=BC=20=EB=95=90?= =?UTF-8?q?=20=EC=9D=BC=EC=B6=9C=20=EB=AC=B8=EA=B5=AC=C2=B7=EC=8B=9C?= =?UTF-8?q?=EA=B0=84=ED=91=9C=C2=B7=EC=9A=A9=EC=96=B4=20=EC=84=A4=EB=AA=85?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 2 +- docs/점수_계산식.md | 4 +- frontend/src/api/client/types.gen.ts | 6 +++ frontend/src/b/SkyPage.tsx | 69 +++++++++++++++++----------- 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/TODO.md b/TODO.md index 5cedabd..2a54985 100644 --- a/TODO.md +++ b/TODO.md @@ -145,7 +145,7 @@ | [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` | | [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | | [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` | -| [ ] | 노을: 하늘 상황 문구 대신 점수 강조(10/7 다시 기획에서 되돌림). 골든아워·블루아워 설명은 시간표 아래에 넣음 | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.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/` | | [ ] | `docs/콘텐츠_구현기획.md` 2-1의 오늘 날씨 점수 식이 예전 기준(기온 40·비 30·바람 15·미세먼지 15) — 새 기준은 `docs/점수_계산식.md` | 점수 계산식 정리 중 발견 (10/8) | `docs/콘텐츠_구현기획.md` | diff --git a/docs/점수_계산식.md b/docs/점수_계산식.md index 0079e6c..4de80eb 100644 --- a/docs/점수_계산식.md +++ b/docs/점수_계산식.md @@ -133,6 +133,8 @@ | 구름이 두꺼워 색이 약해요 | 물들 구름 > 75 | 애매해요 | | 하늘이 넓게 물들 수 있어요 | 그 밖 (25~75) | 나가 볼 만해요 | +- **무엇을 보여 주나**: 다음에 오는 것. 오늘 해 뜨기 전엔 오늘 일출, 그 뒤 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 피드 노을 카드도 같습니다. 일출도 같은 식으로 계산합니다(구름은 해 뜨는 쪽). +- 노을 탭 히어로는 점수를 크게 보여 주고, 그 아래에 해 지는(뜨는) 시각과 하늘 상황을 씁니다. - 화면 결론(나가 볼 만해요·애매해요·쉬어요)은 **하늘 상황 기준**입니다. 상황이 없을 때만 점수로 정합니다(60↑ 나가 볼 만해요, 40↑ 애매해요). - 확신도: 모델별 점수의 표준편차가 8 미만이면 높음, 15 미만이면 보통, 그 이상이거나 모델이 1개면 낮음. - 노을 순위: 대표 30곳을 노을 점수순으로 정렬합니다. 70% 이상이 같은 상황이면 한 줄 요약을 붙입니다. @@ -146,7 +148,7 @@ | 가장 붉을 때 | 일몰 + 10분 + (20km 상층 구름 % ÷ 10)분. 상층 구름이 많을수록 늦게까지 물듦 | | 블루아워 | 해가 진 뒤 해 고도 **−6°**(시민박명 끝)가 되는 때. 해는 졌지만 하늘이 푸르게 남는 시간 | -일출은 순서가 거꾸로입니다(블루아워 → 가장 붉을 때 → 해 떠요). +일출 시간표는 블루아워(해 뜨기 전 해 고도 −6°) → 해 떠요 → 골든아워(해 고도 6°까지 올라오는 때)입니다. '가장 붉을 때'는 해 뜨기 10분 + (상층 구름 % ÷ 10)분 전입니다. ## 8. 달 밝기 diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 83a0b87..90127a9 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -2028,6 +2028,12 @@ export type SkyGrade = typeof SkyGrade[keyof typeof SkyGrade]; * SkyPlanData */ export type SkyPlanData = { + /** + * Kind + * + * 다음에 오는 것: 해 뜨기 전·밤엔 일출, 그 사이엔 노을 + */ + kind: 'sunset' | 'sunrise'; /** * Day */ diff --git a/frontend/src/b/SkyPage.tsx b/frontend/src/b/SkyPage.tsx index ef06ab5..b244ea8 100644 --- a/frontend/src/b/SkyPage.tsx +++ b/frontend/src/b/SkyPage.tsx @@ -33,13 +33,19 @@ const HERO = 'relative mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px const THREE = [0, 1, 2] const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i) -/** 히어로엔 해 지는 시각과 하늘 상황 한 줄만. 결론·이유는 아래 카드로 */ -function HeroBody({ plan, sunset }: { plan?: SkyPlanData; sunset?: string }) { +/** 히어로엔 점수를 크게, 아래에 해 지는(뜨는) 시각과 하늘 상황 한 줄. 결론·이유는 아래 카드로 */ +function HeroBody({ plan, sunAt }: { plan?: SkyPlanData; sunAt?: string }) { const v = (node: ReactNode, w: string) => (plan ? node : ) + const rise = plan?.kind === 'sunrise' return (
-

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

-

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

+

+ {v(plan?.score, 'w-[110px]')} + {plan && 점 · {plan.grade_label}} +

+

+ {v(plan && [sunAt && `${clockShort(sunAt)} ${rise ? '해 떠요' : '해 져요'}`, plan.situation_label ?? plan.headline].filter(Boolean).join(' · '), 'w-[220px]')} +

) } @@ -54,13 +60,24 @@ function Verdict({ plan }: { plan?: SkyPlanData }) { {v(plan?.headline, 'w-20')} {v(plan?.reason, 'w-[220px]')}

- {v(plan && [agree, `노을 점수 ${plan.score}`].filter(Boolean).join(' · '), 'w-48')} + {v(plan && (agree || '\u00a0'), 'w-48')} ) } -/** 골든아워 → 해 짐 → 블루아워 */ -function Timeline({ rows }: { rows?: BestTime[] }) { +const TERMS = { + sunset: { + golden: '해가 낮게 떠 햇빛이 금빛으로 물드는 시간, 해 지기 전 약 30분~1시간', + blue: '해가 진 뒤 하늘이 짙은 푸른빛으로 남는 시간, 적힌 시각쯤 어두워져요', + }, + sunrise: { + blue: '해 뜨기 전 하늘이 짙은 푸른빛인 시간, 적힌 시각쯤부터 밝아져요', + golden: '해가 막 떠 햇빛이 금빛으로 물드는 시간, 적힌 시각까지', + }, +} as const + +/** 노을: 골든아워 → 해 짐 → 블루아워. 일출: 블루아워 → 해 뜸 → 골든아워 */ +function Timeline({ rows, kind = 'sunset' }: { rows?: BestTime[]; kind?: SkyPlanData['kind'] }) { return (
    @@ -75,18 +92,14 @@ function Timeline({ rows }: { rows?: BestTime[] }) {
{rows && (
- {rows.some((t) => t.kind === 'golden') && ( -
-
골든아워
-
해가 낮게 떠 햇빛이 금빛으로 물드는 시간, 해 지기 전 약 30분~1시간
-
- )} - {rows.some((t) => t.kind === 'blue') && ( -
-
블루아워
-
해가 진 뒤 하늘이 짙은 푸른빛으로 남는 시간, 적힌 시각쯤 어두워져요
-
- )} + {rows + .filter((t) => t.kind === 'golden' || t.kind === 'blue') + .map((t) => ( +
+
{t.label}
+
{TERMS[kind][t.kind as 'golden' | 'blue']}
+
+ ))}
)}
@@ -140,8 +153,10 @@ export function SkyPage() { const plan = 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 target = plan?.kind === 'sunrise' ? sky.data?.sunrise : sky.data?.days?.find((d) => d.day === plan?.day) + const sunAt = plan?.timeline?.find((t) => t.kind === 'sun')?.at + const rise = plan?.kind === 'sunrise' + const word = rise ? '일출' : '노을' return (
@@ -151,25 +166,25 @@ export function SkyPage() { {(plan || load === 'loading') && } - + {plan?.timeline?.length || load === 'loading' ? ( - + ) : ( } className="inset-x-3 top-3 bottom-0" /> )} {/* 더 나은 날이 있을 때만 */} {plan?.outlook &&

{plan.outlook}

} - - {spots.length ? ( + {!rise && } + {rise ? null : spots.length ? (