fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영

This commit is contained in:
skkim committed 2026-10-22 13:38:39 +09:00
1 parent 3b5afba8a1
commit 799a46f53c
13 files changed
+124 -66

No files matched your search

+3 -2
View File
@@ -35,9 +35,10 @@ class IndexCRUD:
return await s.scalar(stmt)
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
"""현재 방식으로 모든 구간을 계산하지 않은 행이 있는지."""
stmt = select(IndexScore.index_id).where(
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
IndexScore.region_code == region_code, IndexScore.score_date == day,
text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])")
).limit(1)
return (await s.scalar(stmt)) is not None
+7 -5
View File
@@ -57,6 +57,7 @@ class Context:
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
@dataclass(frozen=True)
@@ -209,7 +210,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
)
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요")
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
@@ -296,12 +297,13 @@ def _summary(hours: list[Hour]) -> str:
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True) -> int:
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int:
"""비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다)."""
mixed = sum(factors[a] * weights[a] for a in AXES) / 100
if not worst_pull:
return round(mixed)
worst = min((factors[a] for a in AXES if weights[a]), default=100)
# 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다.
worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100)
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
@@ -342,7 +344,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
}
factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights, getattr(definition, "worst_pull", True))
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
agg = {
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
@@ -399,7 +401,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
}
factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights, getattr(definition, "worst_pull", True))
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
+1 -1
View File
@@ -311,7 +311,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}:{slot}"
key = f"feed:{region.code}:time-weight-v2:{slot}"
try:
cached = await REDIS.conn.get(key)
if cached:
+19 -29
View File
@@ -77,8 +77,8 @@ class IndexItem:
trend: list[IndexScore]
slot: Optional[str] = None
slots: dict[str, int] = field(default_factory=dict)
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
slot_ranks: dict[str, int] = field(default_factory=dict) # 각 구간의 날씨·시간대 적합도로 계산한 순위
active: bool = True # 시간대와 관계없이 활성화. 제철이 아닌 각만 제외
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
@@ -93,7 +93,7 @@ class IndexBoard:
@property
def ranked(self) -> list[IndexItem]:
"""지금 구간에 해당하는 각만 (순위·피드용)."""
"""활성화된 각 (순위·피드용)."""
return [i for i in self.items if i.active]
@@ -183,7 +183,6 @@ def windows_for(
EARLY = "early" # 0~5시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
def current_slot(now: datetime, sunset_at: datetime) -> str:
@@ -220,16 +219,21 @@ def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
now: Optional[datetime] = None,
) -> dict[str, Result]:
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
"""각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다."""
hours_by_slot = slot_hours(day, sunset_at)
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR))
if now:
_trim_passed(hours_by_slot, day, sunset_at, now)
activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)]
out = {}
for key, windows in parts.items():
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
for key, hours in hours_by_slot.items():
if not hours:
continue
matches = any(any(h % 24 in w for h in hours) for w in activity)
# 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다.
window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}])
windows = windows_for(window, day, region, by_at, by_om, only=hours)
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
if result is not None:
out[key] = result
return out
@@ -336,16 +340,13 @@ class IndexService:
month = today.month
out_season = [d for d in defs if not in_season(d, month)]
defs = [d for d in defs if in_season(d, month)]
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
# 현재 구간의 날씨와 시간 요소로 계산한 점수만 사용한다.
now_score: dict[int, IndexScore] = {}
for d in defs:
row = by_key.get((d.index_id, today))
if row is None:
if row is None or cur not in row.slots:
continue
if not row.slots:
now_score[d.index_id] = row
elif cur in row.slots:
now_score[d.index_id] = _with_slot(row, row.slots[cur])
now_score[d.index_id] = _with_slot(row, row.slots[cur])
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):
@@ -356,17 +357,6 @@ class IndexService:
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],
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
))
off = sorted(
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
)
for d in off:
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],
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
))
for k in SLOTS:
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
for n, i in enumerate(in_slot):
+21 -9
View File
@@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night():
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
def test_gak_hidden_in_slots_outside_its_window():
def test_gak_scores_every_slot_and_time_match_is_binary():
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"evening", "night"}
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0}
def test_rain_in_evening_lowers_only_later_slots():
@@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score():
assert wet < dry
def test_slot_needs_two_overlapping_hours():
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
def test_time_match_includes_one_overlapping_hour():
by_at = _rows()
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
for start, end in ((10, 17), (9, 17), (10, 11)):
assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100
def test_outside_window_uses_current_weather_instead_of_daily_weather():
parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
assert parts["morning"].score == 100
assert parts["night"].score < parts["morning"].score
assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0
def test_early_hours_match_windows_crossing_midnight():
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert parts[EARLY].factors["time"] == 100
now = datetime(2026, 10, 8, 2, 0, tzinfo=KST)
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
assert parts[EARLY].factors["time"] == 0
def test_current_slot_skips_passed_hours():
+6 -1
View File
@@ -8,10 +8,12 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import PostType
from common.utils.kma_time import now_kst
from crud.feed_crud import FeedCRUD
from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from router.router import app
from services.feed_service import build_feed_day
from services.index_service import in_season
from services.week_service import collect_events
REGION = "1114000000"
@@ -61,7 +63,10 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
body = (await client.get("/v1/feed", params={"region": REGION})).json()
assert body["result"]["success"] is True
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
assert len(body["stories"]) == 40
_, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
expected = {d.code for d in definitions if in_season(d, now_kst().month)}
assert {g["code"] for g in body["stories"]} == expected
assert all(g["active"] for g in body["stories"])
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
+38 -7
View File
@@ -8,7 +8,7 @@ import services.air_service as air_service
import services.warning_service as warning_service
import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import OpenMeteoHourly, WeatherHourly
from common.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly
from common.enums import ErrorType
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
@@ -24,6 +24,14 @@ async def _async(v):
return v
def _board_score(index_id, day, score, slot_score=None):
value = score if slot_score is None else slot_score
return IndexScore(index_id=index_id, score_date=day, score=score, slots={
k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}}
for k in ("morning", "day", "evening", "night", "early")
})
def _vilage(*_):
start = kst_midnight(now_kst().date())
items = []
@@ -61,7 +69,8 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
assert body["result"]["success"] is True
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
priority = {d["code"]: d["priority"] for d in _seed()}
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
# 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝.
assert all(i["active"] for i in body["items"] if i["in_season"])
actives = [i["active"] for i in body["items"]]
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
seasons = [i["in_season"] for i in body["items"]]
@@ -139,7 +148,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
]
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
scores = [_board_score(x, today, v) 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})))
@@ -159,7 +168,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
SimpleNamespace(index_id=2, code="mid", priority=2),
SimpleNamespace(index_id=3, code="high", priority=1),
]
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
scores = [_board_score(x, today, 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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
@@ -175,7 +184,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
every = ("morning", "day", "evening", "night", "early")
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}}
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)
@@ -183,10 +192,32 @@ 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) > 상 20(20). 낮·밤: 상 70(70) > 하 90(63).
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
assert "night" not in ranks["high"]
assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
@pytest.mark.anyio
@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"])
async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="outside", priority=1)]
row = _board_score(1, today, 85, slot_score=65)
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row]))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {cur: 50})))
monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur)
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
assert len(board.ranked) == 1
item = board.ranked[0]
assert item.active and item.score.score == 65 and item.rank == 1
assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur)
assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")}
assert item.slot_ranks == {k: 1 for k in item.slots}
def _om_row(at, **over):
+16
View File
@@ -38,6 +38,22 @@ def test_perfect_evening_scores_100():
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
@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}}
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
weight_time=weight, factor_rules=rules)
hours = [[_h(12)]]
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
assert matched.score == 100 and unmatched.score == 100 - weight
def test_time_matching_does_not_replace_weekday_score():
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
def test_good_but_not_perfect_stays_below_100():
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95