feat: 계절 각 — 각마다 제철 달(months), 제철 각에 지금 계절 표시·철 지난 각은 순위 밖 맨 끝, 새 각 12개(꽃구경·이불빨래·빙수·실내건조·한강밤바람·단풍·억새·군고구마·해돋이·눈사람·붕어빵·귤까먹기), 해 뜰 무렵 시간대·일출 점수·눈 조건

This commit is contained in:
minaChoi committed 2026-10-12 17:20:00 +09:00
1 parent 43e1925d70
commit 5c05824ce0
14 files changed
+1130 -66

No files matched your search

+13 -3
View File
@@ -55,6 +55,7 @@ class Context:
wind_warning: bool
lookahead_rain_prob: int
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
@dataclass(frozen=True)
@@ -203,13 +204,17 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
)
if kind == "sunrise_score":
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'])}점"
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"}
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
@@ -253,6 +258,8 @@ def _cond(r: dict) -> tuple[str, str, str]:
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
if r["field"] == "warning":
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
if r["field"] == "snow":
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
return f"{base}이라", f"{base}이거나", f"{base}이면"
@@ -333,6 +340,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
"warning": "wind" if ctx.wind_warning else None,
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
@@ -351,7 +359,7 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다."""
if fc.temp_min_c is None or fc.temp_max_c is None:
return None
best: Optional[Result] = None
@@ -381,7 +389,9 @@ 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)
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
known = {"rain_prob": max_prob, "snow": "no"}
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
if reason is not None:
score = min(score, cap)
mid = hours[len(hours) // 2]
+2 -1
View File
@@ -371,7 +371,8 @@ class FeedService:
for p, item in zip(gak_posts, gak):
cards.append(self._gak(p, item))
has_warning = bool(now_w and now_w.warnings)
items = board.items if board else []
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
items = [i for i in board.items if i.in_season] if board else []
feed = Res_Feed(
region_code=region.code, region_name=region.name, slot=slot,
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
+40 -6
View File
@@ -42,6 +42,26 @@ WEATHER_SCORE_DEF = SimpleNamespace(
)
SEASONS = ("겨울", "봄", "여름", "가을")
def season_of(month: int) -> str:
"""봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2."""
return SEASONS[month % 12 // 3]
def in_season(defn, month: int) -> bool:
"""제철 달이 없으면 일 년 내내."""
months = getattr(defn, "months", None)
return not months or month in months
def season_badge(defn, month: int) -> Optional[str]:
"""제철이 정해진 각이 지금 제철이면 그 계절 이름. 일 년 내내인 각은 없음."""
months = getattr(defn, "months", None)
return season_of(month) if months and month in months else None
@dataclass
class IndexItem:
definition: IndexDefinition
@@ -52,6 +72,8 @@ class IndexItem:
slots: dict[str, int] = field(default_factory=dict)
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
@dataclass
@@ -92,11 +114,12 @@ def slot_label(day: date, today: date) -> str:
def window_hours(defn, day: date, region: Region) -> list[list[int]]:
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각."""
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각. around 는 일몰·일출 시각 ±hours."""
out = []
for w in defn.windows:
if w.get("around") == "sunset":
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
if w.get("around") in ("sunset", "sunrise"):
sun = sun_times(day, float(region.lat), float(region.lon))
h = (sun.sunset_at if w["around"] == "sunset" else sun.sunrise_at).astimezone(KST).hour
out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)))
else:
out.append(list(range(w["from"], w["to"])))
@@ -272,6 +295,9 @@ class IndexService:
if ErrorType.DB_ERROR in (err, err2):
return ErrorType.DB_ERROR, None
by_key = {(x.index_id, x.score_date): x for x in scores}
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:
@@ -290,7 +316,7 @@ class IndexService:
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],
slot=shown_slot(cur), slots=parts,
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),
@@ -301,12 +327,19 @@ class IndexService:
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,
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):
i.slot_ranks[k] = n + 1
# 제철이 아닌 각은 구간 순위 없이 맨 끝에
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,
))
return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
)
@@ -359,6 +392,7 @@ class IndexService:
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
_, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today))
sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value}
sunrise = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNRISE.value}
if err is not ErrorType.SUCCESS:
return err, None
out = []
@@ -366,7 +400,7 @@ class IndexService:
m = night(day, float(region.lat), float(region.lon))
ctx = Context(
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx,
)
for d in defs:
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)