Merge remote-tracking branch 'origin/main' into merge/festivals

# Conflicts:
#	backend/services/week_service.py
This commit is contained in:
minaChoi committed 2026-10-08 11:52:49 +09:00
commit b4fcb313c7
56 files changed
+4132 -251

No files matched your search

+17 -4
View File
@@ -18,6 +18,13 @@ _FALL_FLOOR = exp(-0.5)
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
_TEMP_PLATEAU = 2
_HUMIDITY_PLATEAU = 5
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
def rank_score(score: int, priority: int) -> float:
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
return score * PRIORITY_WEIGHT[priority]
@dataclass(frozen=True)
@@ -154,10 +161,15 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
_AIR_RULE = {"zero": 75, "full": 15}
def air_score(pm25: Optional[int], label: Optional[str], rule: Optional[dict] = None) -> tuple[int, str]:
"""rule 이 없으면 맑을수록 좋음. 집콕각처럼 탁할수록 좋은 각은 {"zero": 15, "full": 75} 로 뒤집는다."""
if pm25 is None:
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
rule = rule or _AIR_RULE
return _linear(pm25, rule["zero"], rule["full"]), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
@@ -208,7 +220,8 @@ def axis_label(axis: str, rules: dict) -> str:
if axis == "rain":
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
if axis == "air":
return "공기 맑음"
rule = rules.get("air", _AIR_RULE)
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
return table[rules[axis]["type"]]
@@ -304,7 +317,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
"wind": wind_score(rules["wind"], max(winds) if winds else None),
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
"air": air_score(ctx.pm25, ctx.air_label),
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
+43 -10
View File
@@ -25,6 +25,7 @@ from router.v1.feed.protocol import (
)
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade
from services.calc.index_calc import rank_score
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
@@ -62,6 +63,19 @@ LINEUP = [
(19, PostType.MOON, RefType.NONE, None),
(20, PostType.UV, RefType.NONE, None),
]
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
def sido_of(region_code: str) -> str:
"""구 행정코드의 시도 부분(앞 2자리)."""
return region_code[:2]
def post_scope(post_type: PostType, region_code: str) -> str:
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
ORDER = {
"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],
@@ -223,17 +237,33 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
return head + rest
def _by_position(posts: list[Post]) -> list[Post]:
"""번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다)."""
out: dict[int, Post] = {}
for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)):
out.setdefault(p.position, p)
return list(out.values())
def _top(i: IndexItem) -> TopIndex:
d = i.definition
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
if err is not ErrorType.SUCCESS:
return err
lineup = [x for x in LINEUP if x[0] not in made]
err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s))
if err is not ErrorType.SUCCESS:
return err
sidos = sorted({sido_of(r.code) for r in all_regions})
lineup = [
(scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos)
if (scope, x[0]) not in made and (NATIONAL_SCOPE, x[0]) not in made
]
if not lineup:
return err
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
@@ -242,12 +272,12 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
end = start + timedelta(days=1)
rows = []
for position, post_type, ref_type, rank in lineup:
for scope, position, post_type, ref_type, rank in lineup:
ref = refs.get(post_type)
if ref_type is RefType.ARTICLE and ref is None:
continue
rows.append({
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
"feed_date": day, "position": position, "scope": scope, "post_type": post_type.value, "ref_type": ref_type.value,
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
"published_at": start, "end_at": end,
})
@@ -301,7 +331,7 @@ class FeedService:
day = feed_day(now)
async with redis_lock("lock:feed:build", ttl_sec=20):
await build_feed_day(day, self.crud, self.season_crud)
await build_feed_day(day, self.crud, self.season_crud, self.regions)
res, partial = await self._assemble(region, now, day, slot, sunset_at)
try:
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
@@ -332,7 +362,8 @@ class FeedService:
_, hourly = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
)
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
posts = _by_position(posts or [])
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
by_article = {a.article_id: a for a in articles or []}
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
@@ -362,7 +393,8 @@ class FeedService:
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
top5=[_top(i) for i in items[:5]],
season=[
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon,
image=a.image_url, image_credit=a.image_credit)
for a in articles or [] if a.category == ArticleCategory.SEASON.value
],
),
@@ -450,7 +482,8 @@ class FeedService:
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
a = c.articles[p.ref_id]
return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0],
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title])
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon, image=a.image_url, image_credit=a.image_credit)],
share_messages=[a.title])
if t is PostType.EVENT:
soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
rank = p.index_rank or 1
@@ -656,7 +689,7 @@ class FeedService:
best = None
for i in c.board.items if c.board else []:
s = next((x for x in i.trend if x.score_date == tomorrow), None)
if s is not None and (best is None or s.score > best[1].score):
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
if best is not None:
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
+2 -2
View File
@@ -16,7 +16,7 @@ from crud.sky_crud import SkyCRUD
from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
from services.calc.moon import illumination
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
@@ -210,7 +210,7 @@ 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}
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: by_key[(d.index_id, today)].score, reverse=True)
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True)
items = [
IndexItem(
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
+6 -4
View File
@@ -79,10 +79,12 @@ class RankItem:
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
for p in spots]
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순. 반경 안에 없으면 가장 가까운 한 곳."""
every = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
for p in spots]
near = [x for x in every if x.distance_km <= SPOT_RADIUS_KM]
if not near:
return sorted(every, key=lambda x: x.distance_km)[:1]
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
+35 -9
View File
@@ -1,4 +1,5 @@
import asyncio
import math
import re
from dataclasses import dataclass
from datetime import date, timedelta
@@ -21,6 +22,7 @@ from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.calc.index_calc import rank_score
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
@@ -41,6 +43,10 @@ MAX_EVENT_DAYS = 60
EVENT_RADIUS_KM = 30
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
PLACE_RADIUS_KM = EVENT_RADIUS_KM
PLACE_LIMIT = 10
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
PLACE_FALLBACK = 3
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
@@ -67,6 +73,7 @@ class DayPlan:
class PlaceItem:
place: Place
is_good: bool
distance_km: float
@dataclass
@@ -144,6 +151,22 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
return e.sido_code == region.code[:2]
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
"""구 중심에서 반경 안의 명소를 날씨에 맞는 것 먼저, 같으면 가까운 순으로. 반경 안에 없으면 가장 가까운 몇 곳."""
lat, lon = float(region.lat), float(region.lon)
dist = sorted(((p, round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in places if p.lat is not None and p.lon is not None), key=lambda x: x[1])
near = [x for x in dist if x[1] <= PLACE_RADIUS_KM] or dist[:PLACE_FALLBACK]
areas = list(dict.fromkeys(p.area for p, _ in near))
items = [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor, distance_km=d) for p, d in near if area is None or p.area == area]
items.sort(key=lambda i: (not i.is_good, i.distance_km))
return items[:PLACE_LIMIT], areas
def place_credit(p: Place) -> Optional[str]:
"""명소 사진은 TourAPI 것만 넣는다."""
return TOUR_CREDIT if p.image_url else None
def _status(e: Event, today: date) -> tuple[str, str]:
if e.start_date <= today <= e.end_date:
return "live", "진행 중"
@@ -234,11 +257,12 @@ class WeekService:
if err is not ErrorType.SUCCESS:
return err, []
names = {d.index_id: d.name for d in defs or []}
priority = {d.index_id: d.priority for d in defs or []}
plans = []
for d in daily:
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
rain_hours = _rain_hours(rows)
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: x.score, reverse=True)[:2]
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
holiday = (holidays or {}).get(d.forecast_date)
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
word = _weather_word(d, rain_hours)
@@ -258,19 +282,21 @@ class WeekService:
))
return ErrorType.SUCCESS, plans
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str]]:
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str], bool]:
err, region = await self._region(region_code)
if err is not ErrorType.SUCCESS:
return err, [], []
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2]))
return err, [], [], False
lat, lon = float(region.lat), float(region.lon)
dlat, dlon = PLACE_RADIUS_KM / 111, PLACE_RADIUS_KM / (111 * math.cos(math.radians(lat)))
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places_in_box(s, lat, lon, dlat, dlon))
if err is ErrorType.SUCCESS and not any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= PLACE_RADIUS_KM for p in places):
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.all_places(s))
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day))
if err is not ErrorType.SUCCESS:
return err, [], []
return err, [], [], False
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
areas = list(dict.fromkeys(p.area for p in places))
picked = [p for p in places if area is None or p.area == area]
picked.sort(key=lambda p: (p.is_outdoor if rainy else not p.is_outdoor, p.sort_order))
return ErrorType.SUCCESS, [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor) for p in picked], areas
items, areas = pick_places(region, places, rainy, area)
return ErrorType.SUCCESS, items, areas, rainy
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
err, region = await self._region(region_code)