fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영
This commit is contained in:
1 parent
3b5afba8a1
commit
799a46f53c
13 files changed
+124
-66
No files matched your search
@@ -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"}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user