feat: 피드에 자외선 포스트 (아침·낮, 오늘 가장 셀 때 '보통' 이상인 날만)

- 오늘 9·12·15·18시 자외선(Open-Meteo)과 가장 셀 때 시각, '높음' 이상이면 할 일 한 줄
- '낮음'인 날은 챙길 게 없어 띄우지 않음
This commit is contained in:
minaChoi committed 2026-10-07 16:51:57 +09:00
1 parent c67121351b
commit 35b3e0df43
6 files changed
+90 -10

No files matched your search

+1
View File
@@ -135,6 +135,7 @@ class PostType(CodeEnum):
AIR = 12
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
class EventKind(CodeEnum):
+39 -6
View File
@@ -1,6 +1,6 @@
import asyncio
import random
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta
from typing import Optional
@@ -10,7 +10,7 @@ from redis.exceptions import RedisError
from common.cache.lock import redis_lock
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Article, Post, Region, WeatherHourly
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
@@ -28,7 +28,7 @@ from services.air_service import pm10_grade, pm25_grade
from services.calc.moon import illumination, nearest, phase_name
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
from services.calc.sun import sun_times
from services.hero_stats import HeroInput, hero_stats
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
from services.index_service import IndexBoard, IndexItem, IndexService
from services.now_service import NowService, NowWeather
from services.season_service import SeasonService
@@ -60,11 +60,12 @@ LINEUP = [
(17, PostType.AIR, RefType.NONE, None),
(18, PostType.DAY_TRIP, RefType.NONE, None),
(19, PostType.MOON, RefType.NONE, None),
(20, PostType.UV, RefType.NONE, None),
]
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
ORDER = {
"morning": [PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.MOON, PostType.QUOTE],
}
@@ -74,6 +75,7 @@ _FEED_TTL_MAX = 3600
_PARTIAL_TTL = 60
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
_RAIN_PROB = 40
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
_SUNSET_FULL = 60
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
@@ -334,7 +336,8 @@ class FeedService:
by_article = {a.article_id: a for a in articles or []}
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, tomorrow=tomorrow, now_w=now_w, sky=sky, board=board,
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip)
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
uv=await self._uv_today(region.code, now))
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
cards = []
@@ -382,6 +385,14 @@ class FeedService:
return (pick, []), True
return (pick, pick_events(pick.best.day, items)), False
async def _uv_today(self, region_code: str, now: datetime) -> list[OpenMeteoHourly]:
"""오늘 09~18시 3시간 칸 끝 시각의 자외선 (Open-Meteo)."""
day = kst_midnight(now.date())
err, rows = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather_crud.openmeteo_between(s, region_code, day + timedelta(hours=9), day + timedelta(hours=18))
)
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
@@ -471,6 +482,8 @@ class FeedService:
return self._day_trip(base, *c.trip)
if t is PostType.MOON:
return self._moon(base, c)
if t is PostType.UV:
return self._uv_post(base, c)
return None
def _moon(self, base: dict, c: "_Ctx") -> PostData:
@@ -573,6 +586,25 @@ class FeedService:
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
share_messages=[f"{line} {tail}"])
def _uv_post(self, base: dict, c: "_Ctx") -> Optional[PostData]:
"""오늘 낮 자외선. 가장 셀 때가 '보통'(3) 아래면 챙길 게 없어 끈다."""
if not c.uv:
return None
peak = max(c.uv, key=lambda r: r.uv_index)
top = float(peak.uv_index)
if top < _UV_SHOW:
return None
label = uv_label(top)
at = peak.forecast_at.astimezone(KST)
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
high = top >= UV_HIGH
if high:
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
air = c.now_w.air if c.now_w else None
@@ -717,3 +749,4 @@ class _Ctx:
articles: dict[int, Article]
quotes: list[Article]
trip: Optional[tuple[TripPick, list[EventItem]]] = None
uv: list[OpenMeteoHourly] = field(default_factory=list) # 오늘 낮 3시간 칸 자외선
+15
View File
@@ -349,3 +349,18 @@ def test_gak_caption_starts_with_score_band_sentence():
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
item.definition.sentences = {}
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
def test_uv_post_only_when_moderate_or_higher():
from datetime import datetime
from types import SimpleNamespace
from common.utils.kma_time import KST
from services.feed_service import FeedService
at = lambda h: datetime(2026, 10, 7, h, tzinfo=KST) # noqa: E731
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요"
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
assert FeedService._uv_post(None, base, ctx([])) is None
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErLine truncated
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErLine truncated
+32 -2
View File
@@ -1,7 +1,7 @@
// This file is auto-generated by @hey-api/openapi-ts
export type ClientOptions = {
baseUrl: 'http://host.docker.internal:9810' | (string & {});
baseUrl: `${string}://openapi.gen.json` | (string & {});
};
/**
@@ -976,7 +976,11 @@ export const PostType = {
/**
* MOON
*/
MOON: 14
MOON: 14,
/**
* UV
*/
UV: 15
} as const;
/**
@@ -1713,6 +1717,10 @@ export type ResWatchSummary = {
* Timeline
*/
timeline?: Array<WatchTimeline>;
/**
* Events
*/
events?: Array<WatchEvent>;
};
/**
@@ -2421,6 +2429,28 @@ export const WarningType = {
*/
export type WarningType = typeof WarningType[keyof typeof WarningType];
/**
* WatchEvent
*/
export type WatchEvent = {
/**
* Name
*/
name: string;
/**
* Place Name
*/
place_name: string;
/**
* Status Label
*/
status_label: string;
/**
* Fit
*/
fit?: string | null;
};
/**
* WatchNow
*/
+2 -1
View File
@@ -29,12 +29,13 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.AIR]: ['미세먼지', 'vent'],
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
}
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac' }
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' }
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
function slideBg(post: PostData, slide: Slide): SlideBg {