fix: 각 점수에 중요도 배율을 반영해 화면 점수와 순위를 일치시킴
This commit is contained in:
1 parent
621a0cf90d
commit
d5f8b148b4
12 files changed
+68
-33
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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]]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 "바깥 일정 잡기 좋아요")
|
||||
|
||||
Reference in new issue
Block a user