feat: 각 포스트가 비어 보이지 않게 — 점수 구간 설명 문장과 근거 네 줄(비중 큰 조건부터 지금 값: 비 확률·체감·바람·미세먼지)을 카드 안에, 글 설명엔 내일 점수만
This commit is contained in:
1 parent
3c34b958fa
commit
74a46dd66a
5 files changed
+69
-8
No files matched your search
@@ -49,6 +49,8 @@ class GakSlide(WebPacketProtocol):
|
||||
score: int
|
||||
line: str
|
||||
summary: str
|
||||
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
|
||||
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
|
||||
|
||||
|
||||
class Cut(WebPacketProtocol):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
@@ -456,7 +457,7 @@ class FeedService:
|
||||
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
||||
d = i.definition
|
||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)],
|
||||
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
|
||||
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||
|
||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
||||
@@ -723,9 +724,32 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
|
||||
return sentences[str(lo)] if lo is not None else None
|
||||
|
||||
|
||||
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
|
||||
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
|
||||
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
|
||||
|
||||
|
||||
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
|
||||
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
|
||||
d, notes = i.definition, i.score.notes or {}
|
||||
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
|
||||
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
|
||||
rows = []
|
||||
for a in axes[:n]:
|
||||
head, _, tail = notes[a].partition(", ")
|
||||
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
|
||||
if prob:
|
||||
value = prob.group(0)
|
||||
elif a == "air" and tail:
|
||||
value = tail
|
||||
else:
|
||||
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
|
||||
rows.append(Row(label=_AXIS_NAME[a], value=value))
|
||||
return rows
|
||||
|
||||
|
||||
def _gak_caption(i: IndexItem) -> str:
|
||||
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간)."""
|
||||
band = _band_sentence(i.definition.sentences, i.score.score)
|
||||
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
if nxt is not None:
|
||||
diff = nxt.score - i.score.score
|
||||
@@ -734,7 +758,7 @@ def _gak_caption(i: IndexItem) -> str:
|
||||
else:
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
return f"{band} {tail}" if band else tail
|
||||
return tail
|
||||
|
||||
|
||||
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
|
||||
|
||||
@@ -383,14 +383,14 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
|
||||
|
||||
def test_gak_caption_starts_with_score_band_sentence():
|
||||
def test_gak_band_sentence_moves_to_slide_and_caption_keeps_hours():
|
||||
"""점수 구간 설명 문장은 슬라이드(say)에 두고, 글 설명엔 내일 점수나 하기 좋은 때만."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _gak_caption
|
||||
from services.feed_service import _band_sentence, _gak_caption
|
||||
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
||||
item.definition.sentences = {}
|
||||
assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
|
||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
||||
|
||||
|
||||
@@ -410,3 +410,19 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
|
||||
|
||||
def test_gak_rows_shows_heaviest_conditions_with_short_values():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import gak_rows
|
||||
|
||||
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
|
||||
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
|
||||
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
|
||||
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
|
||||
d.weight_wind = 0
|
||||
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
|
||||
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
|
||||
assert gak_rows(item)[1].value == "확률 70%"
|
||||
Reference in new issue
Block a user