diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index fb1fb77..d69251e 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -156,6 +156,13 @@ class HeroStat(WebPacketProtocol): tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)") +class WeatherWhy(WebPacketProtocol): + label: str + weight: int = Field(description="비중 % (합 100)") + score: int = Field(description="이 조건 점수 0~100") + note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)") + + class Hero(WebPacketProtocol): now_at: datetime sky_mode: Literal["morning", "day", "sunset", "night"] @@ -168,6 +175,7 @@ class Hero(WebPacketProtocol): will_rain_2h: Optional[bool] = None weather_score: Optional[int] = None weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}") + weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="구간별 날씨 점수 근거(조건·비중·조건 점수·지금 값). 키는 weather_slots 와 같다") top1: Optional[TopIndex] = None bubble: Optional[str] = None moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달") diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index dca83b1..5b1a6c6 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -22,7 +22,7 @@ from crud.season_crud import SeasonCRUD from crud.weather_crud import WeatherCRUD from router.v1.feed.protocol import ( BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide, - PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide, + PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide, ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import pm10_grade, pm25_grade @@ -443,6 +443,7 @@ class FeedService: 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, weather_slots=board.weather_slots if board else {}, + weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.weather_why.items()} if board else {}, top1=_top(top) if top else None, bubble=bubble, moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None, stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)], diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 2837ea4..2a482a5 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -40,6 +40,26 @@ WEATHER_SCORE_DEF = SimpleNamespace( }, zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}], ) +WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"} + + +def strict_weather(raw: int) -> int: + """날씨 점수는 높을수록 깐깐하게: 90점까지는 8/9, 그 위는 두 배로 깎아 100점은 모든 조건이 완벽할 때만 (96 → 92).""" + return round(raw * 8 / 9) if raw <= 90 else round(80 + (raw - 90) * 2) + + +@dataclass +class WeatherWhy: + label: str + weight: int + score: int + note: str + + +def weather_why(r: Result) -> list[WeatherWhy]: + """날씨 점수를 이룬 조건들. 비중 큰 것부터.""" + axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}")) + return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes] SEASONS = ("겨울", "봄", "여름", "가을") @@ -83,6 +103,7 @@ class IndexBoard: weather_score: Optional[int] items: list[IndexItem] weather_slots: dict[str, int] = field(default_factory=dict) + weather_why: dict[str, list[WeatherWhy]] = field(default_factory=dict) @property def ranked(self) -> list[IndexItem]: @@ -187,7 +208,7 @@ def shown_slot(key: str) -> str: return "night" if key == EARLY else key -def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]: +def _shown_parts(parts: dict, cur: str) -> dict: """구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다.""" shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)} return {k: shown[k] for k in SLOTS if k in shown} @@ -362,7 +383,9 @@ class IndexService: trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False, )) return ErrorType.SUCCESS, IndexBoard( - region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur), + region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items, + weather_slots=_shown_parts({k: r.score for k, r in weather_parts.items()}, cur), + weather_why=_shown_parts({k: weather_why(r) for k, r in weather_parts.items()}, cur), ) async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]: @@ -395,7 +418,7 @@ class IndexService: out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)}) return ErrorType.SUCCESS, (shown_slot(cur), out) - async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]: + async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, Result]]]: """재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다.""" _, _, _, warnings, ultra = await asyncio.gather( self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now), @@ -426,7 +449,7 @@ class IndexService: ) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx) sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at - weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()} + weather_parts = {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()} issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) inputs_at = max(issued, air.measured_at) if air else issued diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 936788d..686ef44 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -14,9 +14,12 @@ from common.utils.kma_time import kst_midnight, now_kst from crud.region_crud import RegionCRUD from crud.weather_crud import WeatherCRUD from router.router import app -from services.calc.index_calc import rank_score +from services.calc.index_calc import AXES, Result, rank_score from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for +_RESULT_50 = Result(score=50, factors={a: 50 for a in AXES}, notes={}, zero_reason=None, summary="") +_WEATHER_50 = {k: _RESULT_50 for k in ("morning", "day", "evening", "night", "early")} + REGION = "1141000000" @@ -142,7 +145,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) - monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50}))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, _WEATHER_50))) _, board = await service.board(REGION) view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items] # 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만 @@ -162,7 +165,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch): scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) - monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50}))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, _WEATHER_50))) err, board = await service.board(REGION) assert err is ErrorType.SUCCESS # 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로 @@ -179,7 +182,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) - monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every}))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: _RESULT_50 for k in every}))) monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"])) _, board = await service.board(REGION) ranks = {i.definition.code: i.slot_ranks for i in board.items} diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 1f80e31..8c08f77 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -340,3 +340,26 @@ def test_umbrella_lost_needs_rain_that_stopped(): assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80 assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점" assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0 + + +def test_weather_score_is_strict_near_top(): + """좋은 날(96)도 92 수준, 100점은 모든 조건이 완벽할 때만. 낮은 점수도 조금씩 내려간다.""" + from services.index_service import strict_weather + + assert strict_weather(100) == 100 + assert strict_weather(96) == 92 + assert strict_weather(99) < 100 + assert strict_weather(75) < 75 + scores = [strict_weather(s) for s in range(101)] + assert scores == sorted(scores) + + +def test_weather_why_lists_every_condition_heaviest_first(): + from services.index_service import WEATHER_SCORE_DEF, weather_why + + ctx = Context(day=date(2026, 10, 2), is_holiday=False, pm25=12, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) + r = evaluate(WEATHER_SCORE_DEF, [[_h(h, feels=19.0, prob=0, wind=2.0, hum=55, sunshine_ratio=0.9) for h in range(9, 22)]], ctx) + why = weather_why(r) + assert [w.label for w in why] == ["기온", "비", "햇볕", "바람", "습도", "미세먼지"] + assert sum(w.weight for w in why) == 100 + assert why[0].note.startswith("체감 19°")