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
|
score: int
|
||||||
line: str
|
line: str
|
||||||
summary: str
|
summary: str
|
||||||
|
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
|
||||||
|
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
|
||||||
|
|
||||||
|
|
||||||
class Cut(WebPacketProtocol):
|
class Cut(WebPacketProtocol):
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import random
|
import random
|
||||||
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date, datetime, time, timedelta
|
from datetime import date, datetime, time, timedelta
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -456,7 +457,7 @@ class FeedService:
|
|||||||
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
def _gak(self, p: Post, i: IndexItem) -> PostData:
|
||||||
d = i.definition
|
d = i.definition
|
||||||
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
|
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}점이래"])
|
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
|
||||||
|
|
||||||
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
|
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
|
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:
|
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)
|
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||||
if nxt is not None:
|
if nxt is not None:
|
||||||
diff = nxt.score - i.score.score
|
diff = nxt.score - i.score.score
|
||||||
@@ -734,7 +758,7 @@ def _gak_caption(i: IndexItem) -> str:
|
|||||||
else:
|
else:
|
||||||
spans = [_span(w) for w in i.definition.windows or []]
|
spans = [_span(w) for w in i.definition.windows or []]
|
||||||
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
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]:
|
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"
|
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 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}])
|
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)
|
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
|
||||||
item.definition.sentences = {}
|
|
||||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
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([(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([(9, 1.0), (12, 2.5)])) is None
|
||||||
assert FeedService._uv_post(None, base, ctx([])) 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%"
|
||||||
@@ -545,6 +545,18 @@ export type GakSlide = {
|
|||||||
* Summary
|
* Summary
|
||||||
*/
|
*/
|
||||||
summary: string;
|
summary: string;
|
||||||
|
/**
|
||||||
|
* Rows
|
||||||
|
*
|
||||||
|
* 점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)
|
||||||
|
*/
|
||||||
|
rows?: Array<Row>;
|
||||||
|
/**
|
||||||
|
* Say
|
||||||
|
*
|
||||||
|
* 점수 구간 설명 문장 (seed sentences)
|
||||||
|
*/
|
||||||
|
say?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -133,6 +133,13 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
|
|||||||
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
||||||
<Big>{slide.line}</Big>
|
<Big>{slide.line}</Big>
|
||||||
<Pic name={slide.code} />
|
<Pic name={slide.code} />
|
||||||
|
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
|
||||||
|
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
|
||||||
|
{!!slide.rows?.length && (
|
||||||
|
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
|
||||||
|
<Rows rows={slide.rows} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
|
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
|
||||||
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
||||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||||
|
|||||||
Reference in new issue
Block a user