233 lines
11 KiB
Python
233 lines
11 KiB
Python
import asyncio
|
|
import csv
|
|
import json
|
|
import os
|
|
from dataclasses import asdict, dataclass
|
|
from datetime import date, datetime, timedelta
|
|
from functools import lru_cache
|
|
from types import SimpleNamespace
|
|
from typing import Optional
|
|
|
|
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 Region
|
|
from common.enums import ErrorType, RainType, Sky
|
|
from common.logger import LOG
|
|
from common.utils.geo import haversine_km
|
|
from common.utils.kma_time import kst_midnight, now_kst
|
|
from crud.region_crud import RegionCRUD
|
|
from crud.sky_crud import SkyCRUD
|
|
from crud.weather_crud import WeatherCRUD
|
|
from crud.week_crud import WeekCRUD
|
|
from services.calc.index_calc import OUTING_HOURS, Outing, outing, outing_estimate
|
|
from services.index_service import day_forecast, windows_for
|
|
from services.weather_service import WeatherService
|
|
from services.week_service import _icon
|
|
|
|
# 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를
|
|
# 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다.
|
|
_SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv")
|
|
_KEY = "weekend_rank:v3:{:%Y%m%d}" # v3: 비 상한(최대 30점)을 없앤 점수 (옛 점수 캐시를 쓰지 않게 키를 바꿨다)
|
|
_TTL = 13 * 3600
|
|
_PARALLEL = 4 # 기상청 동시 호출 수
|
|
_WAIT_STEPS, _WAIT_SEC = 60, 0.5
|
|
_WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}])
|
|
# 나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_outing_score_table.py 가 만든다
|
|
OUTING_SCORE_TABLE: list[int] = json.loads(
|
|
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "calc", "outing_score_table.json"), encoding="utf-8").read()
|
|
)["table"]
|
|
|
|
|
|
def calibrated_outing(score: int) -> int:
|
|
return OUTING_SCORE_TABLE[score]
|
|
|
|
|
|
def outing_day_score(result: Outing) -> int:
|
|
"""순위·당일치기에 쓰는 하루 나들이 점수. 시간별 예보로 낸 점수와 중기예보 예상 점수 모두 같은 표를 거친다."""
|
|
return calibrated_outing(result.score)
|
|
|
|
|
|
# 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다.
|
|
TRIP_MIN_KM, TRIP_MAX_KM = 20, 200
|
|
TRIP_MIN_SCORE = calibrated_outing(50) # 원래 점수 50점과 같은 날씨 수준
|
|
|
|
|
|
@dataclass
|
|
class DayScore:
|
|
region_code: str
|
|
day: date
|
|
score: int
|
|
reason: str
|
|
icon: str
|
|
temp_min_c: Optional[float]
|
|
temp_max_c: Optional[float]
|
|
rain_prob: int
|
|
estimated: bool
|
|
|
|
|
|
@dataclass
|
|
class TripCity:
|
|
name: str
|
|
label: str
|
|
note: str
|
|
|
|
|
|
@dataclass
|
|
class TripPick:
|
|
city: Region
|
|
label: str
|
|
note: str
|
|
distance_km: int
|
|
best: DayScore
|
|
runner_up: Optional[tuple[str, DayScore]]
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def trip_cities() -> tuple[TripCity, ...]:
|
|
"""당일치기 후보 도시 (seed/trip_city.csv). 늘리려면 이 파일에 줄만 더한다."""
|
|
with open(_SEED, encoding="utf-8") as f:
|
|
return tuple(TripCity(**row) for row in csv.DictReader(f))
|
|
|
|
|
|
def weekend_days(today: date) -> list[date]:
|
|
"""이번 주 토·일 중 오늘 이후."""
|
|
sat = today + timedelta(days=5 - today.weekday())
|
|
return [d for d in (sat, sat + timedelta(days=1)) if d >= today]
|
|
|
|
|
|
def _sat(today: date) -> date:
|
|
return today + timedelta(days=5 - today.weekday())
|
|
|
|
|
|
def rank_days(scores: list[DayScore], codes: set[str], days: list[date]) -> list[tuple[date, list[DayScore]]]:
|
|
"""날마다 점수 높은 순. 같으면 비 확률 낮은 순."""
|
|
return [(d, sorted((x for x in scores if x.day == d and x.region_code in codes), key=lambda x: (-x.score, x.rain_prob, x.region_code))) for d in days]
|
|
|
|
|
|
def pick_trip(region: Region, scores: list[DayScore], cities: dict[str, tuple[Region, TripCity]], days: list[date]) -> Optional[TripPick]:
|
|
"""내 지역에서 1~2시간 거리 후보 도시 중 이번 주말 하루라도 나들이 점수가 가장 높은 곳. 다른 도시 1위를 함께 돌려준다."""
|
|
near = {}
|
|
for code, (city, meta) in cities.items():
|
|
km = haversine_km(float(region.lat), float(region.lon), float(city.lat), float(city.lon))
|
|
if TRIP_MIN_KM <= km <= TRIP_MAX_KM:
|
|
near[code] = (city, meta, round(km))
|
|
best_by_city = {}
|
|
for x in scores:
|
|
if x.region_code in near and x.day in days:
|
|
cur = best_by_city.get(x.region_code)
|
|
if cur is None or (x.score, -x.rain_prob, -x.day.toordinal()) > (cur.score, -cur.rain_prob, -cur.day.toordinal()):
|
|
best_by_city[x.region_code] = x
|
|
ranked = sorted(best_by_city.values(), key=lambda x: (-x.score, x.rain_prob, x.day, near[x.region_code][2]))
|
|
if not ranked or ranked[0].score < TRIP_MIN_SCORE:
|
|
return None
|
|
top = ranked[0]
|
|
city, meta, km = near[top.region_code]
|
|
second = (near[ranked[1].region_code][1].label, ranked[1]) if len(ranked) > 1 else None
|
|
return TripPick(city=city, label=meta.label, note=meta.note, distance_km=km, best=top, runner_up=second)
|
|
|
|
|
|
class WeekendRank:
|
|
def __init__(self) -> None:
|
|
self.regions, self.sky, self.weather, self.week = RegionCRUD(), SkyCRUD(), WeatherCRUD(), WeekCRUD()
|
|
self.weather_service = WeatherService(self.regions, self.weather, self.sky)
|
|
|
|
async def targets(self) -> tuple[ErrorType, list[Region], dict[str, tuple[Region, TripCity]]]:
|
|
"""순위 대표 지역과 당일치기 후보 도시."""
|
|
err, ranking = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.ranking_regions(s))
|
|
err2, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.search(s))
|
|
if ErrorType.DB_ERROR in (err, err2):
|
|
return ErrorType.DB_ERROR, [], {}
|
|
by_name = {r.name: r for r in regions}
|
|
cities = {}
|
|
for c in trip_cities():
|
|
if c.name not in by_name:
|
|
LOG.error(f"[weekend] trip_city.csv: region not found {c.name}")
|
|
continue
|
|
cities[by_name[c.name].code] = (by_name[c.name], c)
|
|
return ErrorType.SUCCESS, ranking, cities
|
|
|
|
async def scores(self, now: Optional[datetime] = None, compute: bool = True) -> tuple[ErrorType, list[DayScore]]:
|
|
"""이번 주말 점수. 캐시에 없고 compute 면 계산해 넣는다."""
|
|
now = now or now_kst()
|
|
days = weekend_days(now.date())
|
|
key = _KEY.format(_sat(now.date()))
|
|
try:
|
|
cached = await REDIS.conn.get(key)
|
|
except RedisError as e:
|
|
LOG.error(f"[weekend] cache get: {e}")
|
|
cached = None
|
|
if cached:
|
|
return ErrorType.SUCCESS, [x for x in _load(cached) if x.day in days]
|
|
if not compute:
|
|
return ErrorType.NOT_FOUND, []
|
|
return await self.refresh(now)
|
|
|
|
async def refresh(self, now: Optional[datetime] = None) -> tuple[ErrorType, list[DayScore]]:
|
|
now = now or now_kst()
|
|
days = weekend_days(now.date())
|
|
key = _KEY.format(_sat(now.date()))
|
|
err, ranking, cities = await self.targets()
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, []
|
|
targets = list({r.code: r for r in ranking + [c for c, _ in cities.values()]}.values())
|
|
async with redis_lock(f"lock:{key}", ttl_sec=120) as acquired:
|
|
if not acquired:
|
|
return await self._wait(key, days)
|
|
gate = asyncio.Semaphore(_PARALLEL)
|
|
out = await asyncio.gather(*(self._region(r, now, days, gate) for r in targets))
|
|
scores = [x for xs in out for x in xs]
|
|
if not scores:
|
|
return ErrorType.EXTERNAL_API_ERROR, []
|
|
try:
|
|
await REDIS.conn.set(key, json.dumps([{**asdict(x), "day": x.day.isoformat()} for x in scores], ensure_ascii=False), ex=_TTL)
|
|
except RedisError as e:
|
|
LOG.error(f"[weekend] cache set: {e}")
|
|
LOG.info(f"[weekend] {len(targets)} regions {len(scores)} scores")
|
|
return ErrorType.SUCCESS, scores
|
|
|
|
async def _wait(self, key: str, days: list[date]) -> tuple[ErrorType, list[DayScore]]:
|
|
"""다른 요청·워커가 계산 중이면 끝날 때까지 캐시를 본다."""
|
|
for _ in range(_WAIT_STEPS):
|
|
await asyncio.sleep(_WAIT_SEC)
|
|
try:
|
|
cached = await REDIS.conn.get(key)
|
|
except RedisError as e:
|
|
LOG.error(f"[weekend] cache wait: {e}")
|
|
return ErrorType.CACHE_ERROR, []
|
|
if cached:
|
|
return ErrorType.SUCCESS, [x for x in _load(cached) if x.day in days]
|
|
return ErrorType.EXTERNAL_API_ERROR, []
|
|
|
|
async def _region(self, region: Region, now: datetime, days: list[date], gate: asyncio.Semaphore) -> list[DayScore]:
|
|
"""주말이 단기예보 안이면 10~17시 시간별로, 아니면 중기예보로 예상 점수."""
|
|
async with gate:
|
|
await asyncio.gather(self.weather_service.ensure_vilage(region, now, background=False), self.weather_service.ensure_mid(region, now))
|
|
start = kst_midnight(days[0])
|
|
err, hourly = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start, start + timedelta(days=len(days))))
|
|
err2, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, days[0], days[-1]))
|
|
if ErrorType.DB_ERROR in (err, err2):
|
|
LOG.error(f"[weekend] {region.code}: DB_ERROR")
|
|
return []
|
|
by_at = {r.forecast_at: r for r in hourly}
|
|
by_day = {d.forecast_date: d for d in daily}
|
|
out = []
|
|
for d in days:
|
|
row = by_day.get(d)
|
|
result = outing(windows_for(_WINDOW, d, region, by_at)[0]) or (outing_estimate(day_forecast(row)) if row else None)
|
|
if result is None or row is None:
|
|
continue
|
|
out.append(DayScore(
|
|
region_code=region.code, day=d, score=outing_day_score(result), reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
|
|
temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None,
|
|
temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None,
|
|
rain_prob=row.rain_prob, estimated=result.estimated,
|
|
))
|
|
return out
|
|
|
|
|
|
def _load(raw: str) -> list[DayScore]:
|
|
return [DayScore(**{**x, "day": date.fromisoformat(x["day"])}) for x in json.loads(raw)]
|