From b0e6a011572d5d998a867a6cd5d41589ea6cd95e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Mon, 23 Nov 2026 16:22:50 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=EC=A7=80=EA=B8=88=20=EB=B9=84=EA=B0=80?= =?UTF-8?q?=20=EC=98=A4=EB=8A=94=EB=8D=B0=20'=EB=B9=84=2060%'=C2=B7'5?= =?UTF-8?q?=EC=8B=9C=EC=AF=A4=20=EB=B9=84=EA=B0=80=20=EC=99=80=EC=9A=94'?= =?UTF-8?q?=EB=A1=9C=20=EB=82=98=EC=98=A4=EB=8D=98=20=EB=AC=B8=EA=B5=AC=20?= =?UTF-8?q?=E2=80=94=20=EC=8B=A4=ED=99=A9=EC=9C=BC=EB=A1=9C=20=EB=B3=B8=20?= =?UTF-8?q?=EB=8C=80=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 지금 구간 한 줄(히어로·각): 실황으로 관측한 시각은 예보 확률 대신 본 대로 씀. 비가 오면 '비 오는 중'(눈·진눈깨비도), 비가 없으면 확률 없이 바람·하늘. 비가 관측됐는데 예보 확률이 낮아 '바람 조금'으로 나오던 것도 같이 고쳐짐. 예보 시각(다른 구간·내일)은 그대로 확률 - 2시간 비 안내: 실황이 지금 비를 관측했으면 앞으로의 예보보다 먼저 '지금 비가 와요. 우산 챙기세요' - 매시 00~10분은 그 시각 실황이 아직 없어 예보 문구가 나옴 --- backend/services/calc/index_calc.py | 14 +++++--- backend/services/index_service.py | 1 + backend/services/now_service.py | 16 ++++++--- backend/services/weather_service.py | 1 + backend/tests/test_ncst.py | 53 +++++++++++++++++++++++++++++ backend/tests/test_weather_now.py | 29 ++++++++++++++++ 6 files changed, 105 insertions(+), 9 deletions(-) diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index b44a8af..3bfdfdd 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -46,6 +46,7 @@ class Hour: visibility_km: Optional[float] = None gust_ms: Optional[float] = None ground_c: Optional[float] = None + observed: bool = False # 예보가 아니라 초단기실황으로 관측한 시각 (비 확률이 뜻이 없다) @dataclass(frozen=True) @@ -311,12 +312,17 @@ def _summary(hours: list[Hour]) -> str: return summary_line(hours[len(hours) // 2]) +_RAINING_NOW = {RainType.RAIN: "비 오는 중", RainType.SHOWER: "비 오는 중", RainType.SLEET: "진눈깨비 오는 중", RainType.SNOW: "눈 오는 중"} + + def summary_line(mid: Hour) -> str: - """그 시각 날씨 한 줄 (오후 5시 13°, 비 60%).""" + """그 시각 날씨 한 줄 (오후 5시 13°, 비 60%). 실황으로 관측한 시각은 확률 대신 본 대로 쓴다 (오후 4시 11°, 비 오는 중).""" wind = mid.wind_ms - tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else ( - "바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else _SKY_WORD[mid.sky] - ) + calm = "바람 살랑" if wind is not None and wind <= 2 else "바람 조금" if wind is not None and wind <= 5 else "바람 강함" if wind is not None else _SKY_WORD[mid.sky] + if mid.observed: + tag = _RAINING_NOW.get(mid.rain_type, calm) + else: + tag = f"비 {mid.rain_prob}%" if mid.rain_prob >= 50 else calm return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}" diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 869ca2c..ae0c652 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -119,6 +119,7 @@ def _hour(r: WeatherHourly) -> Hour: return Hour( hour=r.forecast_at.astimezone(KST).hour, feels_c=float(r.feels_c), rain_type=RainType(r.rain_type), rain_prob=r.rain_prob, wind_ms=float(r.wind_ms) if r.wind_ms is not None else None, humidity=r.humidity, sky=Sky(r.sky), + observed=getattr(r, "observed", False), # with_observed 가 실황으로 바꾼 행에만 붙인다 ) diff --git a/backend/services/now_service.py b/backend/services/now_service.py index 3e53cdf..ead15d8 100644 --- a/backend/services/now_service.py +++ b/backend/services/now_service.py @@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD from crud.weather_crud import WeatherCRUD from services.air_service import GRADE_LABEL, AirService from services.warning_service import WarningItem, WarningService -from services.weather_service import RainHour, WeatherService, ultra_hours +from services.weather_service import RainHour, WeatherService, observed_now, ultra_hours _COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19)) @@ -52,7 +52,13 @@ def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]: return {Sky.CLEAR: ("sun", "맑음"), Sky.PARTLY: ("sun_cloud", "구름 많음"), Sky.CLOUDY: ("cloud", "흐림")}[sky] -def _rain_2h_text(hours: list[RainHour]) -> tuple[bool, str]: +_NOW_WORD = {RainType.SNOW: "눈이", RainType.SLEET: "진눈깨비가"} + + +def _rain_2h_text(hours: list[RainHour], now_rain: Optional[RainType] = None) -> tuple[bool, str]: + """now_rain: 실황으로 관측한 지금 비 형태 (관측이 없으면 None). 지금 오는 중이면 앞으로의 예보보다 먼저 알린다.""" + if now_rain is not None and now_rain is not RainType.NONE: + return True, f"지금 {_NOW_WORD.get(now_rain, '비가')} 와요. 우산 챙기세요" rainy = [h for h in hours if h.rain_type is not RainType.NONE] if not rainy: return False, "앞으로 2시간, 우산 없어도 돼요" @@ -98,9 +104,9 @@ class NowService: return ErrorType.NOT_FOUND, None now = now_kst() - ultra, _, _, warnings = await asyncio.gather( + ultra, _, _, warnings, observed = await asyncio.gather( self._ultra(region, now), self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), - self.warning_service.for_region(region, now), + self.warning_service.for_region(region, now), observed_now(region, now), ) tomorrow_start = kst_midnight(now.date() + timedelta(days=1)) err, next_rows = await DB_SESSION_MNG.execute_lambda( @@ -115,7 +121,7 @@ class NowService: hours = [h for h in hours if now < h.at <= now + timedelta(hours=2)] if not hours and not next_rows: return ErrorType.EXTERNAL_API_ERROR, None - will_rain, rain_text = _rain_2h_text(hours) + will_rain, rain_text = _rain_2h_text(hours, observed.rain_type if observed else None) rain_from, tomorrow_text, commute = _tomorrow([r for r in next_rows if r.forecast_at >= tomorrow_start]) air = await self.air_service.nearest(region) air_text = None diff --git a/backend/services/weather_service.py b/backend/services/weather_service.py index 3cdca11..de8f156 100644 --- a/backend/services/weather_service.py +++ b/backend/services/weather_service.py @@ -93,6 +93,7 @@ def with_observed(by_at: dict[datetime, WeatherHourly], obs: Optional[Observed]) **cols, "rain_type": obs.rain_type.value, "rain_mm": obs.rain_mm, "temp_c": obs.temp_c, "humidity": obs.humidity, "wind_ms": obs.wind_ms, "feels_c": feels_like_c(obs.temp_c, obs.humidity, obs.wind_ms, obs.at.month), "discomfort_index": discomfort_index(obs.temp_c, obs.humidity), }) + row.observed = True # DB 칸이 아니라 이 사본에만 붙는 표시: 한 줄 문구가 확률 대신 관측한 대로 쓴다 return {**by_at, obs.at: row} diff --git a/backend/tests/test_ncst.py b/backend/tests/test_ncst.py index 607ca7c..c255e0e 100644 --- a/backend/tests/test_ncst.py +++ b/backend/tests/test_ncst.py @@ -49,6 +49,59 @@ def test_observed_does_nothing_without_an_observation_or_the_hours_row(): assert with_observed(rows, _OBS) == rows +def _line(**kw): + from services.calc.index_calc import Hour, summary_line + + base = dict(hour=16, feels_c=11.0, rain_type=RainType.NONE, rain_prob=60, wind_ms=1.5, humidity=90, sky=Sky.CLOUDY) + return summary_line(Hour(**{**base, **kw})) + + +def test_observed_hour_line_says_it_is_raining_instead_of_a_probability(): + """실황은 관측이라 확률이 없다. 지금 비가 오면 '비 60%' 가 아니라 오는 중이라고 쓴다.""" + assert _line(observed=True, rain_type=RainType.RAIN) == "오후 4시 11°, 비 오는 중" + assert _line(observed=True, rain_type=RainType.SHOWER) == "오후 4시 11°, 비 오는 중" + assert _line(observed=True, rain_type=RainType.SNOW) == "오후 4시 11°, 눈 오는 중" + assert _line(observed=True, rain_type=RainType.SLEET) == "오후 4시 11°, 진눈깨비 오는 중" + + +def test_observed_hour_line_without_rain_never_shows_a_probability(): + """관측으로 비가 없으면 예보 확률이 60% 여도 확률을 쓰지 않는다.""" + assert _line(observed=True) == "오후 4시 11°, 바람 살랑" + assert _line(observed=True, wind_ms=None) == "오후 4시 11°, 흐림" + + +def test_forecast_hour_line_keeps_the_probability(): + assert _line() == "오후 4시 11°, 비 60%" + assert _line(rain_type=RainType.RAIN) == "오후 4시 11°, 비 60%" + + +def test_only_the_observed_row_is_marked_observed(): + from services.index_service import _hour + + rows = {r.forecast_at: r for r in (_hourly(13), _hourly(14))} + out = with_observed(rows, _OBS) + assert _hour(out[_at(14)]).observed is True and _hour(out[_at(13)]).observed is False + + +def test_current_slot_line_of_a_gak_uses_the_observed_rain(): + from datetime import date + + from services.calc.index_calc import Context + from services.index_service import slot_results + + day = date(2026, 10, 8) + defn = 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=[{"from": 9, "to": 20}], + ) + ctx = Context(day=day, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) + by_at = with_observed({r.forecast_at: r for r in (_hourly(h) for h in range(5, 24))}, _OBS) + parts = slot_results(defn, day, SimpleNamespace(lat=37.5, lon=127.0), by_at, {}, ctx, _at(18), _at(14, 20)) + assert parts["day"].summary == "오후 2시 8°, 비 오는 중" + + _ITEMS = [{"category": c, "obsrValue": v} for c, v in {"PTY": "1", "REH": "78", "RN1": "0.3", "T1H": "9.8", "WSD": "4.5"}.items()] diff --git a/backend/tests/test_weather_now.py b/backend/tests/test_weather_now.py index e58402e..ff8902d 100644 --- a/backend/tests/test_weather_now.py +++ b/backend/tests/test_weather_now.py @@ -83,6 +83,35 @@ async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean): assert body["warnings"] == [{"warning_type": 4, "level": 1, "text": "건조주의보"}] +def test_rain_text_says_it_is_raining_now_when_observed(): + """지금 비가 오는 중이면 '몇 시쯤 비가 와요'가 아니라 지금 온다고 쓴다. 관측이 없거나 비가 없으면 앞으로 2시간 예보대로.""" + from common.enums import RainType + from services.now_service import _rain_2h_text + from services.weather_service import RainHour + + at = now_kst().replace(hour=17, minute=0, second=0, microsecond=0) + later = [RainHour(at=at, rain_type=RainType.RAIN, rain_mm=1.0)] + assert _rain_2h_text(later, RainType.RAIN) == (True, "지금 비가 와요. 우산 챙기세요") + assert _rain_2h_text([], RainType.SNOW) == (True, "지금 눈이 와요. 우산 챙기세요") + assert _rain_2h_text([], RainType.SLEET) == (True, "지금 진눈깨비가 와요. 우산 챙기세요") + assert _rain_2h_text(later, RainType.NONE) == (True, "오후 5시쯤 비가 와요. 우산 챙기세요") + assert _rain_2h_text(later, None) == (True, "오후 5시쯤 비가 와요. 우산 챙기세요") + assert _rain_2h_text([], None) == (False, "앞으로 2시간, 우산 없어도 돼요") + + +@pytest.mark.anyio +async def test_now_says_raining_now_from_the_observed_weather(monkeypatch, clean): + """앞으로 2시간 예보엔 비가 없어도 실황이 비를 관측했으면 지금 비가 온다고 알린다.""" + monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage())) + monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra())) + monkeypatch.setattr(weather_service, "fetch_ncst", lambda *a: _async( + [{"category": c, "obsrValue": v} for c, v in {"PTY": "1", "REH": "96", "RN1": "2.5", "T1H": "9.8", "WSD": "2.3"}.items()] + )) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + body = (await client.get("/v1/weather/now", params={"region": REGION})).json() + assert body["rain_2h"]["will_rain"] is True and body["rain_2h"]["text"] == "지금 비가 와요. 우산 챙기세요" + + @pytest.mark.anyio async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean): from services.external.data_go_kr import DataGoKrRequestFailed