feat: 축제·전시·콘서트·팝업 7일마다 수집, 피드 행사 종류 섞기

- 행사 수집을 화면 요청에서 빼고 worker 가 월 04:00(켤 때 7일 기록 없으면 한 번) 전국 17개 시도를 받는다
- 문화정보원 음악/콘서트(B000) 추가, 쪽·시도 사이 1초 간격으로 초당 요청 제한 회피
- 팝가(popga.co.kr) 팝업스토어 수집: 사이트맵 + 상세 JSON-LD, 바뀐 페이지만 다시 읽음
- 수집이 끝나면 Teams Workflows webhook 으로 종류별 건수 알림 (TEAMS_WEBHOOK_URL)
- event.kind(1=축제 2=전시 3=콘서트 4=팝업) 칸과 종류별 아이콘 추가
- 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 섞음
- 포스트 종류별 내용·피드 기획 문서 갱신

같은 작업 폴더의 다른 작업(외부 API 가드, 노을·달 계산, 각 API, 문서 파일 이름 정리 등)도 함께 담김.
This commit is contained in:
minaChoi committed 2026-10-07 12:03:48 +09:00
1 parent b61ed92c54
commit 997a366e76
70 files changed
+2083 -649

No files matched your search

+46 -4
View File
@@ -1,11 +1,53 @@
import math
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
_SYNODIC_DAYS = 29.530588
_KNOWN_NEW_MOON = datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)
def illumination(at: datetime) -> float:
"""달이 밝게 보이는 비율 0(그믐)~1(보름). 평균 삭망월 근사."""
phase = ((at - _KNOWN_NEW_MOON).total_seconds() / 86400 % _SYNODIC_DAYS) / _SYNODIC_DAYS
return (1 - math.cos(2 * math.pi * phase)) / 2
"""달이 밝게 보이는 비율 0(그믐)~1(보름)."""
return (1 - math.cos(2 * math.pi * _fraction(at))) / 2
def _fraction(at: datetime) -> float:
"""직전 삭에서 다음 삭까지 얼마나 지났는지 0~1. 앞뒤 삭은 실제 시각(nearest)으로 잡는다."""
near = nearest(at, False)
prev, nxt = (near, nearest(near + timedelta(days=_SYNODIC_DAYS), False)) if near <= at else (nearest(near - timedelta(days=_SYNODIC_DAYS), False), near)
return (at - prev) / (nxt - prev)
# 달 모양 이름. 차오르는 비율(0 삭 → 0.5 보름 → 1 삭) 구간마다
_NAMES = ((0.03, "삭"), (0.22, "초승달"), (0.28, "상현달"), (0.47, "차오르는 달"), (0.53, "보름달"), (0.72, "기우는 달"), (0.78, "하현달"), (0.97, "그믐달"), (1.0, "삭"))
def phase_name(at: datetime) -> str:
"""그 시각 달 모양 이름 (삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달)."""
p = _fraction(at)
return next(name for limit, name in _NAMES if p < limit)
def _true_phase(k: float, full: bool) -> datetime:
"""Meeus 천문 알고리즘 49장. k 는 2000년 1월 기준 몇 번째 삭(보름이면 +0.5). 오차 몇 분."""
t = k / 1236.85
jde = 2451550.09766 + 29.530588861 * k + 0.00015437 * t**2 - 0.000000150 * t**3 + 0.00000000073 * t**4
e = 1 - 0.002516 * t - 0.0000074 * t**2
r = math.radians
m = r(2.5534 + 29.10535670 * k - 0.0000014 * t**2 - 0.00000011 * t**3)
mp = r(201.5643 + 385.81693528 * k + 0.0107582 * t**2 + 0.00001238 * t**3 - 0.000000058 * t**4)
f = r(160.7108 + 390.67050284 * k - 0.0016118 * t**2 - 0.00000227 * t**3 + 0.000000011 * t**4)
om = r(124.7746 - 1.56375588 * k + 0.0020672 * t**2 + 0.00000215 * t**3)
s = math.sin
a, b, c, d = (-0.40614, 0.17302, 0.01614, 0.01043) if full else (-0.40720, 0.17241, 0.01608, 0.01039)
jde += (a * s(mp) + b * e * s(m) + c * s(2 * mp) + d * s(2 * f) + (0.00734 if full else 0.00739) * e * s(mp - m)
- 0.00515 * e * s(mp + m) + (0.00209 if full else 0.00208) * e * e * s(2 * m) - 0.00111 * s(mp - 2 * f)
- 0.00057 * s(mp + 2 * f) + 0.00056 * e * s(2 * mp + m) - 0.00042 * s(3 * mp) + 0.00042 * e * s(m + 2 * f)
+ 0.00038 * e * s(m - 2 * f) - 0.00024 * e * s(2 * mp - m) - 0.00017 * s(om))
return datetime(2000, 1, 1, 12, tzinfo=timezone.utc) + timedelta(days=jde - 2451545.0)
def nearest(at: datetime, full: bool) -> datetime:
"""at 에서 가장 가까운 보름(full) 또는 삭의 실제 시각 (UTC)."""
offset = 0.5 if full else 0.0
k = round((at - _KNOWN_NEW_MOON).total_seconds() / 86400 / _SYNODIC_DAYS - offset) + offset
return min((_true_phase(k + dk, full) for dk in (-1, 0, 1)), key=lambda x: abs(x - at))
+30 -3
View File
@@ -2,7 +2,7 @@ import statistics
from dataclasses import dataclass
from datetime import datetime, timedelta
from common.enums import Confidence, SkyGrade, SkyType
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
DISTANCES_KM = (20, 50, 100)
@@ -49,10 +49,10 @@ def best_times(kind: SkyType, sun_at: datetime, twilight_at: datetime, high_clou
return [
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 져요"},
{"at": (sun_at + timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "블루아워"},
]
return [
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "푸른 새벽"},
{"at": twilight_at.isoformat(), "kind": "twilight", "label": "블루아워"},
{"at": (sun_at - timedelta(minutes=peak_min)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
{"at": sun_at.isoformat(), "kind": "sun", "label": "해 떠요"},
]
@@ -73,6 +73,33 @@ def mean_layers(rows: list[Layers]) -> Layers:
return Layers(*(statistics.mean(getattr(r, k) for r in rows) for k in ("low", "mid", "high")))
def situation(near20: Layers, near50: Layers, far100: Layers) -> SkySituation:
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
return SkySituation.COVERED
if (near20.low + near50.low) / 2 >= 60:
return SkySituation.LOW_CLOUD
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
if canvas < 25:
return SkySituation.FEW
if canvas > 75:
return SkySituation.THICK
return SkySituation.GLOW
SITUATION_LINE = {
SkySituation.COVERED: "구름에 가려요",
SkySituation.LOW_CLOUD: "낮은 구름이 덮어요",
SkySituation.FEW: "구름이 적어 짧게 끝나요",
SkySituation.GLOW: "하늘이 넓게 물들 수 있어요",
SkySituation.THICK: "구름이 두꺼워 색이 약해요",
}
SITUATION_VERDICT = {
SkySituation.COVERED: "rest", SkySituation.LOW_CLOUD: "rest", SkySituation.FEW: "maybe", SkySituation.GLOW: "go", SkySituation.THICK: "maybe",
}
VERDICT_RANK = {"rest": 0, "maybe": 1, "go": 2}
def reason(near20: Layers, near50: Layers, far100: Layers) -> str:
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
if far100.low + 0.5 * far100.mid >= 60:
+31 -19
View File
@@ -1,22 +1,28 @@
import asyncio
import html
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
from config.settings import settings
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.guard import Unreachable, guarded
# 한국문화정보원 한눈에보는문화정보조회서비스 (분야별 목록). 응답은 XML.
REALM_URL = "https://apis.data.go.kr/B553457/cultureinfo/realm2"
EXHIBITION = "D000"
CONCERT = "B000" # 음악/콘서트
_REALM_KIND = {EXHIBITION: EventKind.EXHIBITION, CONCERT: EventKind.CONCERT}
# event.source_id 접두어. TourAPI contentid(숫자)와 겹치지 않게 한다.
SOURCE_PREFIX = "kcis:"
IMAGE_CREDIT = "ⓒ한국문화정보원"
_PAGE_SIZE = 100
_ATTEMPTS = 3
_BACKOFF_SEC = 1.5
_BACKOFF_SEC = 1.0
_PAGE_GAP_SEC = 1.0 # 쪽을 쉬지 않고 받으면 초당 요청 제한(코드 23)에 걸린다
# 법정동 시도 코드 앞 두 자리 → 문화정보 API 의 sido 값
SIDO_NAME = {
@@ -29,6 +35,10 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
"""한 쪽을 받아 (item 목록, totalCount). 로그·예외에 키를 남기지 않는다."""
if not settings.data_go_kr_service_key:
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
return await guarded("datagokr:realm2", lambda: _try_page(client, params), DataGoKrRequestFailed)
async def _try_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict], int]:
last = ""
for attempt in range(_ATTEMPTS):
try:
@@ -36,28 +46,28 @@ async def _get_page(client: httpx.AsyncClient, params: dict) -> tuple[list[dict]
root = ET.fromstring(res.content)
except (httpx.HTTPError, ET.ParseError) as e:
last = type(e).__name__
else:
reason = root.findtext(".//returnReasonCode")
if reason:
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
code = root.findtext(".//resultCode")
if code not in (None, "00", "0000"):
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
if res.status_code == 200:
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
return items, int(root.findtext(".//totalCount") or 0)
last = f"HTTP {res.status_code}"
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
continue
reason = root.findtext(".//returnReasonCode")
if reason:
raise DataGoKrRequestFailed(f"realm2 {reason} {root.findtext('.//errMsg')}")
code = root.findtext(".//resultCode")
if code not in (None, "00", "0000"):
raise DataGoKrRequestFailed(f"realm2 {code} {root.findtext('.//resultMsg')}")
if res.status_code == 200:
items = [{c.tag: (c.text or "").strip() for c in it} for it in root.iter("item")]
return items, int(root.findtext(".//totalCount") or 0)
last = f"HTTP {res.status_code}"
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise DataGoKrRequestFailed(f"realm2 failed after {_ATTEMPTS} attempts: {last}")
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last}")
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int) -> list[dict]:
"""시도의 전시(미술관·박물관 등) 중 since~since+days 사이에 열리는 것."""
async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: date, days: int, realm: str = EXHIBITION) -> list[dict]:
"""시도의 realm 분야(기본 전시) 중 since~since+days 사이에 열리는 것."""
sido = SIDO_NAME.get(sido_code)
if sido is None:
return []
params = {"realmCode": EXHIBITION, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
params = {"realmCode": realm, "sido": sido, "from": since.strftime("%Y%m%d"), "to": (since + timedelta(days=days)).strftime("%Y%m%d")}
items: list[dict] = []
page = 1
while True:
@@ -66,6 +76,7 @@ async def fetch_exhibitions(client: httpx.AsyncClient, sido_code: str, since: da
if not chunk or len(items) >= total:
return items
page += 1
await asyncio.sleep(_PAGE_GAP_SEC)
def _date(v: Optional[str]) -> Optional[date]:
@@ -83,7 +94,7 @@ def _coord(v: Optional[str]) -> Optional[float]:
return None
def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[dict]:
def parse_exhibitions(items: list[dict], sido_code: str, since: date, realm: str = EXHIBITION) -> list[dict]:
rows: dict[str, dict] = {}
for it in items:
start, end = _date(it.get("startDate")), _date(it.get("endDate"))
@@ -94,8 +105,9 @@ def parse_exhibitions(items: list[dict], sido_code: str, since: date) -> list[di
lat, lon = (y, x) if x is None or y is None or x > y else (x, y)
source_id = f"{SOURCE_PREFIX}{it['seq']}"
rows.setdefault(source_id, {
"source_id": source_id, "sido_code": sido_code, "name": it.get("title", "")[:60], "place_name": (it.get("place") or "")[:60],
"source_id": source_id, "sido_code": sido_code, "name": html.unescape(it.get("title", ""))[:60], "place_name": html.unescape(it.get("place") or "")[:60],
"start_date": start, "end_date": end, "is_confirmed": True, "source_url": None,
"image_url": (it.get("thumbnail") or "").replace("http://", "https://", 1) or None, "lat": lat, "lon": lon,
"kind": _REALM_KIND[realm], "icon": EVENT_ICON[_REALM_KIND[realm]],
})
return list(rows.values())
+11 -5
View File
@@ -3,9 +3,10 @@ import asyncio
import httpx
from config.settings import settings
from services.external.guard import Unreachable, guarded
_ATTEMPTS = 3
_BACKOFF_SEC = 1.5
_BACKOFF_SEC = 1.0
class DataGoKrNotConfigured(RuntimeError):
@@ -17,15 +18,20 @@ class DataGoKrRequestFailed(RuntimeError):
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도한다. 로그·예외에 키를 남기지 않는다."""
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
if not settings.data_go_kr_service_key:
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
op = url.rsplit("/", 1)[-1]
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
last = ""
for attempt in range(_ATTEMPTS):
try:
res = await client.get(url, params={"serviceKey": settings.data_go_kr_service_key, **params})
data = res.json() if res.status_code == 200 else None
last = "" if data else f"HTTP {res.status_code}"
except (httpx.HTTPError, ValueError) as e:
data, last = None, type(e).__name__
if data and "response" in data:
@@ -33,9 +39,9 @@ async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
if header.get("resultCode", "00") not in ("00", "0000"):
raise DataGoKrRequestFailed(f"{op} {header.get('resultCode')} {header.get('resultMsg')}")
return data["response"]["body"]
last = last or f"HTTP {res.status_code}"
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise DataGoKrRequestFailed(f"{op} failed after {_ATTEMPTS} attempts: {last}")
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(_BACKOFF_SEC * (attempt + 1))
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}")
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]:
+46
View File
@@ -0,0 +1,46 @@
import asyncio
from typing import Awaitable, Callable, Optional, TypeVar
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.logger import LOG
T = TypeVar("T")
BUDGET_SEC = 8.0 # 재시도까지 합쳐 한 번 호출에 기다리는 최대 시간
DOWN_SEC = 120 # 응답이 없던 API 는 이 시간 동안 부르지 않고 바로 실패로 돌린다
class Unreachable(Exception):
"""재시도해도 응답을 못 받음 (연결 실패·HTTP 오류). API 가 준 오류 코드와 달리 '잠시 쉬기' 대상이다."""
async def _is_down(name: str) -> bool:
try:
return bool(await REDIS.conn.exists(f"apidown:{name}"))
except RedisError as e:
LOG.error(f"[api] {name} down check: {e}")
return False
async def _mark_down(name: str, reason: str) -> None:
LOG.error(f"[api] {name} 응답 없음, {DOWN_SEC}초 동안 부르지 않음: {reason}")
try:
await REDIS.conn.set(f"apidown:{name}", reason[:200], ex=DOWN_SEC)
except RedisError as e:
LOG.error(f"[api] {name} mark down: {e}")
async def guarded(name: str, call: Callable[[], Awaitable[T]], fail: type[Exception], budget_sec: Optional[float] = None) -> T:
"""외부 API 호출을 budget_sec 안에 끝내고, 응답이 없던 API 는 DOWN_SEC 동안 기다리지 않고 바로 fail 을 던진다."""
if await _is_down(name):
raise fail(f"{name} skipped: no answer within the last {DOWN_SEC}s")
budget_sec = budget_sec or BUDGET_SEC
try:
async with asyncio.timeout(budget_sec):
return await call()
except (TimeoutError, Unreachable) as e:
reason = str(e) or f"no answer within {budget_sec:.0f}s"
await _mark_down(name, reason)
raise fail(f"{name} {reason}") from None
+11 -4
View File
@@ -4,10 +4,12 @@ from datetime import datetime, timezone
import httpx
from common.enums import CloudModel
from services.external.guard import Unreachable, guarded
URL = "https://api.open-meteo.com/v1/forecast"
MODELS = {"ecmwf_ifs025": CloudModel.ECMWF, "gfs_seamless": CloudModel.GFS, "jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
_ATTEMPTS = 3
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
class OpenMeteoRequestFailed(RuntimeError):
@@ -20,8 +22,12 @@ _CHUNK = 24
async def fetch_clouds(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 3) -> list[dict]:
"""좌표마다 시간별 층별 구름을 모델 4개로. 한 요청에 좌표가 많으면 느려서 나눠 동시에 보낸다. 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
async def all_chunks() -> list[dict]:
results = await asyncio.gather(*[_fetch_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
return await guarded("openmeteo", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
@@ -39,8 +45,9 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
return data if isinstance(data, list) else [data]
except (httpx.HTTPError, ValueError) as e:
last = f"{type(e).__name__} {getattr(getattr(e, 'response', None), 'status_code', '')}".strip()
await asyncio.sleep(1.0 * (attempt + 1))
raise OpenMeteoRequestFailed(f"forecast {len(points)} points: {last}")
if attempt < _ATTEMPTS - 1:
await asyncio.sleep(1.0 * (attempt + 1))
raise Unreachable(f"forecast {len(points)} points: {last}")
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
+107
View File
@@ -0,0 +1,107 @@
import asyncio
import html
import json
import re
from datetime import date
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
# 팝가(popga.co.kr) 팝업스토어. 공개 API 가 없어 robots.txt 가 허용하는 사이트맵·상세 페이지를 읽는다.
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
POPUP_URL = "https://popga.co.kr/popup/{id}"
SOURCE_PREFIX = "popga:"
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
REQUEST_GAP_SEC = 0.3
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
_URL = re.compile(r"<url>(.*?)</url>", re.S)
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
_POPUP_PATH = re.compile(r"^https://popga\.co\.kr/popup/(\d+)$")
_LD_JSON = re.compile(r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', re.S)
_SIDO = {
"서울": "11", "부산": "26", "대구": "27", "인천": "28", "광주": "29", "대전": "30", "울산": "31", "세종": "36", "경기": "41",
"충북": "43", "충남": "44", "전남": "46", "경북": "47", "경남": "48", "제주": "50", "강원": "51", "전북": "52",
"충청북도": "43", "충청남도": "44", "전라남도": "46", "경상북도": "47", "경상남도": "48", "전라북도": "52",
}
async def fetch_popup_index(client: httpx.AsyncClient) -> dict[int, str]:
"""사이트맵 전체에서 팝업 상세 페이지 {id: lastmod}."""
res = await client.get(SITEMAP_URL)
res.raise_for_status()
found: dict[int, str] = {}
for sitemap in _LOC.findall(res.text):
await asyncio.sleep(REQUEST_GAP_SEC)
part = await client.get(sitemap)
part.raise_for_status()
for block in _URL.findall(part.text):
loc, mod = _LOC.search(block), _LASTMOD.search(block)
m = _POPUP_PATH.match(loc.group(1)) if loc else None
if m:
found[int(m.group(1))] = mod.group(1) if mod else ""
return found
async def fetch_popup_page(client: httpx.AsyncClient, popup_id: int) -> str:
res = await client.get(POPUP_URL.format(id=popup_id))
res.raise_for_status()
return res.text
def sido_of(address: str) -> Optional[str]:
"""주소 첫 낱말("서울", "서울특별시", "경상남도")로 시도 코드."""
first = (address or "").split(" ", 1)[0]
if first in _SIDO:
return _SIDO[first]
return next((code for name, code in _SIDO.items() if len(name) == 2 and first.startswith(name)), None)
def _event_ld(page: str) -> Optional[dict]:
for block in _LD_JSON.findall(page):
try:
data = json.loads(block)
except json.JSONDecodeError:
continue
if isinstance(data, dict) and data.get("@type") == "Event":
return data
return None
def _date(v) -> Optional[date]:
try:
return date.fromisoformat(str(v)[:10])
except ValueError:
return None
def _coord(v) -> Optional[float]:
try:
return round(float(v), 5) if v not in (None, "") else None
except (TypeError, ValueError):
return None
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None."""
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
ld = _event_ld(page)
if kind is None or kind.group(1) != STORE or ld is None:
return None
start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
if start is None or end is None or end < since:
return None
loc = ld.get("location") or {}
sido = sido_of((loc.get("address") or {}).get("streetAddress", ""))
if sido is None:
return None
geo = loc.get("geo") or {}
return {
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60],
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": POPUP_URL.format(id=popup_id), "image_url": None,
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": EventKind.POPUP, "icon": EVENT_ICON[EventKind.POPUP],
}
+44
View File
@@ -0,0 +1,44 @@
import httpx
from common.logger import LOG
from config.settings import settings
TIMEOUT_SEC = 10.0
def _card(title: str, detail: str) -> dict:
"""Adaptive Card 1.2 — Teams Workflows 수신 webhook 이 받는 최소 모양."""
return {
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": True},
{"type": "TextBlock", "text": detail, "wrap": True},
],
},
}],
}
async def send(title: str, detail: str) -> bool:
"""TEAMS_WEBHOOK_URL 이 있을 때만 보낸다. 로그에 주소를 남기지 않는다."""
url = settings.teams_webhook_url.strip()
if not url:
return False
if not url.startswith("https://"):
LOG.error("[teams] TEAMS_WEBHOOK_URL 이 https 가 아니다")
return False
try:
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, follow_redirects=False) as client:
res = await client.post(url, json=_card(title, detail))
res.raise_for_status()
return True
except httpx.HTTPError as e:
LOG.error(f"[teams] send failed: {type(e).__name__}")
return False
+2 -1
View File
@@ -3,6 +3,7 @@ from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
from services.external.data_go_kr import get_all_items
FESTIVAL_URL = "https://apis.data.go.kr/B551011/KorService2/searchFestival2"
@@ -36,6 +37,6 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")),
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
})
return rows
+80 -31
View File
@@ -11,7 +11,7 @@ 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.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, SkyGrade, WarningType
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, Sky, SkyGrade, SkySituation, WarningType
from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
from common.utils.text import compass, day_range, hour_label, short_day
@@ -25,18 +25,20 @@ 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.sky_score import GRADE_LABEL
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.index_service import IndexBoard, IndexItem, IndexService
from services.now_service import NowService, NowWeather
from services.season_service import SeasonService
from services.sky_service import SkyService, SkyView
from services.sky_service import SkyService, SkyView, day_verdict
from services.sky_service import outlook as sky_outlook
from services.weather_service import TodayWeather, WeatherService
from services.week_service import DayPlan, EventItem, WeekService, image_credit
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
from services.weekend_plan import day_plan, forecast, pick_events
from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드기획_v2.html).
# 그날 피드 카드: (번호, 종류, 참조, 지수 순위). 03:00 에 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정한다 (docs/피드_기획.html).
LINEUP = [
(1, PostType.WEATHER, RefType.NONE, None),
(2, PostType.ALERT, RefType.NONE, None),
@@ -56,13 +58,14 @@ LINEUP = [
(16, PostType.WEEKEND_PLAN, RefType.NONE, 2),
(17, PostType.AIR, RefType.NONE, None),
(18, PostType.DAY_TRIP, RefType.NONE, None),
(19, PostType.MOON, 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.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.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.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.QUOTE],
"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],
"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],
}
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
@@ -335,7 +338,7 @@ class FeedService:
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
bands=Bands(
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
image=e.event.image_url, image_credit=image_credit(e.event)) for e in events[:4]],
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)
@@ -373,6 +376,7 @@ class FeedService:
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None,
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
)
@staticmethod
@@ -411,12 +415,12 @@ class FeedService:
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])
if t is PostType.EVENT:
soon = [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()]
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
if len(soon) < rank:
return None
e = soon[rank - 1]
rows = ([Row(label="장소", value=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
caption = _event_caption(e)
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))],
@@ -440,8 +444,46 @@ class FeedService:
return self._quote(base, c)
if t is PostType.DAY_TRIP and c.trip is not None:
return self._day_trip(base, *c.trip)
if t is PostType.MOON:
return self._moon(base, c)
return None
def _moon(self, base: dict, c: "_Ctx") -> PostData:
"""오늘 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기를, 아니면 달 모양·밝기와 다음 보름. 피드 아래쪽에 둔다."""
tonight = _tonight(c.now)
start = tonight.replace(hour=12)
full, new = nearest(tonight, True).astimezone(KST), nearest(tonight, False).astimezone(KST)
at, is_full = (full, True) if start <= full < start + timedelta(days=1) else (new, False) if start <= new < start + timedelta(days=1) else (None, False)
row = next((h for h in c.hourly if h.forecast_at.astimezone(KST) == tonight), None)
sky = Sky(row.sky) if row is not None else None
rows = [Row(label="밤 하늘", value=_MOON_SKY[sky])] if sky is not None else []
eyebrow = f"오늘 밤 달 · {c.region.short_name}"
if at is None:
name, pct = phase_name(tonight), round(illumination(tonight) * 100)
nxt = nearest(tonight + timedelta(days=15), True) if full < tonight else full
nxt = nxt.astimezone(KST)
waxing = name in ("초승달", "상현달", "차오르는 달")
caption = ("구름이 많아 달은 숨바꼭질해요." if sky is Sky.CLOUDY
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n밝기 {pct}%", icon="moon",
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
share_messages=[f"오늘 밤은 {name}이래 🌙"])
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
if is_full:
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
caption = "구름 사이로 잠깐씩 보일 수 있어요." if sky is Sky.CLOUDY else "소원 빌기 딱 좋은 밤이에요 🌕"
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="달 밝기", value="100%"), *rows])],
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
if stars is not None:
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=[Row(label="달 밝기", value="0%"), *rows])],
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
"""1~2시간 거리 후보 도시 중 이번 주말 나들이 점수 1위. 첫 장은 도시·날씨, 뒤로 그날 그곳 행사 최대 2장."""
b = pick.best
@@ -453,7 +495,7 @@ class FeedService:
rows.append(Row(label="볼거리", value=pick.note))
slides = [RowsSlide(kind="rows", eyebrow=f"당일치기 · {when} {short_day(b.day)}", line=f"{when}엔 {pick.label},\n나들이 {b.score}점", icon=b.icon, rows=rows)]
for e in events:
ev_rows = ([Row(label="장소", value=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
ev_rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))]
slides.append(RowsSlide(kind="rows", eyebrow=f"{pick.label} 근처 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=ev_rows,
image=e.event.image_url, image_credit=image_credit(e.event)))
if pick.runner_up is not None:
@@ -526,30 +568,29 @@ class FeedService:
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
def _sunset(self, base: dict, c: "_Ctx") -> Optional[PostData]:
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 60점 미만이면 한 줄 카드."""
"""해 지기 전엔 오늘, 진 뒤엔 내일 노을. 하늘 상황으로 말하고, '쉬어요'면 한 줄 카드."""
after = c.now >= c.sunset_at
target = next((x for x in c.sky.days if x.score_date > c.now.date()), None) if after else c.sky.sunset
if target is None:
return None
when = "내일" if after else "오늘"
grade = GRADE_LABEL[SkyGrade(target.grade)]
if target.score < _SUNSET_FULL:
nxt = None if after else next((x for x in c.sky.days if x.score_date > c.now.date()), None)
caption = "구름에 가려요." + (f" 내일 노을 {nxt.score}점이에요." if nxt is not None else "")
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=caption, slides=[],
share_messages=[f"{when} 노을은 구름에 가려요"])
peak = next((b for b in target.best_times if b["kind"] == "peak"), target.best_times[0])
peak_at = datetime.fromisoformat(peak["at"]).astimezone(KST)
side = compass(c.sky.sunset_azimuth)
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=f"{peak_at:%H:%M}, {side}쪽이 가장 붉어요", score=target.score,
grade_label=grade, cuts=[Cut(**b) for b in target.best_times])]
sit = SkySituation(target.situation) if target.situation else None
line = SITUATION_LINE[sit] if sit else GRADE_LABEL[SkyGrade(target.grade)]
better = sky_outlook(target, c.sky.days, c.now.date())
sun = next((b for b in target.best_times if b["kind"] == "sun"), target.best_times[0])
sun_at = datetime.fromisoformat(sun["at"]).astimezone(KST)
if day_verdict(target) == "rest":
return PostData(**base, size="line", title=f"{when} 노을은 쉬어요", icon="sunset", caption=f"{line}." + (f" {better}" if better else ""),
slides=[], share_messages=[f"{when} 노을은 쉬어요, {line}"])
cuts = [Cut(**b) for b in target.best_times if b["kind"] != "peak"]
slides = [SunsetSlide(kind="sunset", eyebrow=f"{when} 노을 · {c.region.name}", line=line, score=target.score,
grade_label=line, cuts=cuts, situation=sit)]
if c.sky.spots:
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {side}쪽이 트인 곳", icon="sunset",
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{x.distance_km}km") for n, x in enumerate(c.sky.spots)]))
nxt = next((x for x in c.sky.days if x.score_date > target.score_date), None)
caption = f"{'모레' if after else '내일'} 노을은 {nxt.score}점이에요." if nxt is not None else "가장 붉은 때 앞뒤 20분이 골든타임이에요."
return PostData(**base, title=f"{when} 노을 {target.score}점", icon="sunset", caption=caption,
slides=slides, share_messages=[f"{when} 노을 {target.score}점이래 🌇 {peak_at:%H:%M}에 같이 볼래?"])
slides.append(RowsSlide(kind="rows", eyebrow="가까운 노을 명소", line=f"해 지는 {compass(c.sky.sunset_azimuth)}쪽", icon="sunset",
rows=[Row(label=f"{n + 1} {x.spot.name}", value=f"{compass(x.direction)} {x.distance_km}km", place=x.spot.name) for n, x in enumerate(c.sky.spots)]))
caption = better or "보통 해 진 뒤 10~20분이 가장 붉어요."
return PostData(**base, title=f"{when} 노을 · {line}", icon="sunset", caption=caption,
slides=slides, share_messages=[f"{when} 노을, {line} 🌇 {sun_at:%H:%M}에 해 져요"])
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
tomorrow = c.now.date() + timedelta(days=1)
@@ -616,6 +657,14 @@ def _event_caption(e: EventItem) -> str:
return "일정이 확정됐어요." if e.event.is_confirmed else "올해 정확한 일정은 공식 안내로 확인해 주세요."
_MOON_SKY = {Sky.CLEAR: "맑음, 잘 보여요", Sky.PARTLY: "구름 조금, 사이사이 보여요", Sky.CLOUDY: "흐림, 가려질 수 있어요"}
def _tonight(now: datetime) -> datetime:
"""'오늘 밤' 22시. 피드 하루(03:00 시작)와 맞춰, 자정~03시는 전날 밤으로 본다."""
return datetime.combine(feed_day(now.astimezone(KST)), time(22), tzinfo=KST)
@dataclass
class _Ctx:
region: Region
+40 -16
View File
@@ -13,14 +13,15 @@ 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, SkyScore, SunsetSpot
from common.enums import ErrorType, SkyGrade, SkyType
from common.enums import ErrorType, SkyGrade, SkySituation, SkyType
from common.logger import LOG
from common.utils.geo import destination, haversine_km
from common.utils.geo import bearing_deg, destination, haversine_km
from common.utils.kma_time import KST, now_kst
from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
from services.calc.sky_score import (
DISTANCES_KM, GRADE_LABEL, VERDICT_LINE, Layers, best_times, confidence, grade, mean_layers, reason, score, sunset_timeline, verdict,
DISTANCES_KM, GRADE_LABEL, SITUATION_LINE, SITUATION_VERDICT, VERDICT_LINE, VERDICT_RANK, Layers, best_times, confidence, grade, mean_layers,
reason, score, situation, sunset_timeline, verdict,
)
from services.calc.sun import SunTimes, sun_times
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds, parse_clouds
@@ -37,6 +38,7 @@ _background: set[asyncio.Task] = set()
class Spot:
spot: SunsetSpot
distance_km: float
direction: float = 0.0 # 내 구에서 본 방위각
@dataclass
@@ -49,6 +51,9 @@ class SkyPlan:
reason: str
score: int
grade_label: str
situation_label: Optional[str]
models_total: Optional[int]
models_agree: Optional[int]
best_at: Optional[datetime]
spot: Optional[Spot]
timeline: list[dict]
@@ -75,7 +80,8 @@ 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)) for p in spots]
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]
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
@@ -96,21 +102,23 @@ def _subject(word: str) -> str:
return f"{word}{'이' if 0 <= last < 11172 and last % 28 else '가'}"
def day_verdict(x: SkyScore) -> str:
"""하늘 상황이 있으면 그걸로, 없으면(예전 계산분) 점수로."""
return SITUATION_VERDICT[SkySituation(x.situation)] if x.situation else verdict(x.score)
def outlook(target: SkyScore, days: list[SkyScore], today: date) -> str:
"""target 다음 날들 중 가장 나은 날과 비교한다. 10점 넘게 차이 나야 낫다고 말한다."""
later = [x for x in days if x.score_date > target.score_date]
"""뒤의 날 중 결론이 더 좋은 날이 있을 때만 한 줄. 없으면 빈 문자열."""
later = [x for x in days if x.score_date > target.score_date and VERDICT_RANK[day_verdict(x)] > VERDICT_RANK[day_verdict(target)]]
if not later:
return ""
best = max(later, key=lambda x: x.score)
if best.score - target.score > _OUTLOOK_GAP:
return f"{_subject(_word(best.score_date, today))} 더 나아요 — {best.score}점, {VERDICT_LINE[verdict(best.score)]}"
if target.score - best.score > _OUTLOOK_GAP:
return f"{_subject(_word(target.score_date, today))} 가장 나아요 — 뒤로 갈수록 못해요"
return f"{'·'.join(_word(x.score_date, today) for x in later)}도 비슷해요"
best = max(later, key=lambda x: (VERDICT_RANK[day_verdict(x)], x.score))
line = SITUATION_LINE[SkySituation(best.situation)] if best.situation else VERDICT_LINE[day_verdict(best)]
return f"{_subject(_word(best.score_date, today))} 더 나아요 · {line}"
def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], spots: list[Spot], days: list[SkyScore], today: date) -> SkyPlan:
v = verdict(target.score)
v = day_verdict(target)
when = _word(target.score_date, today)
peak = next((b for b in target.best_times if b["kind"] == "peak"), None)
peak_at = datetime.fromisoformat(peak["at"]) if peak else None
@@ -118,8 +126,10 @@ def build_plan(target: SkyScore, st: SunTimes, layers: Optional[list[Layers]], s
day=target.score_date, when=when, verdict=v, headline=VERDICT_LINE[v],
reason=reason(*layers) if layers else _FALLBACK_REASON[v],
score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
situation_label=SITUATION_LINE[SkySituation(target.situation)] if target.situation else None,
models_total=target.models_total, models_agree=target.models_agree,
best_at=peak_at, spot=spots[0] if spots and v != "rest" else None,
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), peak_at, st.dusk_end_at.astimezone(KST)),
timeline=sunset_timeline(st.golden_start_at.astimezone(KST), st.sunset_at.astimezone(KST), None, st.dusk_end_at.astimezone(KST)),
outlook=outlook(target, days, today),
)
@@ -149,26 +159,40 @@ def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> lis
st: SunTimes = sun_times(d, float(region.lat), float(region.lon))
sun_at, twilight_at = (st.sunset_at, st.dusk_end_at) if kind is SkyType.SUNSET else (st.sunrise_at, st.dawn_start_at)
hour = _nearest_hour(sun_at)
per_model = []
highs = []
per_model, highs, model_layers = [], [], []
for model in {k[2] for k in clouds}:
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
if None in layers:
continue
per_model.append(score(*layers))
highs.append((layers[0].high + layers[1].high) / 2)
model_layers.append(layers)
if not per_model:
continue
value = round(statistics.mean(per_model))
sit = situation(*(mean_layers([m[k] for m in model_layers]) for k in range(3)))
rows.append({
"region_code": region.code, "score_date": d, "sky_type": kind.value, "score": value, "grade": grade(value).value,
"confidence": confidence(per_model).value,
"best_times": best_times(kind, sun_at.astimezone(KST), twilight_at.astimezone(KST), statistics.mean(highs)),
"computed_at": now,
"situation": sit.value, "models_total": len(model_layers), "models_agree": sum(situation(*m) is sit for m in model_layers),
})
return rows
def ranking_summary(items: list["RankItem"]) -> Optional[str]:
"""대표 30곳 대부분(70% 이상)이 같은 상황이면 한 줄로. 점수 차이가 작아 순위만으론 뜻이 없는 날."""
sits = [x.score.situation for x in items if x.score.situation]
if len(sits) < 5:
return None
for sit, line in ((SkySituation.FEW, "오늘은 전국이 맑아 대부분 짧게 끝나요"), (SkySituation.COVERED, "오늘은 전국 대부분 구름에 가려요"),
(SkySituation.LOW_CLOUD, "오늘은 전국 대부분 낮은 구름이 덮어요")):
if sits.count(sit.value) >= 0.7 * len(sits):
return line
return None
class SkyService:
def __init__(self, regions: RegionCRUD = Depends(RegionCRUD), crud: SkyCRUD = Depends(SkyCRUD)) -> None:
self.regions = regions
+43 -30
View File
@@ -11,7 +11,7 @@ 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 Event, Place, Region, WeatherDaily
from common.enums import ErrorType, RainType, Sky
from common.enums import ErrorType, EventKind, RainType, Sky
from common.logger import LOG
from common.utils.geo import haversine_km
from common.utils.kma_time import KST, kst_midnight, now_kst
@@ -22,7 +22,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
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 fetch_exhibitions, parse_exhibitions
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kasi import fetch_holidays
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
@@ -100,6 +100,21 @@ def image_credit(e: Event) -> Optional[str]:
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
_MIX_ORDER = (EventKind.FESTIVAL, EventKind.POPUP, EventKind.EXHIBITION, EventKind.CONCERT)
def mix_kinds(items: list[EventItem]) -> list[EventItem]:
"""종류(축제→팝업→전시→콘서트)를 돌아가며 하나씩. 같은 종류 안에서는 받은 순서를 지킨다."""
queues = [[e for e in items if e.event.kind == k] for k in _MIX_ORDER]
queues.append([e for e in items if e.event.kind not in _MIX_ORDER])
mixed = []
while any(queues):
for q in queues:
if q:
mixed.append(q.pop(0))
return mixed
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
lat, lon = float(region.lat), float(region.lon)
@@ -131,6 +146,31 @@ def _status(e: Event, today: date) -> tuple[str, str]:
return "soon", f"D-{days}"
async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str) -> list[dict]:
"""문화정보원 전시·콘서트. 실패해도 TourAPI 행사는 그대로 넣게 여기서 로그만 남긴다."""
try:
return parse_exhibitions(await fetch_exhibitions(client, sido, today, EVENT_DAYS, realm), sido, today, realm)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
LOG.error(f"[week] culture {realm} {sido}: {e}")
return []
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
try:
async with httpx.AsyncClient(timeout=30) as client:
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
exhibitions = await _culture(client, sido, today, EXHIBITION)
concerts = await _culture(client, sido, today, CONCERT)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
LOG.error(f"[week] events {sido}: {e}")
return ErrorType.EXTERNAL_API_ERROR, {}
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values())
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
class WeekService:
def __init__(
self,
@@ -214,8 +254,7 @@ class WeekService:
return err, []
sidos = nearby_sidos(region, regions)
await asyncio.gather(
*(self._ensure_events(sido, today) for sido in sidos), self.index_service.weather_service.ensure_vilage(region, now),
self.index_service.weather_service.ensure_mid(region, now),
self.index_service.weather_service.ensure_vilage(region, now), self.index_service.weather_service.ensure_mid(region, now),
)
err, events = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.events(s, sidos, today, today + timedelta(days=EVENT_DAYS)))
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, today, today + timedelta(days=DAYS - 1)))
@@ -258,29 +297,3 @@ class WeekService:
await REDIS.conn.set(key, "1", ex=30 * 86400)
except _ERRORS as e:
LOG.error(f"[week] holidays {year}: {e}")
async def _exhibitions(self, client: httpx.AsyncClient, sido: str, today: date) -> list[dict]:
"""문화정보원 전시. 실패해도 TourAPI 행사는 그대로 나가게 여기서 로그만 남긴다."""
try:
return parse_exhibitions(await fetch_exhibitions(client, sido, today, EVENT_DAYS), sido, today)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
LOG.error(f"[week] exhibitions {sido}: {e}")
return []
async def _ensure_events(self, sido: str, today: date) -> None:
key = f"event:{sido}:{today:%Y%m%d}"
try:
if await REDIS.conn.exists(key):
return
async with redis_lock(f"lock:{key}", ttl_sec=60) as acquired:
if not acquired:
return
async with httpx.AsyncClient(timeout=30) as client:
rows = parse_festivals(await fetch_festivals(client, sido, today), sido)
rows += await self._exhibitions(client, sido, today)
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_events(s, rows)])
if err is ErrorType.SUCCESS:
await REDIS.conn.set(key, "1", ex=86400)
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
except _ERRORS as e:
LOG.error(f"[week] events {sido}: {e}")