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/30] =?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/30] =?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/30] =?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 5a5f585bdac9726824b0194a18658e9589badfd8 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:09:12 +0900 Subject: [PATCH 04/30] =?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 05/30] =?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 06/30] =?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 ? (
    {spots.map((p) => (
  • From 3a73a44cb0e5df1063eab4ea59d79b7076742d24 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:20:06 +0900 Subject: [PATCH 07/30] =?UTF-8?q?feat:=20=ED=9E=88=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=B9=B8=EC=9D=84=20=EC=A7=80=EA=B8=88=C2=B7=EC=8A=B5=EB=8F=84?= =?UTF-8?q?=C2=B7=EB=B6=88=EC=BE=8C=EC=A7=80=EC=88=98=C2=B7=EC=83=81?= =?UTF-8?q?=ED=99=A9=201=EC=B9=B8=EC=9C=BC=EB=A1=9C=20=E2=80=94=20?= =?UTF-8?q?=EC=8A=B5=EB=8F=84=C2=B7=EB=B6=88=EC=BE=8C=EC=A7=80=EC=88=98=20?= =?UTF-8?q?=EB=8A=98=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 2 +- backend/router/v1/feed/protocol.py | 5 +++-- backend/services/feed_service.py | 3 ++- backend/services/hero_stats.py | 12 ++---------- backend/tests/test_hero_stats.py | 13 +++++++------ frontend/src/api/client/types.gen.ts | 10 +++++++++- frontend/src/b/TodayPage.tsx | 9 +++++++-- 7 files changed, 31 insertions(+), 23 deletions(-) diff --git a/TODO.md b/TODO.md index 2a54985..b880681 100644 --- a/TODO.md +++ b/TODO.md @@ -143,7 +143,7 @@ | [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` | | [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 3) | 10/8 회의 결정 | `backend/services/index_service.py:203` | | [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` | -| [ ] | 히어로에 습도·불쾌지수 항상 표시 — 지금은 상황별 두 칸이라 불쾌지수는 일정 수치 이상일 때만 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | +| [x] | 히어로에 습도·불쾌지수 항상 표시 → 4칸(지금·습도·불쾌지수·상황 1칸, 사용자 결정). 불쾌지수 75 이상이면 경고 색, 상황 칸 후보에서 불쾌지수 뺌 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | | [ ] | 달 '밝기 %' 정의(밝기인지 보이는 면적인지) + 구름·달 모양 반영 산정 로직 | 10/8 회의 | `backend/services/calc/moon.py` | | [x] | 노을: 점수 강조(히어로에 점수 크게) + 골든아워·블루아워 설명. 결론은 다음에 오는 것(해 뜨기 전·밤엔 일출, 그 사이엔 노을)으로, 피드 노을 카드도 같이 (사용자 결정 '각·노을도 지금 기준') | 10/8 회의, 사용자 결정 | `frontend/src/b/SkyPage.tsx`, `backend/services/sky_service.py` | | [ ] | 주말 예보 UI 개선 — 회의에서 구체 내용 없음 | 10/8 회의 | `frontend/src/b/WeekPage.tsx` | diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index b495804..f5d3d74 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -146,7 +146,8 @@ class Hero(WebPacketProtocol): sky_mode: Literal["morning", "day", "sunset", "night"] temp_c: Optional[float] = None feels_c: Optional[float] = None - discomfort: Optional[int] = None + humidity: Optional[int] = Field(default=None, description="지금 습도 %. 히어로에 늘 보인다") + discomfort: Optional[int] = Field(default=None, description="지금 불쾌지수. 히어로에 늘 보인다") discomfort_label: Optional[str] = None rain_2h_text: Optional[str] = None will_rain_2h: Optional[bool] = None @@ -155,7 +156,7 @@ class Hero(WebPacketProtocol): bubble: Optional[str] = None moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달") moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100") - stats: list[HeroStat] = Field(default_factory=list, description="히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저") + stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저") class BandEvent(WebPacketProtocol): diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 90e5ed9..a84a49e 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -144,7 +144,7 @@ def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: O rain_later_at=later, today_known=bool(ahead), air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv, temp_min=min(temps, default=None), temp_max=max(temps, default=None), - temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None, + temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, moon=phase_name(_tonight(now)), ) @@ -430,6 +430,7 @@ class FeedService: return Hero( now_at=now, sky_mode=_SKY_MODE[slot], temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None, + humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None, rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None, weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble, diff --git a/backend/services/hero_stats.py b/backend/services/hero_stats.py index 02b501c..031f777 100644 --- a/backend/services/hero_stats.py +++ b/backend/services/hero_stats.py @@ -12,8 +12,7 @@ Tone = Literal["normal", "warn", "rain"] UV_HIGH = 6.0 TEMP_SWING_C = 10.0 WIND_CHILL_C = 3.0 -MUGGY = 75 -SHOWN = 2 +SHOWN = 1 @dataclass(frozen=True) @@ -38,7 +37,6 @@ class HeroInput: temp_max: Optional[float] = None temp: Optional[float] = None feels: Optional[float] = None - discomfort: Optional[int] = None moon: Optional[str] = None @@ -46,16 +44,12 @@ def uv_label(uv: float) -> str: return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험" -def _discomfort_label(v: int) -> str: - return "보통" if v < 75 else "높음" if v < 80 else "매우 높음" - - def _rain_value(now: datetime, at: datetime) -> str: return "지금 와요" if at <= now else f"{hour_label(at.astimezone(KST).hour)}쯤 와요" def hero_stats(x: HeroInput) -> list[HeroStatItem]: - """히어로 두 칸. 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다.""" + """히어로 상황 칸 (습도·불쾌지수는 늘 따로 보인다). 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다.""" alerts: list[HeroStatItem] = [] if x.rain_at is not None: alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain")) @@ -69,8 +63,6 @@ def hero_stats(x: HeroInput) -> list[HeroStatItem]: alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷")) if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C: alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀")) - if x.discomfort is not None and x.discomfort >= MUGGY: - alerts.append(HeroStatItem("muggy", "muggy", "불쾌지수", f"{x.discomfort} · {_discomfort_label(x.discomfort)}", "warn")) # 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다 fills: list[HeroStatItem] = [] diff --git a/backend/tests/test_hero_stats.py b/backend/tests/test_hero_stats.py index d7b0cc0..fb0ef59 100644 --- a/backend/tests/test_hero_stats.py +++ b/backend/tests/test_hero_stats.py @@ -12,8 +12,9 @@ def _view(x: HeroInput) -> list[tuple[str, str, str, str]]: def test_clear_day_shows_uv_warning_and_temp_swing(): - x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23, discomfort=68) - assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn"), ("coldwind", "일교차 10°", "아침엔 겉옷", "normal")] + x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23) + assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn")] + assert _view(HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=2.0, temp_min=13, temp_max=23)) == [("coldwind", "일교차 10°", "아침엔 겉옷", "normal")] def test_rain_comes_first(): @@ -30,12 +31,12 @@ def test_rain_later_today_and_no_rain_today(): def test_bad_air_beats_uv_and_wears_mask(): x = HeroInput(now=NOW, night=False, air=AirGrade.VERY_BAD, uv=7.2) - assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn"), ("glasses", "자외선", "7 · 높음", "warn")] + assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn")] -def test_summer_night_muggy_then_moon_and_no_card_for_no_rain(): - x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, discomfort=80, moon="보름달") - assert _view(x) == [("muggy", "불쾌지수", "80 · 매우 높음", "warn"), ("moon", "오늘 밤 달", "보름달", "normal")] +def test_night_without_alert_shows_moon_and_no_card_for_no_rain(): + x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, moon="보름달") + assert _view(x) == [("moon", "오늘 밤 달", "보름달", "normal")] def test_one_coldwind_card_only(): diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 90127a9..6971d57 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -561,8 +561,16 @@ export type Hero = { * Feels C */ feels_c?: number | null; + /** + * Humidity + * + * 지금 습도 %. 히어로에 늘 보인다 + */ + humidity?: number | null; /** * Discomfort + * + * 지금 불쾌지수. 히어로에 늘 보인다 */ discomfort?: number | null; /** @@ -601,7 +609,7 @@ export type Hero = { /** * Stats * - * 히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저 + * 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저 */ stats?: Array; }; diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 584fca8..18ff165 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -31,7 +31,8 @@ const PREVIEW: Record } // 히어로 칸을 받아 오는 동안 자리만 잡아 둔다 -const STAT_HOLD = ['a', 'b'] +const STAT_HOLD = ['a'] +const MUGGY = 75 // 불쾌지수 이 이상이면 경고 색 const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 })) // 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게 @@ -131,9 +132,13 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {