fix: 각 점수에 중요도 배율을 반영해 화면 점수와 순위를 일치시킴

This commit is contained in:
skkim committed 2026-10-23 09:14:52 +09:00
1 parent 621a0cf90d
commit d5f8b148b4
12 files changed
+68 -33

No files matched your search

+2 -2
View File
@@ -86,7 +86,7 @@ class WeekDay(WebPacketProtocol):
temp_min_c: Optional[float] = None
temp_max_c: Optional[float] = None
rain_prob: Optional[int] = None
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음")
class WeekSlide(WebPacketProtocol):
@@ -154,7 +154,7 @@ class TopIndex(WebPacketProtocol):
summary: Optional[str] = None
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)")
class HeroStat(WebPacketProtocol):
+2 -2
View File
@@ -5,7 +5,7 @@ import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from services.calc.index_calc import PRIORITY_WEIGHT, _cond # noqa: E402
from services.calc.index_calc import _cond # noqa: E402
SEED = os.path.join(ROOT, "seed", "index_definition.json")
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
@@ -109,7 +109,7 @@ def main() -> None:
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
P("- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.\n")
P("## 한눈에 보기\n")
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
+8 -4
View File
@@ -18,13 +18,17 @@ _FALL_FLOOR = exp(-0.5)
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
_TEMP_PLATEAU = 2
_HUMIDITY_PLATEAU = 5
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
def rank_score(score: int, priority: int) -> float:
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
return score * PRIORITY_WEIGHT[priority]
def priority_score(score: int, priority: int) -> int:
"""중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
return round(score * PRIORITY_WEIGHT[priority])
def rank_score(score: int, priority: int) -> tuple[int, int]:
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
return score, -priority
@dataclass(frozen=True)
+3 -3
View File
@@ -242,7 +242,7 @@ def _by_position(posts: list[Post]) -> list[Post]:
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도)."""
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
@@ -340,7 +340,7 @@ class FeedService:
now = now_kst()
sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at
slot = slot_of(now, sunset_at)
key = f"feed:{region.code}:time-weight-v2:{slot}"
key = f"feed:{region.code}:priority-score-v4:{slot}"
try:
cached = await REDIS.conn.get(key)
if cached:
@@ -813,7 +813,7 @@ _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
"""그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로."""
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
+13 -6
View File
@@ -19,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
@@ -279,6 +279,13 @@ def _with_slot(row: IndexScore, data: dict) -> IndexScore:
return out
def _with_priority(row: IndexScore, priority: int) -> IndexScore:
"""DB의 원점수·요소 점수는 보존하고 응답용 사본의 최종 점수에만 중요도를 적용한다."""
out = IndexScore(**{c.key: getattr(row, c.key, None) for c in IndexScore.__table__.columns})
out.score = priority_score(row.score, priority)
return out
def day_forecast(d: WeatherDaily) -> DayForecast:
return DayForecast(
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
@@ -366,15 +373,15 @@ class IndexService:
row = by_key.get((d.index_id, today))
if row is None or cur not in row.slots:
continue
now_score[d.index_id] = _with_slot(row, row.slots[cur])
now_score[d.index_id] = _with_priority(_with_slot(row, row.slots[cur]), d.priority)
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
items = []
for i, d in enumerate(ranked):
row = by_key[(d.index_id, today)]
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
parts = _shown_parts({k: priority_score(v["score"], d.priority) for k, v in row.slots.items()}, cur)
items.append(IndexItem(
definition=d, score=now_score[d.index_id], rank=i + 1,
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
trend=[now_score[d.index_id] if day == today else _with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key],
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
))
for k in SLOTS:
@@ -385,8 +392,8 @@ class IndexService:
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
row = by_key[(d.index_id, today)]
items.append(IndexItem(
definition=d, score=row, rank=len(items) + 1,
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
definition=d, score=_with_priority(row, d.priority), rank=len(items) + 1,
trend=[_with_priority(by_key[(d.index_id, day)], d.priority) 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[cur].score if cur in weather_parts else None, items=items,
+3 -3
View File
@@ -22,7 +22,7 @@ from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.calc.index_calc import rank_score
from services.calc.index_calc import priority_score, rank_score
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
@@ -291,14 +291,14 @@ class WeekService:
for d in daily:
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
rain_hours = _rain_hours(rows)
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(priority_score(x.score, priority.get(x.index_id, 2)), priority.get(x.index_id, 2)), reverse=True)[:2]
holiday = (holidays or {}).get(d.forecast_date)
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
word = _weather_word(d, rain_hours)
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
is_rainy = d.rain_type != RainType.NONE.value
if top:
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top)
summary = ", ".join(f"{names.get(x.index_id, '')} {priority_score(x.score, priority.get(x.index_id, 2))}점" for x in top)
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
else:
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
+17 -7
View File
@@ -79,8 +79,10 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
seasons = [i["in_season"] for i in body["items"]]
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
for group in (True, False):
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert weighted == sorted(weighted, reverse=True)
scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]]
assert scores == sorted(scores, reverse=True)
order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert order == sorted(order, reverse=True)
today = now_kst().date()
for i in body["items"]:
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
@@ -164,7 +166,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
@pytest.mark.anyio
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
async def test_board_displays_and_ranks_by_priority_adjusted_score(monkeypatch):
today = now_kst().date()
defs = [
SimpleNamespace(index_id=1, code="low", priority=3),
@@ -172,17 +174,25 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
SimpleNamespace(index_id=3, code="high", priority=1),
]
scores = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))]
scores += [_board_score(x, today + timedelta(days=1), v) 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, {now_kst().date(): _WEATHER_50})))
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 68, 2), ("low", 63, 3)]
for item in board.items:
assert item.trend[0].score == item.score.score
assert item.trend[1].score == item.score.score
assert all(value == item.score.score for value in item.slots.values())
# 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다.
assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70]
_, again = await service.board(REGION)
assert [i.score.score for i in again.items] == [70, 68, 63]
@pytest.mark.anyio
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
async def test_board_ranks_each_slot_by_displayed_score(monkeypatch):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
every = ("morning", "day", "evening", "night", "early")
@@ -195,7 +205,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
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}
# 아침: 하 90(63) > 상 20(20). 낮·밤: 상 70(70) > 하 90(63).
# 하 90점은 표시 63점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다.
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
+15 -1
View File
@@ -9,7 +9,7 @@ import pytest
from common.enums import RainType, Sky
from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
uv_score, view_score, zero_rules_text,
priority_score, rank_score, uv_score, view_score, zero_rules_text,
)
from services.calc.moon import illumination
@@ -38,6 +38,20 @@ def test_perfect_evening_scores_100():
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
shown = [(priority_score(score, priority), priority) for score, priority in items]
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
assert priority_score(91, 2) == 77
assert priority_score(89, 2) == 76
def test_rank_uses_priority_only_to_break_ties():
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
@pytest.mark.parametrize("weight", [5, 10, 20])
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
+1 -1
View File
@@ -10,7 +10,7 @@
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
## 한눈에 보기
+1 -1
View File
@@ -189,7 +189,7 @@
| 노을 | 그날 노을 점수 (2-9) | 사진산책각 |
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다.
- **최종 점수**는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시에 같은 점수를 사용합니다.
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
+1 -1
View File
@@ -91,7 +91,7 @@
- **시간대 알맞음:** 활동 시간대와 겹치면 요소 점수 100점, 아니면 0점입니다. 가중치가 10%라면 10점 또는 0점을 반영하고, 불일치에 따른 추가 최저 요소 감점은 없습니다. 요일·달·노을·일출 요소는 기존 계산을 유지합니다.
- 각 상세 창과 시간대 미리보기의 아침·낮·저녁·밤 점수도 각 구간의 날씨로 계산하며 하루 점수로 대체하지 않습니다.
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
## 5. 나들이 점수 (주말 순위·당일치기)
+2 -2
View File
@@ -2974,7 +2974,7 @@ export type TopIndex = {
/**
* Slot Ranks
*
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
* 오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)
*/
slot_ranks?: {
[key: string]: number;
@@ -3339,7 +3339,7 @@ export type WeekDay = {
/**
* Gaks
*
* 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음
* 그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음
*/
gaks?: Array<WeekGak>;
};