From d082e713166383f8aa905728a2faf8581aa0290f Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 29 Oct 2026 15:25:06 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=EB=9F=AC=EB=8B=9D=EA=B0=81=EC=9D=B4=20?= =?UTF-8?q?=EB=B9=84=C2=B7=EC=B6=94=EC=9C=84=C2=B7=EB=82=AE=20=EC=8B=9C?= =?UTF-8?q?=EA=B0=84=EC=97=90=EB=8F=84=20=EC=9C=84=EC=97=90=20=EB=9C=A8?= =?UTF-8?q?=EB=8D=98=20=EA=B2=83=20=E2=80=94=20=ED=99=9C=EB=8F=99=20?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=EB=8C=80(6~8=EC=8B=9C=C2=B719~22=EC=8B=9C)?= =?UTF-8?q?=20=EB=B0=96=20=EA=B5=AC=EA=B0=84=EC=9D=80=20=EC=B5=9C=EB=8C=80?= =?UTF-8?q?=2050=EC=A0=90,=20=EB=B9=84=20=ED=99=95=EB=A5=A0=2060%=20?= =?UTF-8?q?=EC=9D=B4=EC=83=81=2030=EC=A0=90=C2=B770%=20=EC=9D=B4=EC=83=81?= =?UTF-8?q?=200=EC=A0=90,=20=EC=B2=B4=EA=B0=90=205=C2=B0=20=EB=AF=B8?= =?UTF-8?q?=EB=A7=8C=2040=EC=A0=90=C2=B70=C2=B0=20=EB=AF=B8=EB=A7=8C=200?= =?UTF-8?q?=EC=A0=90,=20=EA=B0=95=ED=92=8D=C2=B7=EB=8F=8C=ED=92=8D=C2=B7?= =?UTF-8?q?=EB=AF=B8=EC=84=B8=EB=A8=BC=EC=A7=80=C2=B7=EB=8D=94=EC=9C=84=20?= =?UTF-8?q?=EC=83=81=ED=95=9C,=20=EC=A0=90=EC=88=98=20=EA=B5=AC=EA=B0=84?= =?UTF-8?q?=20=EB=AC=B8=EA=B5=AC=20=EA=B5=90=EC=B2=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 지수 0점 조건에서 time_matches(활동 시간대 일치)를 볼 수 있게 함 (다른 각은 그대로) - 편한 체감 5~18°(최적 12°), 바람 잔잔 기준 3m/s·한계 8m/s - FAQ·각 계산기준 문서 갱신 (검토: Codex gpt-6-astra) --- backend/docs/index-draft.html | 2 +- backend/docs/각_계산기준.md | 16 ++--- backend/seed/index_definition.json | 76 +++++++++++++++++++++--- backend/services/calc/index_calc.py | 3 + backend/tests/test_index_calc.py | 91 +++++++++++++++++++++++++++++ backend/tests/test_index_slots.py | 41 ++++++++++++- frontend/seo/faq.json | 4 +- 7 files changed, 215 insertions(+), 18 deletions(-) diff --git a/backend/docs/index-draft.html b/backend/docs/index-draft.html index a8c14c4..ef66ede 100644 --- a/backend/docs/index-draft.html +++ b/backend/docs/index-draft.html @@ -70,7 +70,7 @@ td.n{white-space:nowrap;font-weight:600} 등산 가을7~12시30·25·20·10·10·5범위 10~20° (정상 기준 −6°)마를수록잔잔 ≤4, 한계 12범위주말 100, 평일 50비 확률 70% 이상, 강풍주의보등산로 통제, 낙석 세차오늘 + 앞으로 이틀5·60·10·10·10·5범위 5~28°마를수록 (이틀 최대)잔잔 ≤4, 한계 10낮을수록낮 100, 밤 40이틀 안 비 70% 이상 → 20점 아래황사·꽃가루 캠핑 가을18~다음날 8시30·25·15·15·10·5범위 12~22°마를수록잔잔 ≤3, 한계 9낮을수록 (이슬)금·토 100, 평일 60비 확률 60% 이상, 강풍캠핑장 예약 -러닝6~8시, 19~22시 중 좋은 쪽35·20·10·20·10·5범위 8~18°마를수록잔잔 ≤4, 한계 10낮을수록아침·저녁 100, 늦은 밤 40체감 35° 이상, 비 확률 90% 이상노면 상태 +러닝6~8시, 19~22시 (지금 순위는 구간별, 하루 점수는 좋은 쪽)35·20·10·15·15·5범위 5~18°, 최적 12° (5~8°도 좋음)마를수록잔잔 ≤3, 한계 8낮을수록활동 시간대와 겹치면 100, 아니면 0 (시간 비중 5%). 현재 구간은 남은 시간만 평가0점: 비 소식, 비 확률 70% 이상, 체감 0° 미만·35° 이상, 바람 8m/s 이상, 돌풍 15m/s 이상, 강풍 특보, 초미세먼지 75㎍/㎥ 이상
최대 30점: 비 확률 60% 이상, 바람 6m/s 이상, 초미세먼지 36㎍/㎥ 이상, 체감 28° 이상
최대 40점: 체감 5° 미만
최대 50점: 활동 시간대와 겹치지 않는 구간 (더 낮은 상한 우선)노면 상태 별보기 가을21~02시5·15·5·10·20·45범위 5~25°마를수록잔잔 ≤5, 한계 12낮을수록달이 어두울수록 100 (보름 20)하늘 흐림(전체 구름) 80% 이상도시 불빛 (지역 평균만) 짬뽕각 재미11~14시, 17~20시40·25·15·10·5·5낮을수록 (25° 0점 → 5° 100점)올수록셀수록높을수록식사 시간 100없음실제 주문량 검증 전 막걸리각 재미17~22시15·50·10·15·5·5낮을수록 (28° 0점 → 10° 100점)올수록셀수록높을수록금·토 100, 평일 50없음실제 판매량 검증 전 diff --git a/backend/docs/각_계산기준.md b/backend/docs/각_계산기준.md index 31525ec..5cf83f2 100644 --- a/backend/docs/각_계산기준.md +++ b/backend/docs/각_계산기준.md @@ -259,20 +259,22 @@ - 설명: 뛰기 좋은 정도 (아침·저녁 중 좋은 쪽) - 분류: 밖에서 놀기 · 중요도 상 · 아이콘 `running` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음 - 시간대: 6~8시 / 19~22시 +- 지금 순위는 구간별 날씨로 계산하며 현재 구간은 남은 시각만 평가합니다. 하루 점수는 활동 시간대 중 좋은 쪽을 씁니다. - 요소별 규칙 (비중): - - 기온 35%: 체감 8~18°가 좋음 + - 기온 35%: 체감 5~18°가 좋음 (최적 12°, 5~8°도 좋은 점수 유지) - 비 20%: 비 안 올수록 좋음 - - 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점) + - 바람 10%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 8m면 0점) - 습도 15%: 낮을수록 좋음 (90%=0점 → 40%=100점) - 미세먼지 15%: 초미세먼지 낮을수록 좋음 - - 시간·요일 5%: 고정 100점 -- 점수 깎이는 조건: 비 소식이 있으면 0점, 체감 35° 이상이면 0점, 비 확률 70% 이상이면 0점 + - 시간·요일 5%: 활동 시간대와 겹치면 100점, 겹치지 않으면 0점 +- 점수 깎이는 조건: 비 소식이 있으면 0점, 체감 35° 이상이면 0점, 비 확률 70% 이상이면 0점, 체감 0° 미만이면 0점, 강풍 특보가 있으면 0점, 바람 8m/s 이상이면 0점, 돌풍 15m/s 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점, 비 확률 60% 이상이면 최대 30점, 바람 6m/s 이상이면 최대 30점, 초미세먼지 36㎍/㎥ 이상이면 최대 30점, 체감 28° 이상이면 최대 30점, 체감 5° 미만이면 최대 40점, 활동 시간대가 아니면 최대 50점 +- 상한이 겹치면 더 낮은 상한을 우선하도록 0점 → 최대 30점 → 최대 40점 → 최대 50점 순서로 조건을 둡니다. 중기예보 예상 점수에는 비 확률 상한만 적용됩니다. - 반영 못 하는 것: 노면 상태는 반영하지 못해요 - 점수 구간별 설명 (상세 창에 나옴): - - 0~29점: 체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로! - - 30~59점: 덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭! + - 0~29점: 밖에서 뛰기엔 날씨가 험해요. 오늘은 러닝머신으로! + - 30~59점: 지금은 뛰기 애매해요. 아침·저녁에 짧게 가볍게! - 60~79점: 뛸 만해요! 아침·저녁 중 시원한 쪽 고르기. - - 80~100점: 8~18°에 공기 보송, 기록 갱신각 🏃 + - 80~100점: 선선하고 공기 보송, 기록 갱신각 🏃 ### 별보기각 (`stars`) diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index 0c602f7..a02e334 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -717,16 +717,17 @@ "factor_rules": { "temp": { "type": "range", - "lo": 8, - "hi": 18 + "lo": 5, + "hi": 18, + "best": 12 }, "rain": { "dir": "dry" }, "wind": { "type": "calm", - "ok": 4, - "limit": 10 + "ok": 3, + "limit": 8 }, "humidity": { "type": "lower" @@ -751,14 +752,75 @@ "field": "rain_prob", "op": ">=", "value": 70 + }, + { + "field": "feels_c", + "op": "<", + "value": 0 + }, + { + "field": "warning", + "op": "==", + "value": "wind" + }, + { + "field": "wind_ms", + "op": ">=", + "value": 8 + }, + { + "field": "gust_ms", + "op": ">=", + "value": 15 + }, + { + "field": "pm25", + "op": ">=", + "value": 75 + }, + { + "field": "rain_prob", + "op": ">=", + "value": 60, + "cap": 30 + }, + { + "field": "wind_ms", + "op": ">=", + "value": 6, + "cap": 30 + }, + { + "field": "pm25", + "op": ">=", + "value": 36, + "cap": 30 + }, + { + "field": "feels_c", + "op": ">=", + "value": 28, + "cap": 30 + }, + { + "field": "feels_c", + "op": "<", + "value": 5, + "cap": 40 + }, + { + "field": "time_matches", + "op": "==", + "value": false, + "cap": 50 } ], "limit_description": "노면 상태는 반영하지 못해요", "sentences": { - "0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!", - "30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!", + "0": "밖에서 뛰기엔 날씨가 험해요. 오늘은 러닝머신으로!", + "30": "지금은 뛰기 애매해요. 아침·저녁에 짧게 가볍게!", "60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.", - "80": "8~18°에 공기 보송, 기록 갱신각 🏃" + "80": "선선하고 공기 보송, 기록 갱신각 🏃" }, "sort_order": 9, "priority": 1, diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index f807a15..7dc9fdb 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -270,6 +270,8 @@ def _cond(r: dict) -> tuple[str, str, str]: return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면" if r["field"] == "rain_before": return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면" + if r["field"] == "time_matches": + return "활동 시간대가 아니라", "활동 시간대가 아니거나", "활동 시간대가 아니면" base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}" return f"{base}이라", f"{base}이거나", f"{base}이면" @@ -358,6 +360,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re "snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no", "rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)), "rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no", + "time_matches": ctx.time_matches, } reason, cap = _zero(definition.zero_rules, agg) if reason is not None: diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 2bb97c4..549fb6c 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -68,6 +68,18 @@ def test_time_matching_does_not_replace_weekday_score(): assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100 +def test_time_mismatch_cap_only_applies_outside_activity_hours(): + limit = [{"field": "time_matches", "op": "==", "value": False, "cap": 50}] + defn = _defn(factor_rules=_defn().factor_rules | {"time": {"type": "fixed", "value": 100}}, zero_rules=limit) + matched = evaluate(defn, [[_h(7, wind=1.0)]], CTX) + unmatched = evaluate(defn, [[_h(12, wind=1.0)]], replace(CTX, time_matches=False)) + assert matched.score == 100 and matched.zero_reason is None + assert unmatched.score == 50 and unmatched.zero_reason == "활동 시간대가 아니라 최대 50점" + assert zero_rules_text(limit) == "활동 시간대가 아니면 최대 50점" + assert zero_rules_text(limit + [{"field": "rain_prob", "op": ">=", "value": 60, "cap": 50}]) == \ + "활동 시간대가 아니거나 비 확률 60% 이상이면 최대 50점" + + def test_good_but_not_perfect_stays_below_100(): assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95 @@ -275,6 +287,85 @@ def _seed_score(code, day=_SAT, pm25=10, **hour): return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score +@pytest.mark.parametrize("prob, ceiling", [(60, 30), (69, 30), (70, 0)]) +def test_running_high_rain_probability_limits_score(prob, ceiling): + assert _seed_score("running", feels=12, prob=prob) <= ceiling + + +@pytest.mark.parametrize("rain", [RainType.RAIN, RainType.SNOW, RainType.SLEET]) +def test_running_any_precipitation_in_window_is_zero(rain): + hours = [_h(6, feels=12), _h(7, feels=12, prob=10, rain=rain)] + result = evaluate(_SEED["running"], [hours], CTX) + assert result.score == 0 and result.zero_reason == "비 소식이 있어 0점" + + +@pytest.mark.parametrize("feels, ceiling", [(-3, 0), (0, 40), (2, 40), (3, 40), (4.9, 40), (28, 30), (35, 0)]) +def test_running_cold_and_heat_limit_score(feels, ceiling): + assert _seed_score("running", feels=feels) <= ceiling + + +def test_running_cold_limit_uses_coldest_hour(): + hours = [_h(6, feels=3), _h(7, feels=12)] + assert evaluate(_SEED["running"], [hours], CTX).score <= 40 + + +@pytest.mark.parametrize("hour", [6, 7, 19, 21]) +@pytest.mark.parametrize("feels", [5, 8, 10, 12, 15]) +def test_running_clear_cool_morning_and_evening_stay_good(hour, feels): + result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], CTX) + assert result.score >= 80 and result.zero_reason is None + + +@pytest.mark.parametrize("hour, feels", [(12, 12), (12, 14), (12, 25), (22, 12), (26, 12)]) +def test_running_outside_activity_hours_stays_low(hour, feels): + result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False)) + assert result.factors["time"] == 0 and result.score <= 50 + + +@pytest.mark.parametrize("wind, ceiling", [(6, 30), (8, 0)]) +def test_running_strong_wind_limits_score(wind, ceiling): + assert _seed_score("running", feels=12, wind=wind) <= ceiling + + +def test_running_strong_gust_is_zero(): + assert _seed_score("running", feels=12, gust_ms=15) == 0 + + +@pytest.mark.parametrize("pm25, ceiling", [(36, 30), (75, 0)]) +def test_running_bad_air_limits_score(pm25, ceiling): + assert _seed_score("running", feels=12, pm25=pm25) <= ceiling + + +def test_running_wind_warning_is_zero(): + assert evaluate(_SEED["running"], [[_h(6, feels=12)]], replace(CTX, wind_warning=True)).score == 0 + + +@pytest.mark.parametrize("hour", [dict(prob=60, feels=3), dict(prob=60, feels=35), dict(prob=60, wind=8)]) +@pytest.mark.parametrize("time_matches", [True, False]) +def test_running_stricter_limits_win_when_conditions_overlap(hour, time_matches): + result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], replace(CTX, time_matches=time_matches)) + assert result.score <= (30 if hour.get("feels") == 3 else 0) + + +@pytest.mark.parametrize("time_matches", [True, False]) +@pytest.mark.parametrize("hour", [dict(feels=12), dict(feels=20, hum=80), dict(feels=3, prob=60), dict(feels=12, wind=8, rain=RainType.RAIN)]) +def test_other_definitions_ignore_unused_time_match_condition(time_matches, hour): + from unittest.mock import patch + + from services.calc import index_calc + + ctx = replace(CTX, time_matches=time_matches, pm25=30) + windows = [[_h(7, **hour)]] + zero = index_calc._zero + for code, defn in _SEED.items(): + if code == "running": + continue + assert all(r["field"] != "time_matches" for r in defn.zero_rules) + actual = evaluate(defn, windows, ctx) + with patch.object(index_calc, "_zero", side_effect=lambda rules, agg: zero(rules, {k: v for k, v in agg.items() if k != "time_matches"})): + assert actual == evaluate(defn, windows, ctx), code + + @pytest.mark.parametrize("code, good, bad", [ ("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)), ("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)), diff --git a/backend/tests/test_index_slots.py b/backend/tests/test_index_slots.py index 13207af..ad14fae 100644 --- a/backend/tests/test_index_slots.py +++ b/backend/tests/test_index_slots.py @@ -1,10 +1,13 @@ +import json +from dataclasses import replace from datetime import date, timedelta +from pathlib import Path from types import SimpleNamespace from common.enums import RainType, Sky from common.utils.kma_time import kst_midnight from services.calc.index_calc import Context, DayForecast -from services.index_service import day_result, slot_days, slot_label +from services.index_service import day_result, slot_days, slot_label, slot_results REGION = SimpleNamespace(lat=37.56, lon=126.97) SAT = date(2026, 10, 10) @@ -18,6 +21,7 @@ DEFN = SimpleNamespace( zero_rules=[], windows=[{"from": 11, "to": 16}], ) FC = {SAT: DayForecast(temp_min_c=12, temp_max_c=22, rain_prob_am=10, rain_prob_pm=20, sky=Sky.CLEAR)} +RUNNING = SimpleNamespace(**next(x for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8")) if x["code"] == "running")) def _hourly(day: date) -> dict: @@ -71,3 +75,38 @@ def test_partial_hourly_falls_back_to_estimate(): def test_no_mid_forecast_gives_no_score(): assert day_result(DEFN, SAT, REGION, {}, {}, CTX, short=False) is None + + +def test_running_slot_rain_outside_activity_hours_still_zero(): + start = kst_midnight(SAT) + hourly = _hourly(SAT) + for row in hourly.values(): + row.feels_c = 12 + hourly[start + timedelta(hours=9)].rain_type = RainType.RAIN.value + results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, start + timedelta(hours=18)) + assert results["morning"].score == 0 + assert results["morning"].zero_reason == "비 소식이 있어 0점" + assert results["night"].score >= 80 + + +def test_running_slots_lower_day_and_late_night_but_keep_activity_hours(): + start = kst_midnight(SAT) + hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1)) + for row in hourly.values(): + row.feels_c = 25 if 11 <= row.forecast_at.hour < 16 else 12 + sunset = start + timedelta(hours=18) + results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset) + assert results["morning"].score >= 80 and results["night"].score >= 80 + assert results["day"].score <= 50 and results["early"].score <= 50 + late = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=22)) + assert late["night"].factors["time"] == 0 and late["night"].score <= 50 + + +def test_running_muggy_morning_does_not_exceed_original_weather_score(): + start = kst_midnight(SAT) + hourly = _hourly(SAT) + for row in hourly.values(): + row.feels_c, row.humidity, row.wind_ms = 20, 80, 1.5 + results = slot_results(RUNNING, SAT, REGION, hourly, {}, replace(CTX, pm25=30), start + timedelta(hours=18)) + assert results["morning"].factors["time"] == 100 + assert results["morning"].score <= 67 diff --git a/frontend/seo/faq.json b/frontend/seo/faq.json index 2063142..414a903 100644 --- a/frontend/seo/faq.json +++ b/frontend/seo/faq.json @@ -16,7 +16,7 @@ }, { "q": "더운 날 뭐 하면 좋을까요?", - "a": "더운 날엔 낮엔 물놀이·빙수·냉면, 운동은 해 뜨기 전 아침이나 해 진 뒤가 좋아요. 러닝각은 체감 35° 이상이면 0점이라 아침 6~8시나 저녁 7~10시 중 시원한 쪽을 고르세요. 빨래는 잘 마르니 이불 빨래하기 좋은 날이에요." + "a": "더운 낮에는 물놀이·빙수·냉면, 운동은 선선한 아침이나 저녁이 좋아요. 러닝각은 체감 28° 이상이면 최대 30점, 35° 이상이면 0점이에요." }, { "q": "추운 날 뭐 하면 좋을까요?", @@ -45,7 +45,7 @@ }, { "q": "러닝하기 좋은 날씨와 시간은 언제인가요?", - "a": "러닝은 체감 8~18°에 습도가 낮고 바람이 잔잔한 날이 좋아요. 러닝각은 아침 6~8시와 저녁 7~10시 날씨로 계산해 둘 중 좋은 쪽 점수를 보여 드려요." + "a": "러닝각은 체감 5~18°를 편한 범위로 보고 12° 부근을 가장 높게 평가해요. 비 소식이나 높은 비 확률, 체감 5° 미만의 추위에는 점수를 크게 낮춰요. 활동 시간대인 6~8시·19~22시와 겹치지 않는 구간은 최대 50점이에요." }, { "q": "캠핑하기 좋은 날씨는 언제인가요?",