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:
1 parent
b61ed92c54
commit
997a366e76
70 files changed
+2083
-649
No files matched your search
@@ -121,6 +121,9 @@ class SkyScore(Base):
|
||||
confidence: Mapped[int] = mapped_column(SmallInteger)
|
||||
best_times: Mapped[list] = mapped_column(JSONB)
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
situation: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
models_total: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
models_agree: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
|
||||
|
||||
class SunsetSpot(Base):
|
||||
@@ -220,6 +223,7 @@ class Event(Base):
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
lat: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
lon: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
kind: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
|
||||
|
||||
class SolarTerm(Base):
|
||||
|
||||
@@ -91,6 +91,15 @@ class SkyGrade(CodeEnum):
|
||||
RED = 4
|
||||
|
||||
|
||||
class SkySituation(CodeEnum):
|
||||
"""노을·일출 하늘 상황. 구름 층으로 고른다 (sky_score.situation)."""
|
||||
COVERED = 1 # 해 지는 쪽 먼 하늘이 막힘
|
||||
LOW_CLOUD = 2 # 머리 위 낮은 구름
|
||||
FEW = 3 # 물들 구름이 적음 (맑은 날 대부분)
|
||||
GLOW = 4 # 중·높은 구름이 알맞음
|
||||
THICK = 5 # 중·높은 구름이 두꺼움
|
||||
|
||||
|
||||
class Confidence(CodeEnum):
|
||||
HIGH = 1
|
||||
NORMAL = 2
|
||||
@@ -125,6 +134,18 @@ class PostType(CodeEnum):
|
||||
WEEKEND_PLAN = 11
|
||||
AIR = 12
|
||||
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
|
||||
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
|
||||
|
||||
|
||||
class EventKind(CodeEnum):
|
||||
FESTIVAL = 1
|
||||
EXHIBITION = 2
|
||||
CONCERT = 3
|
||||
POPUP = 4
|
||||
|
||||
|
||||
# 행사 종류별 아이콘 (사진이 없을 때 보인다, 프론트 public/b/icons)
|
||||
EVENT_ICON = {EventKind.FESTIVAL: "fireworks", EventKind.EXHIBITION: "exhibition", EventKind.CONCERT: "concert", EventKind.POPUP: "popup"}
|
||||
|
||||
|
||||
class RefType(CodeEnum):
|
||||
|
||||
@@ -10,6 +10,14 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
return 2 * _EARTH_RADIUS_KM * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def bearing_deg(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
"""1에서 2를 보는 방위각 (북 0°, 동 90°)."""
|
||||
p1, p2, dl = math.radians(lat1), math.radians(lat2), math.radians(lon2 - lon1)
|
||||
y = math.sin(dl) * math.cos(p2)
|
||||
x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
|
||||
return (math.degrees(math.atan2(y, x)) + 360) % 360
|
||||
|
||||
|
||||
def destination(lat: float, lon: float, bearing_deg: float, km: float) -> tuple[float, float]:
|
||||
"""출발점에서 방위각 방향으로 km 떨어진 지점."""
|
||||
d = km / _EARTH_RADIUS_KM
|
||||
|
||||
@@ -27,6 +27,7 @@ class Settings(BaseSettings):
|
||||
redis_db: int = 0
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
|
||||
@@ -28,7 +28,7 @@ class SkyCRUD:
|
||||
stmt = insert(SkyScore).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["region_code", "score_date", "sky_type"],
|
||||
set_={k: stmt.excluded[k] for k in ("score", "grade", "confidence", "best_times", "computed_at")},
|
||||
set_={k: stmt.excluded[k] for k in ("score", "grade", "confidence", "best_times", "computed_at", "situation", "models_total", "models_agree")},
|
||||
))
|
||||
|
||||
async def scores(self, s: AsyncSession, region_codes: list[str], since: date) -> list[SkyScore]:
|
||||
|
||||
@@ -45,7 +45,7 @@ class WeekCRUD:
|
||||
stmt = insert(Event).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["source_id"],
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon")},
|
||||
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
|
||||
))
|
||||
|
||||
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `../../docs/데이터흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `data-pipeline.md` (`.html` 은 같은 내용) | 외부 API를 언제 받아 어디에 저장·캐시하는지, 피드 칸, 하루 1번 스케줄, 테스트 DB | https://claude.ai/artifact/A4cE22L5aPnMfU53mKCSps |
|
||||
| `../../docs/데이터_흐름.html` | 데이터 흐름: 어디서 받는지와 그 이유, 피드 하나를 열면 무엇을 언제 받아 어디에 두는지, 하루 시계, 화면별 데이터 | https://claude.ai/artifact/CcdToNRntavNvo3XKNokqJ |
|
||||
| `api.html` | API 목록, 응답 예시, 프론트 연결(Hey API) | https://claude.ai/artifact/LjVYpLzomBTrkMxjDvAoDD |
|
||||
| `index-draft.html` | 활동 지수 기준 초안 (실제 값은 `seed/index_definition.json`) | https://claude.ai/artifact/RrgaKozLCycwduymWPXz4s |
|
||||
| `api-codegen.html` | 프론트 코드 생성 도구 비교 (Hey API 로 결정) | https://claude.ai/artifact/FPuknSnajrmxTM7hEpPKek |
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
<title>날씨각 데이터 흐름</title>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&family=IBM+Plex+Sans+KR:wght@400;600&family=IBM+Plex+Mono:wght@400&display=swap">
|
||||
<style>
|
||||
/* 한 단 문서: data-pipeline.md 와 같은 내용 */
|
||||
:root{
|
||||
--bg:#f5f7fb; --fg:#1c2433; --muted:#3f4a5c; --line:#d4dbe7; --soft:#e8edf5; --accent:#2457a6; --warn:#8f3c17; --ok:#1d6b46;
|
||||
--display:"Gowun Dodum","Apple SD Gothic Neo",sans-serif;
|
||||
--body:"IBM Plex Sans KR","Apple SD Gothic Neo","Malgun Gothic",sans-serif;
|
||||
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}}
|
||||
:root[data-theme="dark"]{--bg:#11161f;--fg:#e3e8f1;--muted:#a9b4c5;--line:#2a3443;--soft:#18202c;--accent:#8fb4f0;--warn:#f0a07a;--ok:#7fd8ab;color-scheme:dark}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--body);font-size:14.5px;line-height:1.65}
|
||||
main{max-width:1080px;margin:0 auto;padding-inline:20px;padding-block:32px 72px;display:flex;flex-direction:column;gap:34px}
|
||||
h1{font-family:var(--display);font-size:30px;margin:0;text-wrap:balance}
|
||||
h2{font-family:var(--display);font-size:22px;margin:0 0 10px;text-wrap:balance}
|
||||
h3{font-size:15px;margin:14px 0 6px}
|
||||
p,li{max-width:76ch}
|
||||
p{margin:0 0 8px}
|
||||
ol,ul{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:5px}
|
||||
.sub{color:var(--muted)}
|
||||
code{font-family:var(--mono);font-size:12.5px;background:var(--soft);padding:2px 6px;border-radius:3px;overflow-wrap:anywhere}
|
||||
.wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px}
|
||||
table{border-collapse:collapse;width:100%;min-width:780px;font-variant-numeric:tabular-nums}
|
||||
th,td{text-align:left;vertical-align:top;padding:9px 11px;border-bottom:1px solid var(--line)}
|
||||
th{background:var(--soft);font-size:12.5px;font-weight:600;letter-spacing:.02em;white-space:nowrap}
|
||||
tr:last-child td{border-bottom:0}
|
||||
.tag{display:inline-block;font-size:11.5px;line-height:1.5;padding:1px 7px;border-radius:3px;border:1px solid currentColor;white-space:nowrap}
|
||||
.t-view{color:var(--accent)} .t-time{color:var(--ok)} .t-plan{color:var(--warn)}
|
||||
.ok{color:var(--ok);font-weight:600}
|
||||
blockquote{margin:8px 0;padding:10px 14px;border-left:3px solid var(--warn);background:var(--soft);max-width:76ch}
|
||||
</style>
|
||||
<main>
|
||||
<header><h1>날씨각 데이터 흐름</h1>
|
||||
<p class="sub">기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.</p>
|
||||
</header>
|
||||
<section><h2>원칙</h2>
|
||||
<ol><li>외부 API는 <b>첫 사용자가 볼 때</b> 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.</li><li>받자마자 우리 형식으로 바꿔 <b>PostgreSQL</b>에 저장한다. 원본 응답은 저장하지 않는다.</li><li>계산(체감기온, 지수, 노을 점수)은 <b>데이터가 들어올 때 한 번</b> 하고 저장한다.</li><li><b>그날 카드는 처음부터 다 보인다.</b> 매일 03:00 스케줄러가 그날 카드(<code>post</code>)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다.</li><li><b>Redis</b>는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.</li><li>스케줄은 <b>하루 1번</b>(매일 03:00, worker)만 돈다.</li></ol>
|
||||
</section>
|
||||
<section><h2>한눈에</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>출처</th><th>언제 받나</th><th>저장 (DB)</th><th>캐시 (Redis)</th></tr><tr><td>시간별·하루 날씨</td><td>기상청 단기예보</td><td>새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때</td><td><code>weather_hourly</code> <code>weather_daily</code></td><td>피드 완성본에 포함</td></tr><tr><td>앞으로 2시간 비</td><td>기상청 초단기예보</td><td>매시 45분 이후 그 구를 처음 볼 때</td><td>저장 안 함</td><td><code>ultra:{구}</code></td></tr><tr><td>4~7일 뒤 날씨</td><td>기상청 중기예보</td><td>새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때</td><td><code>weather_daily</code> (단기예보가 8시간 미만인 날은 중기 값 유지)</td><td>—</td></tr><tr><td>층별 구름</td><td>Open-Meteo (ECMWF·GFS·JMA·ICON)</td><td>오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청</td><td><code>cloud_hourly</code> (일출·일몰 시각 값만)</td><td>—</td></tr><tr><td>미세먼지</td><td>에어코리아 실시간</td><td>매시 20분 이후 처음 볼 때, 전국 1번</td><td><code>air_quality</code></td><td>—</td></tr><tr><td>기상특보</td><td>기상청 기상특보</td><td>매시 정각 이후 처음 볼 때, 전국 1번</td><td><code>weather_warning</code></td><td>—</td></tr><tr><td>축제·행사</td><td>TourAPI (<code>lDongRegnCd</code> = 구 코드 앞 2자리)</td><td>그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌</td><td><code>event</code></td><td>—</td></tr><tr><td>해 시각</td><td>서버 계산 (API 없음)</td><td>그 구의 그날 값이 없을 때</td><td><code>sun_time</code></td><td>—</td></tr><tr><td>측정소 위치</td><td>에어코리아 측정소</td><td>처음 볼 때 + 하루 1번 스케줄</td><td><code>air_station</code></td><td>—</td></tr><tr><td>공휴일 · 24절기</td><td>천문연 특일정보</td><td>그해 값이 없을 때 처음 볼 때 1년치</td><td><code>holiday</code> <code>solar_term</code></td><td>—</td></tr><tr><td>지수·노을 점수</td><td>위 값으로 계산</td><td>재료가 새로 들어온 직후</td><td><code>index_score</code> <code>sky_score</code></td><td>피드 완성본에 포함</td></tr><tr><td>그날 피드 카드</td><td>스케줄러</td><td>매일 03:00</td><td><code>post</code></td><td>—</td></tr><tr><td>피드 완성본</td><td>위 테이블 조립</td><td>캐시가 없을 때 (시간대마다 따로)</td><td>—</td><td><code>feed:{구}:{시간대}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>저장하는 곳</h2>
|
||||
<div class="wrap"><table><tr><th>곳</th><th>담는 것</th><th>지워지면</th></tr><tr><td>PostgreSQL</td><td>받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용</td><td>볼륨에 둬서 지워지지 않음. 원본은 여기</td></tr><tr><td>Redis</td><td>피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금</td><td>문제없음. 다음 요청 때 PostgreSQL로 다시 만듦</td></tr><tr><td>시드 파일 (저장소)</td><td>구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리</td><td>git에 있음. 배포할 때 PostgreSQL로 불러옴</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>화면 요청 하나가 처리되는 순서</h2>
|
||||
<p>예: 17:20에 마포구 메인 피드를 연다.</p>
|
||||
<ol><li><b>Redis <code>feed:마포구:저녁</code> 확인.</b> (10월 17:20은 일몰 2시간 전이 지나 저녁 시간대) 있으면 그대로 돌려준다. 대부분 여기서 끝난다.</li><li><b>없으면 재료가 최신인지 확인.</b><ul><li>단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)</li><li>초단기예보: Redis <code>ultra:마포구</code>가 있나</li><li>미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)</li><li>해 시각: 없으면 계산한다</li></ul></li><li><b>오래된 것만 외부에서 받는다.</b><ul><li>여러 API는 <b>동시에</b> 부른다 (가장 느린 하나만큼만 걸림).</li><li>Redis 잠금 <code>lock:{API}:{구}</code>를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.</li><li>DB에 직전 값이 있으면 <b>그 값으로 먼저 응답</b>하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.</li></ul></li><li><b>받은 값을 우리 형식으로 바꿔 DB에 저장.</b> 체감기온·불쾌지수도 이때 계산.</li><li><b>재료가 바뀌었으면 계산.</b> 지수 24개 × 오늘·내일·모레 → <code>index_score</code>.</li><li><b>피드 완성본 조립.</b> 오늘 <code>post</code> 카드 중 켜질 조건이 맞는 것만 골라 저녁 시간대 순서로 놓고, 카드마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.</li></ol>
|
||||
<p>실패할 때:</p>
|
||||
<ul><li>외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.</li><li>잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.</li></ul>
|
||||
</section>
|
||||
<section><h2>최신인지 판단하는 법</h2>
|
||||
<div class="wrap"><table><tr><th>데이터</th><th>"최신" 기준</th></tr><tr><td>단기예보</td><td>02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>초단기예보</td><td>매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음</td></tr><tr><td>중기예보</td><td>06·18시 발표. DB의 <code>issued_at</code>이 그보다 이르면 다시 받음</td></tr><tr><td>미세먼지</td><td><code>measured_at</code>이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음</td></tr><tr><td>기상특보</td><td>마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음</td></tr><tr><td>층별 구름</td><td>오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음</td></tr><tr><td>지수 점수</td><td><code>index_score.computed_at</code>이 단기예보 <code>issued_at</code>이나 미세먼지 <code>measured_at</code>보다 이르면 다시 계산</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>Redis 캐시 키</h2>
|
||||
<div class="wrap"><table><tr><th>키</th><th>담는 것</th><th>만료</th><th>미리 지우는 경우</th></tr><tr><td><code>feed:{구 코드}:{시간대}</code></td><td>메인 피드 응답 완성본</td><td>다음 시간대 경계(05·11·21시, 일몰 2시간 전), 다음 단기예보 제공 시각, 다음 정시 20분(미세먼지) 중 가장 빠른 쪽. 최대 1시간</td><td>03:00 새 피드가 정해졌을 때 (전체)</td></tr><tr><td><code>ultra:{구 코드}</code></td><td>초단기예보 6시간</td><td>다음 정시 45분</td><td>—</td></tr><tr><td><code>rank:sunset:{날짜}</code></td><td>전국 노을 순위 (대표 30곳)</td><td>다음 날 00:00</td><td>—</td></tr><tr><td><code>lock:{API}:{구 코드}</code></td><td>동시 호출 잠금</td><td>10초</td><td>호출이 끝나면 바로 풂</td></tr></table></div>
|
||||
<p>Redis는 compose에서 볼륨 + <code>appendonly yes</code>로 띄운다. 도커를 내렸다 올려도 값이 남는다.</p>
|
||||
</section>
|
||||
<section><h2>출처 주소</h2>
|
||||
<p>모든 data.go.kr API는 최상위 <code>.env</code>의 <code>DATA_GO_KR_SERVICE_KEY</code> 하나를 쓴다 (API마다 활용신청 필요).</p>
|
||||
<div class="wrap"><table><tr><th>출처</th><th>주소</th><th>한 번에 받는 범위</th></tr><tr><td>기상청 단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst</code></td><td>구 1곳 (5km 칸 <code>nx</code>,<code>ny</code>). 오늘~모레 1시간 간격, 글피 3시간 간격</td></tr><tr><td>기상청 초단기예보</td><td><code>https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst</code></td><td>구 1곳, 6시간</td></tr><tr><td>기상청 중기예보</td><td><code>https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst</code> · <code>getMidTa</code></td><td>예보 구역 1곳</td></tr><tr><td>기상청 기상특보</td><td><code>https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd</code></td><td>전국</td></tr><tr><td>에어코리아 실시간</td><td><code>https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty</code> (<code>sidoName=전국</code>)</td><td>전국 측정소</td></tr><tr><td>에어코리아 측정소</td><td><code>https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList</code></td><td>전국 측정소</td></tr><tr><td>TourAPI 축제</td><td><code>https://apis.data.go.kr/B551011/KorService2/searchFestival2</code> (지역은 <code>lDongRegnCd</code>, <code>areaCode</code> 아님)</td><td>시도 1곳</td></tr><tr><td>천문연 특일정보</td><td><code>https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo</code></td><td>1개월</td></tr><tr><td>Open-Meteo</td><td><code>https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high</code></td><td>좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음)</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>계산 (데이터가 들어올 때 한 번)</h2>
|
||||
<div class="wrap"><table><tr><th>계산</th><th>계산하는 순간</th><th>재료</th><th>저장</th></tr><tr><td>체감기온, 불쾌지수</td><td>단기예보 저장할 때</td><td>기온·습도·바람</td><td><code>weather_hourly</code></td></tr><tr><td>지수 24개 × 오늘·내일·모레</td><td>단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회</td><td>날씨, 미세먼지, 해 시각, 지수 정의</td><td><code>index_score</code></td></tr><tr><td>노을·일출 점수, 3컷 시각</td><td>층별 구름 저장 직후</td><td>구름, 해 시각</td><td><code>sky_score</code></td></tr><tr><td>전국 노을 순위</td><td>13시 이후 순위를 처음 볼 때</td><td><code>sky_score</code></td><td>Redis <code>rank:sunset</code></td></tr><tr><td>포스트 문장</td><td>피드 완성본을 조립할 때</td><td>위 결과 + 문장 틀</td><td>Redis <code>feed:{구}</code></td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>그날 피드 (매일 03:00 스케줄러가 만듦, 안 돌았으면 첫 요청에서)</h2>
|
||||
<p>기획: <code>docs/피드기획_v2.html</code>. 스케줄러는 그날 카드를 <code>post</code>에 넣는다. 공개 시각은 없고 모든 카드는 03:00부터 다음 날 03:00까지 유효하다. 좋아요·댓글은 카드(<code>post_id</code>)에 붙으므로 순서가 바뀌어도 이어지고, 전국 사용자가 같이 본다.</p>
|
||||
<h3>시간대</h3>
|
||||
<div class="wrap"><table><tr><th>시간대</th><th>범위</th></tr><tr><td>아침</td><td>05:00–11:00</td></tr><tr><td>낮</td><td>11:00–일몰 2시간 전</td></tr><tr><td>저녁</td><td>일몰 2시간 전–21:00 (그 구 <code>sun_time</code> 기준)</td></tr><tr><td>밤</td><td>21:00–05:00</td></tr></table></div>
|
||||
<h3>카드와 켜지는 조건</h3>
|
||||
<div class="wrap"><table><tr><th>카드</th><th>켜지는 조건</th><th>볼 때 채우는 내용</th></tr><tr><td>지금 날씨 (히어로)</td><td>항상, 맨 위 고정</td><td>현재 기온·체감·불쾌지수, 오늘 날씨 점수, 앞으로 2시간 비, 오늘 1위 각(작게)</td></tr><tr><td>오늘 하루 날씨</td><td>항상, 히어로 바로 아래 고정 (특보가 있으면 특보 다음)</td><td>3시간 칸, 미세먼지. 우산은 우산·특보 카드에서</td></tr><tr><td>우산·특보</td><td>오늘 남은 시간·내일 출퇴근(8·19시) 강수확률 40% 이상, 또는 그 구 특보</td><td>비 오는 시각, 특보 종류. 특보는 히어로 바로 아래</td></tr><tr><td>각 1·2·3위</td><td>항상 (3장)</td><td>그날 하루 기준 순위. 밤에도 오늘 순위 유지</td></tr><tr><td>노을</td><td>항상. 60점 미만이면 한 줄 카드</td><td>점수·가장 예쁜 시각·명소. 일몰 뒤에는 내일 일출·노을</td></tr><tr><td>내일 미리보기</td><td>저녁·밤</td><td>내일 날씨 한 줄, 내일 1위 각, 출근길 비</td></tr><tr><td>주말 추천</td><td>목~일</td><td>그 구 토·일 날씨와 추천</td></tr><tr><td>행사</td><td>그 시도에 7일 안 행사가 있을 때</td><td>가장 가까운 행사와 그날 날씨</td></tr><tr><td>계절 소식</td><td>매일 1장 (<code>article</code>, 날마다 돌아가며)</td><td>글 첫 문단</td></tr><tr><td>날씨 상식</td><td>매일 1장 (<code>article</code>, 그날 날씨와 이어지는 글 우선)</td><td>글 첫 문단</td></tr><tr><td>한 문장·시</td><td>매일 1장</td><td>오늘 날씨에 맞는 문장. 밤에는 맨 끝 고정</td></tr></table></div>
|
||||
<h3>시간대별 순서 (히어로 제외)</h3>
|
||||
<div class="wrap"><table><tr><th>카드</th><th>아침</th><th>낮</th><th>저녁</th><th>밤</th></tr><tr><td>우산·특보</td><td>1</td><td>2</td><td>3</td><td>2</td></tr><tr><td>각 1·2·3위</td><td>2–4</td><td>1–3</td><td>2–4</td><td>5–7</td></tr><tr><td>노을</td><td>6</td><td>4</td><td>1</td><td>3</td></tr><tr><td>내일 미리보기</td><td>꺼짐</td><td>꺼짐</td><td>5</td><td>1</td></tr><tr><td>주말 추천</td><td>8</td><td>6</td><td>6 (금 2)</td><td>4</td></tr><tr><td>행사</td><td>9</td><td>5</td><td>7</td><td>8</td></tr><tr><td>계절 소식</td><td>5</td><td>7</td><td>8</td><td>6</td></tr><tr><td>날씨 상식</td><td>7</td><td>8</td><td>9</td><td>9</td></tr><tr><td>한 문장·시</td><td>10</td><td>9</td><td>10</td><td>맨 끝</td></tr></table></div>
|
||||
<ul><li>같은 시간대 안의 각 3장은 하기 좋은 시간이 가까운 각을 앞에, 시간이 지난 각을 뒤에 둔다.</li><li>같은 종류 카드는 붙이지 않는다. 각 3장 사이에는 다른 카드를 하나씩 끼운다.</li><li>꺼진 카드는 빼고 뒤 카드를 올린다. 빈 카드는 만들지 않는다 (노을 한 줄 카드만 예외).</li><li>좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.</li></ul>
|
||||
<blockquote>구현: <code>services/feed_service.py</code>의 <code>LINEUP</code>(그날 카드)·<code>ORDER</code>(시간대별 순서)·<code>arrange</code>. 한 문장·시는 <code>article</code> 의 <code>category=4</code>(코드 앞머리 <code>quote-rain-</code>·<code>quote-cloud-</code>·<code>quote-clear-</code>·<code>quote-night-</code>·<code>quote-any-</code>로 날씨에 맞춰 고름). seed 문장은 검수 전 예시다.</blockquote>
|
||||
</section>
|
||||
<section><h2>하루 1번 스케줄 (매일 03:00, worker)</h2>
|
||||
<div class="wrap"><table><tr><th>하는 일</th><th>이유</th></tr><tr><td>그날 피드 카드를 <code>post</code>에 넣고 Redis <code>feed:*</code> 비우기</td><td>하루 카드 목록</td></tr><tr><td>7일 지난 날씨·해 시각·각 점수·노을 점수, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기</td><td>테이블이 계속 커지지 않게</td></tr><tr><td>에어코리아 측정소 목록 갱신 (전국 1번)</td><td>측정소가 새로 생기거나 없어질 때 반영</td></tr></table></div>
|
||||
</section>
|
||||
<section><h2>테스트</h2>
|
||||
<p><code>pytest</code>는 개발 DB를 건드리지 않는다. 실행할 때마다 <code>nalssigak_test</code> DB를 <code>init.sql</code>로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (<code>tests/conftest.py</code>의 <code>offline</code>).</p>
|
||||
</section>
|
||||
</main>
|
||||
@@ -1,171 +0,0 @@
|
||||
# 날씨각 데이터 흐름
|
||||
|
||||
기준 화면: 시안 B 피드. 무엇을, 언제, 어디서 받아서, 어디에 저장하고, 얼마나 캐시하는지.
|
||||
|
||||
## 원칙
|
||||
|
||||
1. 외부 API는 **첫 사용자가 볼 때** 받는다. 캐시가 오래됐을 때만 부르고, 나머지 사용자는 그 값을 같이 쓴다.
|
||||
2. 받자마자 우리 형식으로 바꿔 **PostgreSQL**에 저장한다. 원본 응답은 저장하지 않는다.
|
||||
3. 계산(체감기온, 지수, 노을 점수)은 **데이터가 들어올 때 한 번** 하고 저장한다.
|
||||
4. **그날 카드는 처음부터 다 보인다.** 매일 03:00 스케줄러가 그날 카드(`post`)를 만들고, 카드 안의 숫자·문장은 볼 때 그 구 데이터로 채운다. 시각별로 카드를 하나씩 공개하지 않는다. 순서는 시간대(아침·낮·저녁·밤)에 따라 바뀌고, 조건이 맞는 카드만 켜진다.
|
||||
5. **Redis**는 지워져도 되는 것만 담는다. 비면 PostgreSQL로 다시 만든다.
|
||||
6. 스케줄은 **하루 1번**(매일 03:00, worker)만 돈다.
|
||||
|
||||
## 한눈에
|
||||
|
||||
| 데이터 | 출처 | 언제 받나 | 저장 (DB) | 캐시 (Redis) |
|
||||
|---|---|---|---|---|
|
||||
| 시간별·하루 날씨 | 기상청 단기예보 | 새 발표(02·05·08·11·14·17·20·23시 +10분) 후 그 구를 처음 볼 때 | `weather_hourly` `weather_daily` | 피드 완성본에 포함 |
|
||||
| 앞으로 2시간 비 | 기상청 초단기예보 | 매시 45분 이후 그 구를 처음 볼 때 | 저장 안 함 | `ultra:{구}` |
|
||||
| 4~7일 뒤 날씨 | 기상청 중기예보 | 새 발표(06·18시 +30분) 후 주말 탭·행사를 처음 볼 때 | `weather_daily` (단기예보가 8시간 미만인 날은 중기 값 유지) | — |
|
||||
| 층별 구름 | Open-Meteo (ECMWF·GFS·JMA·ICON) | 오전·13시(노을)·21시(일출) 시간대마다 처음 볼 때. 좌표 24개씩 나눠 동시에 요청 | `cloud_hourly` (일출·일몰 시각 값만) | — |
|
||||
| 미세먼지 | 에어코리아 실시간 | 매시 20분 이후 처음 볼 때, 전국 1번 | `air_quality` | — |
|
||||
| 기상특보 | 기상청 기상특보 | 매시 정각 이후 처음 볼 때, 전국 1번 | `weather_warning` | — |
|
||||
| 축제·행사 | TourAPI (`lDongRegnCd` = 구 코드 앞 2자리) | 그 시도를 그날 처음 볼 때. 60일 넘게 이어지는 상설 행사는 목록에서 뺌 | `event` | — |
|
||||
| 해 시각 | 서버 계산 (API 없음) | 그 구의 그날 값이 없을 때 | `sun_time` | — |
|
||||
| 측정소 위치 | 에어코리아 측정소 | 처음 볼 때 + 하루 1번 스케줄 | `air_station` | — |
|
||||
| 공휴일 · 24절기 | 천문연 특일정보 | 그해 값이 없을 때 처음 볼 때 1년치 | `holiday` `solar_term` | — |
|
||||
| 지수·노을 점수 | 위 값으로 계산 | 재료가 새로 들어온 직후 | `index_score` `sky_score` | 피드 완성본에 포함 |
|
||||
| 그날 피드 카드 | 스케줄러 | 매일 03:00 | `post` | — |
|
||||
| 피드 완성본 | 위 테이블 조립 | 캐시가 없을 때 (시간대마다 따로) | — | `feed:{구}:{시간대}` |
|
||||
|
||||
## 저장하는 곳
|
||||
|
||||
| 곳 | 담는 것 | 지워지면 |
|
||||
|---|---|---|
|
||||
| PostgreSQL | 받아 온 값(우리 형식), 계산 결과, 포스트, 사람이 쓴 내용 | 볼륨에 둬서 지워지지 않음. 원본은 여기 |
|
||||
| Redis | 피드 완성본, 초단기예보, 전국 노을 순위, 동시 호출 잠금 | 문제없음. 다음 요청 때 PostgreSQL로 다시 만듦 |
|
||||
| 시드 파일 (저장소) | 구 목록, 지수 정의·문장 틀, 명소, 절기, 계절 책, 읽을거리 | git에 있음. 배포할 때 PostgreSQL로 불러옴 |
|
||||
|
||||
## 화면 요청 하나가 처리되는 순서
|
||||
|
||||
예: 17:20에 마포구 메인 피드를 연다.
|
||||
|
||||
1. **Redis `feed:마포구:저녁` 확인.** (10월 17:20은 일몰 2시간 전이 지나 저녁 시간대) 있으면 그대로 돌려준다. 대부분 여기서 끝난다.
|
||||
2. **없으면 재료가 최신인지 확인.**
|
||||
- 단기예보: DB에 17시 발표가 있나 (17:10부터 받을 수 있음)
|
||||
- 초단기예보: Redis `ultra:마포구`가 있나
|
||||
- 미세먼지·특보: 이번 시각 갱신분이 DB에 있나 (전국 공용이라 한 사람이 받으면 모두 같이 씀)
|
||||
- 해 시각: 없으면 계산한다
|
||||
3. **오래된 것만 외부에서 받는다.**
|
||||
- 여러 API는 **동시에** 부른다 (가장 느린 하나만큼만 걸림).
|
||||
- Redis 잠금 `lock:{API}:{구}`를 잡아, 같은 구를 여러 명이 동시에 열어도 호출은 1번.
|
||||
- DB에 직전 값이 있으면 **그 값으로 먼저 응답**하고, 새 값은 받는 대로 저장해 다음 요청부터 반영한다.
|
||||
4. **받은 값을 우리 형식으로 바꿔 DB에 저장.** 체감기온·불쾌지수도 이때 계산.
|
||||
5. **재료가 바뀌었으면 계산.** 지수 24개 × 오늘·내일·모레 → `index_score`.
|
||||
6. **피드 완성본 조립.** 오늘 `post` 카드 중 켜질 조건이 맞는 것만 골라 저녁 시간대 순서로 놓고, 카드마다 그 구 데이터로 제목·캡션·슬라이드·보내기 문구를 만든다. Redis에 넣고 돌려준다.
|
||||
|
||||
실패할 때:
|
||||
- 외부 호출이 실패하면 DB의 직전 값으로 응답하고 로그를 남긴다. 완성본은 5분만 캐시해서 5분 뒤 다시 시도.
|
||||
- 잠금을 못 잡으면(다른 요청이 받는 중) 최대 3초 기다렸다가 DB에서 읽는다.
|
||||
|
||||
## 최신인지 판단하는 법
|
||||
|
||||
| 데이터 | "최신" 기준 |
|
||||
|---|---|
|
||||
| 단기예보 | 02·05·08·11·14·17·20·23시 중 "발표 + 10분"이 지난 마지막 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 초단기예보 | 매시 30분 발표, 45분부터 제공. Redis에 없으면 다시 받음 |
|
||||
| 중기예보 | 06·18시 발표. DB의 `issued_at`이 그보다 이르면 다시 받음 |
|
||||
| 미세먼지 | `measured_at`이 이번 시각(매시 20분 기준)보다 이르면 전국을 다시 받음 |
|
||||
| 기상특보 | 마지막으로 받은 시각이 이번 정시보다 이르면 다시 받음 |
|
||||
| 층별 구름 | 오늘 13시(노을)·21시(일출) 이후에 받은 값이 없으면 다시 받음 |
|
||||
| 지수 점수 | `index_score.computed_at`이 단기예보 `issued_at`이나 미세먼지 `measured_at`보다 이르면 다시 계산 |
|
||||
|
||||
## Redis 캐시 키
|
||||
|
||||
| 키 | 담는 것 | 만료 | 미리 지우는 경우 |
|
||||
|---|---|---|---|
|
||||
| `feed:{구 코드}:{시간대}` | 메인 피드 응답 완성본 | 다음 시간대 경계(05·11·21시, 일몰 2시간 전), 다음 단기예보 제공 시각, 다음 정시 20분(미세먼지) 중 가장 빠른 쪽. 최대 1시간 | 03:00 새 피드가 정해졌을 때 (전체) |
|
||||
| `ultra:{구 코드}` | 초단기예보 6시간 | 다음 정시 45분 | — |
|
||||
| `rank:sunset:{날짜}` | 전국 노을 순위 (대표 30곳) | 다음 날 00:00 | — |
|
||||
| `lock:{API}:{구 코드}` | 동시 호출 잠금 | 10초 | 호출이 끝나면 바로 풂 |
|
||||
|
||||
Redis는 compose에서 볼륨 + `appendonly yes`로 띄운다. 도커를 내렸다 올려도 값이 남는다.
|
||||
|
||||
## 출처 주소
|
||||
|
||||
모든 data.go.kr API는 최상위 `.env`의 `DATA_GO_KR_SERVICE_KEY` 하나를 쓴다 (API마다 활용신청 필요).
|
||||
|
||||
| 출처 | 주소 | 한 번에 받는 범위 |
|
||||
|---|---|---|
|
||||
| 기상청 단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst` | 구 1곳 (5km 칸 `nx`,`ny`). 오늘~모레 1시간 간격, 글피 3시간 간격 |
|
||||
| 기상청 초단기예보 | `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst` | 구 1곳, 6시간 |
|
||||
| 기상청 중기예보 | `https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst` · `getMidTa` | 예보 구역 1곳 |
|
||||
| 기상청 기상특보 | `https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd` | 전국 |
|
||||
| 에어코리아 실시간 | `https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty` (`sidoName=전국`) | 전국 측정소 |
|
||||
| 에어코리아 측정소 | `https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList` | 전국 측정소 |
|
||||
| TourAPI 축제 | `https://apis.data.go.kr/B551011/KorService2/searchFestival2` (지역은 `lDongRegnCd`, `areaCode` 아님) | 시도 1곳 |
|
||||
| 천문연 특일정보 | `https://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo` | 1개월 |
|
||||
| Open-Meteo | `https://api.open-meteo.com/v1/forecast?hourly=cloud_cover_low,cloud_cover_mid,cloud_cover_high` | 좌표 여러 개, 3일. ECMWF·GFS·JMA·ICON 모델 사용 (KMA 모델은 값이 비어 있음) |
|
||||
|
||||
## 계산 (데이터가 들어올 때 한 번)
|
||||
|
||||
| 계산 | 계산하는 순간 | 재료 | 저장 |
|
||||
|---|---|---|---|
|
||||
| 체감기온, 불쾌지수 | 단기예보 저장할 때 | 기온·습도·바람 | `weather_hourly` |
|
||||
| 지수 24개 × 오늘·내일·모레 | 단기예보 저장 직후 / 미세먼지 갱신 뒤 첫 조회 | 날씨, 미세먼지, 해 시각, 지수 정의 | `index_score` |
|
||||
| 노을·일출 점수, 3컷 시각 | 층별 구름 저장 직후 | 구름, 해 시각 | `sky_score` |
|
||||
| 전국 노을 순위 | 13시 이후 순위를 처음 볼 때 | `sky_score` | Redis `rank:sunset` |
|
||||
| 포스트 문장 | 피드 완성본을 조립할 때 | 위 결과 + 문장 틀 | Redis `feed:{구}` |
|
||||
|
||||
## 그날 피드 (매일 03:00 스케줄러가 만듦, 안 돌았으면 첫 요청에서)
|
||||
|
||||
기획: `docs/피드기획_v2.html`. 스케줄러는 그날 카드를 `post`에 넣는다. 공개 시각은 없고 모든 카드는 03:00부터 다음 날 03:00까지 유효하다. 좋아요·댓글은 카드(`post_id`)에 붙으므로 순서가 바뀌어도 이어지고, 전국 사용자가 같이 본다.
|
||||
|
||||
### 시간대
|
||||
|
||||
| 시간대 | 범위 |
|
||||
|---|---|
|
||||
| 아침 | 05:00–11:00 |
|
||||
| 낮 | 11:00–일몰 2시간 전 |
|
||||
| 저녁 | 일몰 2시간 전–21:00 (그 구 `sun_time` 기준) |
|
||||
| 밤 | 21:00–05:00 |
|
||||
|
||||
### 카드와 켜지는 조건
|
||||
|
||||
| 카드 | 켜지는 조건 | 볼 때 채우는 내용 |
|
||||
|---|---|---|
|
||||
| 지금 날씨 (히어로) | 항상, 맨 위 고정 | 현재 기온·체감·불쾌지수, 오늘 날씨 점수, 앞으로 2시간 비, 오늘 1위 각(작게) |
|
||||
| 오늘 하루 날씨 | 항상, 히어로 바로 아래 고정 (특보가 있으면 특보 다음) | 3시간 칸, 미세먼지. 우산은 우산·특보 카드에서 |
|
||||
| 우산·특보 | 오늘 남은 시간·내일 출퇴근(8·19시) 강수확률 40% 이상, 또는 그 구 특보 | 비 오는 시각, 특보 종류. 특보는 히어로 바로 아래 |
|
||||
| 각 1·2·3위 | 항상 (3장) | 그날 하루 기준 순위. 밤에도 오늘 순위 유지 |
|
||||
| 노을 | 항상. 60점 미만이면 한 줄 카드 | 점수·가장 예쁜 시각·명소. 일몰 뒤에는 내일 일출·노을 |
|
||||
| 내일 미리보기 | 저녁·밤 | 내일 날씨 한 줄, 내일 1위 각, 출근길 비 |
|
||||
| 주말 추천 | 목~일 | 그 구 토·일 날씨와 추천 |
|
||||
| 행사 | 그 시도에 7일 안 행사가 있을 때 | 가장 가까운 행사와 그날 날씨 |
|
||||
| 계절 소식 | 매일 1장 (`article`, 날마다 돌아가며) | 글 첫 문단 |
|
||||
| 날씨 상식 | 매일 1장 (`article`, 그날 날씨와 이어지는 글 우선) | 글 첫 문단 |
|
||||
| 한 문장·시 | 매일 1장 | 오늘 날씨에 맞는 문장. 밤에는 맨 끝 고정 |
|
||||
|
||||
### 시간대별 순서 (히어로 제외)
|
||||
|
||||
| 카드 | 아침 | 낮 | 저녁 | 밤 |
|
||||
|---|---|---|---|---|
|
||||
| 우산·특보 | 1 | 2 | 3 | 2 |
|
||||
| 각 1·2·3위 | 2–4 | 1–3 | 2–4 | 5–7 |
|
||||
| 노을 | 6 | 4 | 1 | 3 |
|
||||
| 내일 미리보기 | 꺼짐 | 꺼짐 | 5 | 1 |
|
||||
| 주말 추천 | 8 | 6 | 6 (금 2) | 4 |
|
||||
| 행사 | 9 | 5 | 7 | 8 |
|
||||
| 계절 소식 | 5 | 7 | 8 | 6 |
|
||||
| 날씨 상식 | 7 | 8 | 9 | 9 |
|
||||
| 한 문장·시 | 10 | 9 | 10 | 맨 끝 |
|
||||
|
||||
- 같은 시간대 안의 각 3장은 하기 좋은 시간이 가까운 각을 앞에, 시간이 지난 각을 뒤에 둔다.
|
||||
- 같은 종류 카드는 붙이지 않는다. 각 3장 사이에는 다른 카드를 하나씩 끼운다.
|
||||
- 꺼진 카드는 빼고 뒤 카드를 올린다. 빈 카드는 만들지 않는다 (노을 한 줄 카드만 예외).
|
||||
- 좋아요·댓글 수와 내가 누른 표시는 캐시와 상관없이 매번 DB에서 덮어쓴다.
|
||||
|
||||
> 구현: `services/feed_service.py`의 `LINEUP`(그날 카드)·`ORDER`(시간대별 순서)·`arrange`. 한 문장·시는 `article` 의 `category=4`(코드 앞머리 `quote-rain-`·`quote-cloud-`·`quote-clear-`·`quote-night-`·`quote-any-`로 날씨에 맞춰 고름). seed 문장은 검수 전 예시다.
|
||||
|
||||
## 하루 1번 스케줄 (매일 03:00, worker)
|
||||
|
||||
| 하는 일 | 이유 |
|
||||
|---|---|
|
||||
| 그날 피드 카드를 `post`에 넣고 Redis `feed:*` 비우기 | 하루 카드 목록 |
|
||||
| 7일 지난 날씨·해 시각·각 점수·노을 점수, 2일 지난 구름, 끝난 지 30일 지난 행사 지우기 | 테이블이 계속 커지지 않게 |
|
||||
| 에어코리아 측정소 목록 갱신 (전국 1번) | 측정소가 새로 생기거나 없어질 때 반영 |
|
||||
|
||||
## 테스트
|
||||
|
||||
`pytest`는 개발 DB를 건드리지 않는다. 실행할 때마다 `nalssigak_test` DB를 `init.sql`로 새로 만들고 시드를 넣으며, Redis는 15번을 쓴다. 테스트마다 외부에서 받은 데이터와 Redis를 비운다. 외부 API는 가짜 값으로 바꾼다 (`tests/conftest.py`의 `offline`).
|
||||
@@ -1,6 +1,6 @@
|
||||
# 날씨각 호출량·DB 크기 추정
|
||||
|
||||
2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `data-pipeline.md` 참고.
|
||||
2026-10-02 기준 코드와 개발 DB 실측으로 계산했다. 동작 방식은 `../../docs/데이터_흐름.html` 참고.
|
||||
|
||||
## 핵심
|
||||
|
||||
|
||||
@@ -100,6 +100,9 @@ CREATE TABLE IF NOT EXISTS public.sky_score (
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, sky_type)
|
||||
);
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS situation SMALLINT NULL; -- SkySituation: 1=가려짐 2=낮은 구름 3=물들 구름 적음 4=넓게 물듦 5=두꺼움
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_total SMALLINT NULL; -- 계산에 쓴 예보 모델 수
|
||||
ALTER TABLE public.sky_score ADD COLUMN IF NOT EXISTS models_agree SMALLINT NULL; -- 그중 같은 하늘 상황을 낸 모델 수
|
||||
|
||||
-- 구별 지수 점수. 오늘·내일·모레와 이번 주말을 날짜별 줄로 둔다 (각 상세 창 칸: 오늘·내일·토·일).
|
||||
CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
@@ -287,11 +290,13 @@ CREATE TABLE IF NOT EXISTS public.event (
|
||||
source_url VARCHAR(500) NULL,
|
||||
image_url VARCHAR(500) NULL, -- TourAPI firstimage
|
||||
lat NUMERIC(8,5) NULL, -- TourAPI mapy (가까운 행사 고르기)
|
||||
lon NUMERIC(8,5) NULL -- TourAPI mapx
|
||||
lon NUMERIC(8,5) NULL, -- TourAPI mapx
|
||||
kind SMALLINT NOT NULL DEFAULT 1 -- EventKind: 1=축제 2=전시 3=콘서트 4=팝업
|
||||
);
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1;
|
||||
|
||||
-- 공휴일 (주말·행사 탭의 "개천절").
|
||||
CREATE TABLE IF NOT EXISTS public.holiday (
|
||||
|
||||
@@ -3,13 +3,14 @@ from typing import Annotated, Literal, Optional, Union
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import PostType, SlotTone
|
||||
from common.enums import PostType, SkySituation, SlotTone
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class Row(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
||||
|
||||
|
||||
class HourCell(WebPacketProtocol):
|
||||
@@ -62,6 +63,7 @@ class SunsetSlide(WebPacketProtocol):
|
||||
score: int
|
||||
grade_label: str
|
||||
cuts: list[Cut]
|
||||
situation: Optional[SkySituation] = Field(default=None, description="하늘 상황. 앱이 카드 하늘 색을 고른다")
|
||||
|
||||
|
||||
class WeekDay(WebPacketProtocol):
|
||||
@@ -143,6 +145,8 @@ class Hero(WebPacketProtocol):
|
||||
weather_score: Optional[int] = None
|
||||
top1: Optional[TopIndex] = None
|
||||
bubble: Optional[str] = None
|
||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100")
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from common.models.errors import error_info
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -53,4 +53,12 @@ async def get_index(index_id: int = Path(...), region: str = Query(..., descript
|
||||
if getattr(d, f"weight_{a}")
|
||||
],
|
||||
zero_rules=zero_rules_text(d.zero_rules), zero_reason=s.zero_reason, limit=d.limit_description,
|
||||
bands=_bands(d.sentences or {}, s.score),
|
||||
)
|
||||
|
||||
|
||||
def _bands(sentences: dict, score: int) -> list[ScoreBand]:
|
||||
"""seed 의 sentences {"0": ..., "30": ..., "60": ..., "80": ...} 를 구간으로. 키는 구간 시작 점수."""
|
||||
lows = sorted(int(k) for k in sentences)
|
||||
highs = [lo - 1 for lo in lows[1:]] + [100]
|
||||
return [ScoreBand(low=lo, high=hi, text=sentences[str(lo)], current=lo <= score <= hi) for lo, hi in zip(lows, highs)]
|
||||
@@ -44,6 +44,13 @@ class Factor(WebPacketProtocol):
|
||||
note: str
|
||||
|
||||
|
||||
class ScoreBand(WebPacketProtocol):
|
||||
low: int
|
||||
high: int
|
||||
text: str = Field(description="이 점수 구간이면 어떤 날인지, 통통 튀는 말투 한 문장")
|
||||
current: bool = Field(description="오늘 점수가 이 구간에 있음")
|
||||
|
||||
|
||||
class Res_IndexDetail(Res_WebPacketProtocol):
|
||||
index: Optional[IndexSummary] = None
|
||||
description: Optional[str] = None
|
||||
@@ -51,3 +58,4 @@ class Res_IndexDetail(Res_WebPacketProtocol):
|
||||
zero_rules: Optional[str] = None
|
||||
zero_reason: Optional[str] = None
|
||||
limit: Optional[str] = None
|
||||
bands: list[ScoreBand] = Field(default=[], description="점수 구간별 설명 (0~29, 30~59, 60~79, 80~100)")
|
||||
@@ -1,7 +1,9 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkySituation, SkyType
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -19,6 +21,9 @@ class SkyScoreData(WebPacketProtocol):
|
||||
grade_label: str
|
||||
confidence: Confidence
|
||||
best_times: list[BestTime] = []
|
||||
situation: Optional[SkySituation] = None
|
||||
situation_label: Optional[str] = Field(default=None, description="하늘 상황 한 줄: 구름에 가려요 / 구름이 적어 짧게 끝나요 / 하늘이 넓게 물들 수 있어요 등")
|
||||
verdict: Optional[Literal["go", "maybe", "rest"]] = None
|
||||
|
||||
|
||||
class SpotData(WebPacketProtocol):
|
||||
@@ -28,6 +33,7 @@ class SpotData(WebPacketProtocol):
|
||||
lat: float
|
||||
lon: float
|
||||
distance_km: float
|
||||
direction: str = Field(default="", description="내 구에서 본 방향 (16방위, 예: 북서)")
|
||||
|
||||
|
||||
class PlanSpot(WebPacketProtocol):
|
||||
@@ -43,6 +49,9 @@ class SkyPlanData(WebPacketProtocol):
|
||||
reason: str
|
||||
score: int
|
||||
grade_label: str
|
||||
situation_label: Optional[str] = None
|
||||
models_total: Optional[int] = Field(default=None, description="계산에 쓴 예보 모델 수")
|
||||
models_agree: Optional[int] = Field(default=None, description="그중 같은 하늘 상황을 낸 모델 수")
|
||||
best_at: Optional[datetime] = None
|
||||
spot: Optional[PlanSpot] = None
|
||||
timeline: list[BestTime] = []
|
||||
@@ -66,8 +75,10 @@ class RankData(WebPacketProtocol):
|
||||
note: Optional[str] = None
|
||||
score: int
|
||||
grade: SkyGrade
|
||||
situation_label: Optional[str] = None
|
||||
|
||||
|
||||
class Res_SkyRanking(Res_WebPacketProtocol):
|
||||
day: Optional[date] = None
|
||||
summary: Optional[str] = Field(default=None, description="대부분 같은 하늘 상황인 날 한 줄 (예: 오늘은 전국이 맑아 대부분 짧게 끝나요)")
|
||||
items: list[RankData] = []
|
||||
@@ -1,12 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkyType
|
||||
from common.enums import Confidence, ErrorType, SkyGrade, SkySituation, SkyType
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import now_kst
|
||||
from common.utils.text import compass
|
||||
from router.v1.sky.protocol import BestTime, PlanSpot, RankData, Res_Sky, Res_SkyRanking, SkyPlanData, SkyScoreData, SpotData
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.sky_service import SkyPlan, SkyService
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.sky_service import SkyPlan, SkyService, day_verdict, ranking_summary
|
||||
|
||||
router = APIRouter(prefix="/v1/sky", tags=["sky"])
|
||||
|
||||
@@ -15,12 +16,18 @@ def _score(x: SkyScore) -> SkyScoreData:
|
||||
return SkyScoreData(
|
||||
day=x.score_date, sky_type=SkyType(x.sky_type), score=x.score, grade=g, grade_label=GRADE_LABEL[g],
|
||||
confidence=Confidence(x.confidence), best_times=[BestTime(**b) for b in x.best_times],
|
||||
situation=SkySituation(x.situation) if x.situation else None, situation_label=_situation(x), verdict=day_verdict(x),
|
||||
)
|
||||
|
||||
|
||||
def _situation(x: SkyScore) -> str | None:
|
||||
return SITUATION_LINE[SkySituation(x.situation)] if x.situation else None
|
||||
|
||||
|
||||
def _plan(p: SkyPlan) -> SkyPlanData:
|
||||
return SkyPlanData(
|
||||
day=p.day, when=p.when, verdict=p.verdict, headline=p.headline, reason=p.reason, score=p.score, grade_label=p.grade_label,
|
||||
situation_label=p.situation_label, models_total=p.models_total, models_agree=p.models_agree,
|
||||
best_at=p.best_at, spot=PlanSpot(name=p.spot.spot.name, distance_km=p.spot.distance_km) if p.spot else None,
|
||||
timeline=[BestTime(**b) for b in p.timeline], outlook=p.outlook,
|
||||
)
|
||||
@@ -36,7 +43,8 @@ async def get_sky(region: str = Query(..., description="구 행정코드"), serv
|
||||
sunset=_score(view.sunset) if view.sunset else None, sunrise=_score(view.sunrise) if view.sunrise else None,
|
||||
days=[_score(x) for x in view.days],
|
||||
spots=[
|
||||
SpotData(no=i + 1, name=s.spot.name, description=s.spot.description, lat=float(s.spot.lat), lon=float(s.spot.lon), distance_km=s.distance_km)
|
||||
SpotData(no=i + 1, name=s.spot.name, description=s.spot.description, lat=float(s.spot.lat), lon=float(s.spot.lon), distance_km=s.distance_km,
|
||||
direction=compass(s.direction))
|
||||
for i, s in enumerate(view.spots)
|
||||
],
|
||||
plan=_plan(view.plan) if view.plan else None,
|
||||
@@ -49,9 +57,10 @@ async def get_sky_ranking(service: SkyService = Depends()) -> Res_SkyRanking:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_SkyRanking(result=error_info(err))
|
||||
return Res_SkyRanking(
|
||||
day=now_kst().date(),
|
||||
day=now_kst().date(), summary=ranking_summary(items),
|
||||
items=[
|
||||
RankData(rank=i.rank, region_code=i.region.code, name=i.region.name, note=i.region.ranking_note, score=i.score.score, grade=SkyGrade(i.score.grade))
|
||||
RankData(rank=i.rank, region_code=i.region.code, name=i.region.name, note=i.region.ranking_note, score=i.score.score, grade=SkyGrade(i.score.grade),
|
||||
situation_label=_situation(i.score))
|
||||
for i in items
|
||||
],
|
||||
)
|
||||
@@ -1,6 +1,10 @@
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
@@ -8,11 +12,22 @@ from common.utils.kma_time import now_kst
|
||||
from crud.air_crud import AirCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.external.airkorea import fetch_stations, parse_stations
|
||||
from services.external import popga, teams_webhook
|
||||
from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.week_service import collect_events
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
||||
_POPGA_BATCH = 100
|
||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||
_EVENTS_TTL_SEC = 7 * 86400
|
||||
_SIDO_GAP_SEC = 1.0
|
||||
_KIND_KO = {"festival": "축제", "exhibition": "전시", "concert": "콘서트"}
|
||||
|
||||
_CLEANUP_SQL = [
|
||||
"DELETE FROM public.weather_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
"DELETE FROM public.weather_daily WHERE forecast_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
@@ -55,3 +70,88 @@ async def build_today_feed() -> ErrorType:
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
|
||||
if err is ErrorType.SUCCESS and seen:
|
||||
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_popups() -> ErrorType:
|
||||
"""팝가 팝업스토어 중 이번 달 1일 이후에 끝나는 것을 event 에 넣는다. 첫 실행은 전부, 그 뒤로는 바뀐 페이지만 읽는다."""
|
||||
since = now_kst().date().replace(day=1)
|
||||
saved = 0
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20, headers={"User-Agent": "nalssigak-bot"}) as client:
|
||||
index = await popga.fetch_popup_index(client)
|
||||
known = await REDIS.conn.hgetall(_POPGA_SEEN)
|
||||
todo = sorted((i for i, mod in index.items() if known.get(str(i)) != mod), reverse=True)
|
||||
LOG.info(f"[scheduler] refresh_popups: {len(todo)}/{len(index)} pages to read")
|
||||
rows: list[dict] = []
|
||||
seen: dict[str, str] = {}
|
||||
for n, popup_id in enumerate(todo, 1):
|
||||
await asyncio.sleep(popga.REQUEST_GAP_SEC)
|
||||
try:
|
||||
page = await popga.fetch_popup_page(client, popup_id)
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[scheduler] refresh_popups {popup_id}: {type(e).__name__}")
|
||||
continue
|
||||
row = popga.parse_popup(page, popup_id, since)
|
||||
if row:
|
||||
rows.append(row)
|
||||
seen[str(popup_id)] = index[popup_id]
|
||||
if n % _POPGA_BATCH == 0 or n == len(todo):
|
||||
if await _save_popups(rows, seen) is not ErrorType.SUCCESS:
|
||||
return ErrorType.DB_ERROR
|
||||
saved += len(rows)
|
||||
rows, seen = [], {}
|
||||
except (httpx.HTTPError, RedisError) as e:
|
||||
LOG.error(f"[scheduler] refresh_popups: {type(e).__name__} {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR
|
||||
LOG.info(f"[scheduler] refresh_popups saved {saved}")
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
|
||||
async def _popup_count() -> int:
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q))
|
||||
return n if err is ErrorType.SUCCESS and n is not None else 0
|
||||
|
||||
|
||||
async def refresh_events(only_if_missing: bool = False) -> ErrorType:
|
||||
"""전국 축제·전시·콘서트·팝업을 받고 Teams 로 알린다. only_if_missing 이면 7일 안에 마친 기록이 있을 때 건너뛴다."""
|
||||
try:
|
||||
if only_if_missing and await REDIS.conn.exists(EVENTS_DONE):
|
||||
return ErrorType.SUCCESS
|
||||
except RedisError as e:
|
||||
LOG.error(f"[scheduler] refresh_events done check: {e}")
|
||||
today = now_kst().date()
|
||||
totals = dict.fromkeys(_KIND_KO, 0)
|
||||
failed: list[str] = []
|
||||
for sido, name in SIDO_NAME.items():
|
||||
err, counts = await collect_events(sido, today)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
failed.append(name)
|
||||
for k, n in counts.items():
|
||||
totals[k] += n
|
||||
await asyncio.sleep(_SIDO_GAP_SEC)
|
||||
popup_err = await refresh_popups()
|
||||
popups = await _popup_count()
|
||||
|
||||
ok = not failed and popup_err is ErrorType.SUCCESS
|
||||
lines = [f"{_KIND_KO[k]} {n}" for k, n in totals.items()] + [f"팝업 {popups}"]
|
||||
detail = f"{today:%Y-%m-%d} · {', '.join(lines)} (진행 중·예정)"
|
||||
if failed:
|
||||
detail += f"\n실패한 시도: {', '.join(failed)}"
|
||||
if popup_err is not ErrorType.SUCCESS:
|
||||
detail += f"\n팝업 수집 실패: {popup_err.name}"
|
||||
await teams_webhook.send("행사 수집 완료" if ok else "행사 수집 일부 실패", detail)
|
||||
if ok:
|
||||
try:
|
||||
await REDIS.conn.set(EVENTS_DONE, today.isoformat(), ex=_EVENTS_TTL_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[scheduler] refresh_events done mark: {e}")
|
||||
LOG.info(f"[scheduler] refresh_events: {detail}")
|
||||
return ErrorType.SUCCESS if ok else ErrorType.EXTERNAL_API_ERROR
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_데이터.md")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
@@ -111,7 +111,10 @@ def main() -> None:
|
||||
if x.get("limit_description"):
|
||||
P(f"- 반영 못 하는 것: {x['limit_description']}")
|
||||
if x.get("sentences"):
|
||||
P(f"- 문장: {json.dumps(x['sentences'], ensure_ascii=False)}")
|
||||
lows = sorted(int(k) for k in x["sentences"])
|
||||
P("- 점수 구간별 설명 (상세 창에 나옴):")
|
||||
for lo, hi in zip(lows, [v - 1 for v in lows[1:]] + [100]):
|
||||
P(f" - {lo}~{hi}점: {x['sentences'][str(lo)]}")
|
||||
P("")
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out) + "\n")
|
||||
|
||||
@@ -61,7 +61,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 오거나 바람이 쌩쌩, 오늘 야장은 접어요. 실내 포차로 피신!",
|
||||
"30": "앉을 순 있는데 춥거나 덥거나 눅눅해요. 겉옷이나 부채 필수!",
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
},
|
||||
{
|
||||
@@ -121,7 +126,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "잔디 상태, 공원 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 돗자리는 집에 고이 두기!",
|
||||
"30": "햇볕이 뜨겁거나 바람이 쌀쌀해요. 그늘이나 담요 챙기면 버틸 만!",
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
},
|
||||
{
|
||||
@@ -185,7 +195,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "야구 경기 같은 이벤트는 아직 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 10° 아래거나 비가 와요. 치킨은 배달, 맥주는 집에서!",
|
||||
"30": "바깥은 좀 쌀쌀하거나 후덥지근해요. 가게 안쪽 자리 추천!",
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
},
|
||||
{
|
||||
@@ -247,7 +262,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "길 공사, 조명은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 쏟아지거나 초미세먼지가 매우 나빠요. 오늘은 실내 걷기로!",
|
||||
"30": "걸을 순 있는데 춥거나 덥거나 공기가 탁해요. 짧게 한 바퀴만!",
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
},
|
||||
{
|
||||
@@ -314,7 +334,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 방향과 주변 공사 먼지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "초미세먼지가 매우 나빠요. 창문 꼭 닫고 공기청정기 ON!",
|
||||
"30": "공기가 탁하거나 비가 와요. 5분만 짧게 열고 닫기!",
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
},
|
||||
{
|
||||
@@ -380,7 +405,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "등산로 통제, 낙석 정보는 산림청 안내를 확인하세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이나 강풍 특보가 있어요. 오늘 산은 쉬어요!",
|
||||
"30": "산 위는 꽤 춥거나 더워요(6° 낮게 쳐요). 옷차림 단단히!",
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
},
|
||||
{
|
||||
@@ -436,7 +466,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "황사·꽃가루 같은 하늘 먼지는 일부만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "곧 비가 와요. 지금 세차하면 물 낭비!",
|
||||
"30": "비 기운이 남아 있어요. 하루쯤 미루는 게 이득!",
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
},
|
||||
{
|
||||
@@ -497,7 +532,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "캠핑장 예약 상황은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 너무 세요. 텐트 날아가요!",
|
||||
"30": "밤에 춥거나 습해요. 침낭은 두꺼운 걸로!",
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
},
|
||||
{
|
||||
@@ -560,7 +600,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 상태는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!",
|
||||
"30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!",
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
},
|
||||
{
|
||||
@@ -613,7 +658,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "도시 불빛은 지역 평균으로만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "구름이 하늘을 꽉 덮었어요. 별은 다음 기회에!",
|
||||
"30": "달이 밝거나 하늘이 뿌예서 큰 별 몇 개만 보여요.",
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
},
|
||||
{
|
||||
@@ -663,7 +713,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "25° 넘게 더워요. 국물보다 냉면이 당길 날!",
|
||||
"30": "국물이 살짝 생각나는 정도예요.",
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
},
|
||||
{
|
||||
@@ -711,7 +766,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 판매량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 없어요. 파전은 비 오는 날을 기다려요!",
|
||||
"30": "하늘이 꾸물꾸물, 막걸리 생각이 살짝 나요.",
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
},
|
||||
{
|
||||
@@ -757,7 +817,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침부터 22° 넘어요. 아직은 아아의 계절!",
|
||||
"30": "아침이 살짝 선선해요. 아아 들다 손 시릴 수도?",
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
},
|
||||
{
|
||||
@@ -809,7 +874,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 일조량은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 오늘 빨래는 실내 건조로!",
|
||||
"30": "눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.",
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
},
|
||||
{
|
||||
@@ -874,7 +944,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "자전거 도로 공사는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요!",
|
||||
"30": "맞바람이 세거나 기온이 애매해요. 짧은 코스만!",
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
},
|
||||
{
|
||||
@@ -940,7 +1015,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 온도는 실측하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!",
|
||||
"30": "덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.",
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
},
|
||||
{
|
||||
@@ -986,7 +1066,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실내 온도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침이 15° 넘게 따뜻해요. 안경 김 걱정 없어요!",
|
||||
"30": "실내 들어갈 때 살짝 뿌예질 수 있어요.",
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
},
|
||||
{
|
||||
@@ -1032,7 +1117,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "피부 타입은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "선선하고 보송해요. 화장 하루 종일 버텨요!",
|
||||
"30": "오후쯤 살짝 번들거릴 수 있어요.",
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
},
|
||||
{
|
||||
@@ -1080,7 +1170,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "점심이 18° 아래로 선선해요. 냉면보다 국밥!",
|
||||
"30": "시원한 게 살짝 당기는 정도예요.",
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
},
|
||||
{
|
||||
@@ -1128,7 +1223,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "행사·공연 종료 시간은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "맑고 포근한 밤, 택시 금방 잡혀요.",
|
||||
"30": "조금 기다릴 수 있어요. 앱 미리 켜두기!",
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
},
|
||||
{
|
||||
@@ -1177,7 +1277,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 배달 앱 지표로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "날씨 멀쩡해요. 배달 평소처럼 와요.",
|
||||
"30": "살짝 늦을 수 있어요.",
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
},
|
||||
{
|
||||
@@ -1234,7 +1339,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "식물 종류는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 물 주기는 하늘에 맡겨요!",
|
||||
"30": "춥거나 더워요. 화분은 안으로, 물은 조금만.",
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
},
|
||||
{
|
||||
@@ -1290,7 +1400,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "장소 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 와요. 카메라는 쉬어요!",
|
||||
"30": "노을이 약하거나 하늘이 흐려요. 골목 사진 위주로!",
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
},
|
||||
{
|
||||
@@ -1348,7 +1463,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "경기 일정과 시즌(3~10월)은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 70% 넘어요. 우천 취소 각!",
|
||||
"30": "쌀쌀하거나 비 기운이 있어요. 담요랑 우비 챙겨요.",
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
},
|
||||
{
|
||||
@@ -1397,7 +1517,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 공부는… 내일의 내가 할게요!",
|
||||
"30": "나가고 싶은 마음 반, 공부 반이에요.",
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
},
|
||||
{
|
||||
@@ -1445,7 +1570,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밤 공기가 좋아서 밖이 더 끌려요.",
|
||||
"30": "한 편 정도 볼 만해요.",
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
},
|
||||
{
|
||||
@@ -1491,7 +1621,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "군밤 노점이 있는지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 군밤은 조금 더 추워지면!",
|
||||
"30": "저녁이 선선해졌어요. 군밤 노점이 슬슬 생각나요.",
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
}
|
||||
]
|
||||
@@ -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))
|
||||
@@ -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
@@ -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
@@ -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]:
|
||||
|
||||
Vendored
+46
@@ -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
@@ -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]:
|
||||
|
||||
Vendored
+107
@@ -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
@@ -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
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}")
|
||||
@@ -2,8 +2,9 @@ import asyncio
|
||||
import os
|
||||
|
||||
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
|
||||
# 여러 작업 폴더에서 동시에 돌릴 땐 TEST_DB_NAME·TEST_REDIS_DB 를 폴더마다 다르게 준다 (시작할 때 DB 를 지우고 Redis 를 비우므로).
|
||||
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
|
||||
os.environ["REDIS_DB"] = "15"
|
||||
os.environ["REDIS_DB"] = os.environ.get("TEST_REDIS_DB", "15")
|
||||
|
||||
import asyncpg # noqa: E402
|
||||
import pytest # noqa: E402
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fast(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(data_go_kr, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(guard, "BUDGET_SEC", 0.3)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def _ok(_req: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": []}}})
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hanging_api_gives_up_within_budget_then_is_skipped(fast):
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return _ok(req)
|
||||
|
||||
async with _client(hang) as client:
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="no answer within"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 1
|
||||
start = time.perf_counter()
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert time.perf_counter() - start < 0.1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refused_connection_is_skipped_but_other_apis_still_called(fast):
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("getVilageFcst"):
|
||||
raise httpx.ConnectError("refused")
|
||||
return _ok(req)
|
||||
|
||||
async with _client(handler) as client:
|
||||
with pytest.raises(DataGoKrRequestFailed, match="failed after 3 attempts: ConnectError"):
|
||||
await get_body(client, URL, {})
|
||||
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
|
||||
await get_body(client, URL, {})
|
||||
assert await get_body(client, URL.replace("getVilageFcst", "getUltraSrtFcst"), {}) == {"items": []}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_error_code_from_api_does_not_pause_it(fast):
|
||||
calls = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "03", "resultMsg": "NO_DATA"}}})
|
||||
|
||||
async with _client(handler) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(DataGoKrRequestFailed, match="03 NO_DATA"):
|
||||
await get_body(client, URL, {})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
monkeypatch.setattr(open_meteo, "_BUDGET_SEC", 0.3)
|
||||
calls = []
|
||||
|
||||
async def hang(req: httpx.Request) -> httpx.Response:
|
||||
calls.append(1)
|
||||
await asyncio.sleep(5)
|
||||
return httpx.Response(200, json=[])
|
||||
|
||||
async with _client(hang) as client:
|
||||
for _ in range(2):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
@@ -3,9 +3,10 @@ from datetime import date
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from config.settings import settings
|
||||
from services.external import culture_api
|
||||
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
|
||||
from services.external.culture_api import CONCERT, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
_ITEM = """<item><serviceName>공연/전시</serviceName><seq>{seq}</seq><title>{title}</title><startDate>{start}</startDate><endDate>{end}</endDate>
|
||||
@@ -23,6 +24,7 @@ def key(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(culture_api, "_PAGE_SIZE", 2)
|
||||
monkeypatch.setattr(culture_api, "_BACKOFF_SEC", 0)
|
||||
monkeypatch.setattr(culture_api, "_PAGE_GAP_SEC", 0)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
@@ -45,6 +47,19 @@ async def test_fetch_exhibitions_pages_through_xml(key):
|
||||
assert seen[0]["realmCode"] == "D000" and seen[0]["sido"] == "서울" and seen[0]["from"] == "20261006" and seen[0]["to"] == "20261105"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_asks_concert_realm(key):
|
||||
seen = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
seen.append(dict(req.url.params))
|
||||
return httpx.Response(200, text=_page([], 0))
|
||||
|
||||
async with _client(handler) as client:
|
||||
assert await fetch_exhibitions(client, "26", date(2026, 10, 6), 30, CONCERT) == []
|
||||
assert seen[0]["realmCode"] == "B000" and seen[0]["sido"] == "부산"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_reports_unregistered_key(key):
|
||||
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
|
||||
@@ -76,4 +91,12 @@ def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
|
||||
assert rows[0]["image_url"] == "https://www.culture.go.kr/upload/a.jpg"
|
||||
assert rows[0]["lat"] == 37.57592 and rows[0]["lon"] == 126.97689
|
||||
assert rows[0]["sido_code"] == "11" and rows[0]["place_name"] == "테스트 미술관"
|
||||
assert rows[0]["kind"] == EventKind.EXHIBITION
|
||||
assert all(len(r["source_id"]) <= 20 for r in rows)
|
||||
|
||||
|
||||
def test_parse_exhibitions_unescapes_title_and_place():
|
||||
items = [{"seq": "601", "title": "테스트 콘서트 <가을밤>", "place": "테스트 홀 & 라운지", "startDate": "20261010", "endDate": "20261010"}]
|
||||
rows = parse_exhibitions(items, "11", date(2026, 10, 6), CONCERT)
|
||||
assert rows[0]["name"] == "테스트 콘서트 <가을밤>" and rows[0]["place_name"] == "테스트 홀 & 라운지"
|
||||
assert rows[0]["kind"] == EventKind.CONCERT and rows[0]["icon"] == "concert"
|
||||
@@ -0,0 +1,83 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
from services.external import teams_webhook
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def send(title, detail):
|
||||
calls.append((title, detail))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(jobs.teams_webhook, "send", send)
|
||||
monkeypatch.setattr(jobs, "_SIDO_GAP_SEC", 0)
|
||||
monkeypatch.setattr(jobs, "refresh_popups", lambda: _async(ErrorType.SUCCESS))
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_sums_kinds_and_notifies(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async((ErrorType.SUCCESS, {"festival": 2, "exhibition": 1, "concert": 3})))
|
||||
assert await jobs.refresh_events() is ErrorType.SUCCESS
|
||||
n = len(jobs.SIDO_NAME)
|
||||
assert sent[0][0] == "행사 수집 완료"
|
||||
assert f"축제 {2 * n}, 전시 {n}, 콘서트 {3 * n}, 팝업 0" in sent[0][1]
|
||||
assert await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_reports_failed_sido_and_does_not_mark_done(sent, monkeypatch):
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async(
|
||||
(ErrorType.EXTERNAL_API_ERROR, {}) if sido == "46" else (ErrorType.SUCCESS, {"festival": 1, "exhibition": 0, "concert": 0})))
|
||||
assert await jobs.refresh_events() is ErrorType.EXTERNAL_API_ERROR
|
||||
assert sent[0][0] == "행사 수집 일부 실패" and "실패한 시도: 전남" in sent[0][1]
|
||||
assert not await REDIS.conn.exists(jobs.EVENTS_DONE)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_events_skips_when_done_within_7_days(sent, monkeypatch):
|
||||
await REDIS.conn.set(jobs.EVENTS_DONE, "2026-10-05")
|
||||
monkeypatch.setattr(jobs, "collect_events", lambda *a: pytest.fail("수집하면 안 된다"))
|
||||
assert await jobs.refresh_events(only_if_missing=True) is ErrorType.SUCCESS
|
||||
assert sent == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_teams_send_posts_adaptive_card_only_when_configured(monkeypatch):
|
||||
posted = []
|
||||
|
||||
class Client:
|
||||
def __init__(self, **_):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
return False
|
||||
|
||||
async def post(self, url, json):
|
||||
posted.append((url, json))
|
||||
return httpx.Response(202, request=httpx.Request("POST", url))
|
||||
|
||||
monkeypatch.setattr(teams_webhook.httpx, "AsyncClient", Client)
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "http://example.test/hook")
|
||||
assert await teams_webhook.send("t", "d") is False
|
||||
monkeypatch.setattr(settings, "teams_webhook_url", "https://example.test/hook")
|
||||
assert await teams_webhook.send("행사 수집 완료", "축제 1") is True
|
||||
card = posted[0][1]["attachments"][0]["content"]
|
||||
assert [b["text"] for b in card["body"]] == ["행사 수집 완료", "축제 1"]
|
||||
assert len(posted) == 1
|
||||
@@ -6,10 +6,12 @@ from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
from services.week_service import collect_events
|
||||
|
||||
REGION = "1114000000"
|
||||
|
||||
@@ -51,6 +53,7 @@ def test_weekends_groups_this_and_next_weekend():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
@@ -160,6 +163,7 @@ async def test_build_day_makes_every_card_at_three():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_has_quote_and_no_adjacent_same_type(offline):
|
||||
await collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
articles = (await client.get("/v1/season/article/list")).json()
|
||||
@@ -324,6 +328,7 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
await week_service.collect_events("51", today)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": "4113500000"})).json()
|
||||
trip = next(p for p in body["posts"] if p["post_type"] == PostType.DAY_TRIP.value)
|
||||
|
||||
@@ -78,3 +78,21 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/1", params={"region": REGION})).json()
|
||||
bands = body["bands"]
|
||||
assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)]
|
||||
assert all(b["text"] for b in bands)
|
||||
current = [b for b in bands if b["current"]]
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
@@ -0,0 +1,40 @@
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.moon import nearest, phase_name
|
||||
from services.feed_service import FeedService, _tonight
|
||||
|
||||
|
||||
def test_true_phases_match_published_times_within_five_minutes():
|
||||
known = [(True, datetime(2024, 4, 23, 23, 49, tzinfo=timezone.utc)), (False, datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)),
|
||||
(True, datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)), (False, datetime(2017, 8, 21, 18, 30, tzinfo=timezone.utc))]
|
||||
for full, at in known:
|
||||
assert abs((nearest(at, full) - at).total_seconds()) < 300
|
||||
|
||||
|
||||
def test_phase_names():
|
||||
assert phase_name(datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)) == "보름달"
|
||||
assert phase_name(datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)) == "삭"
|
||||
|
||||
|
||||
def test_tonight_follows_feed_day_starting_at_3am():
|
||||
assert _tonight(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 8, 20, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
|
||||
assert _tonight(datetime(2024, 4, 9, 9, 0, tzinfo=KST)) == datetime(2024, 4, 9, 22, 0, tzinfo=KST)
|
||||
|
||||
|
||||
def _moon_post(now: datetime):
|
||||
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
|
||||
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구"), hourly=[], board=None)
|
||||
return FeedService._moon(None, base, c)
|
||||
|
||||
|
||||
def test_moon_post_every_night_with_full_and_new_moon_stories():
|
||||
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
|
||||
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line
|
||||
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
|
||||
assert new.title == "오늘 밤 달 없는 밤"
|
||||
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
|
||||
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
|
||||
@@ -0,0 +1,64 @@
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.enums import EventKind
|
||||
from services.external import popga
|
||||
from services.external.popga import fetch_popup_index, parse_popup, sido_of
|
||||
|
||||
|
||||
def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울 성동구 테스트로 1") -> str:
|
||||
ld = {
|
||||
"@context": "https://schema.org", "@type": "Event", "name": "테스트 팝업 & 굿즈", "startDate": start, "endDate": end,
|
||||
"location": {"@type": "Place", "name": "테스트 빌딩 1F", "address": {"@type": "PostalAddress", "streetAddress": address},
|
||||
"geo": {"@type": "GeoCoordinates", "latitude": 37.5446123, "longitude": 127.0557456}},
|
||||
}
|
||||
payload = f'self.__next_f.push([1,"{{\\"data\\":{{\\"id\\":{popup_id},\\"type\\":\\"{kind}\\",\\"source\\":null}}}}"])'
|
||||
return f'<html><script type="application/ld+json">{json.dumps(ld, ensure_ascii=False)}</script><script>{payload}</script></html>'
|
||||
|
||||
|
||||
def test_parse_popup_maps_store():
|
||||
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
|
||||
assert row == {
|
||||
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F",
|
||||
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
|
||||
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-10-11", "알 수 없는 주소"),
|
||||
])
|
||||
def test_parse_popup_skips_non_store_ended_or_unknown_sido(kind, end, address):
|
||||
assert parse_popup(_page(502, kind, "2026-09-01", end, address), 502, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
def test_parse_popup_reads_type_of_its_own_id():
|
||||
page = _page(503, "STORE", "2026-10-02", "2026-10-11").replace('\\"id\\":503,\\"type\\":\\"STORE\\"', '\\"id\\":999,\\"type\\":\\"STORE\\"')
|
||||
assert parse_popup(page, 503, date(2026, 10, 1)) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address,code", [
|
||||
("서울 마포구 테스트로 1", "11"), ("서울특별시 마포구", "11"), ("경기 수원시", "41"), ("경상남도 진주시", "48"),
|
||||
("강원특별자치도 춘천시", "51"), ("전북특별자치도 전주시", "52"), ("", None),
|
||||
])
|
||||
def test_sido_of(address, code):
|
||||
assert sido_of(address) == code
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_popup_index_reads_popup_pages_only(monkeypatch):
|
||||
monkeypatch.setattr(popga, "REQUEST_GAP_SEC", 0)
|
||||
pages = {
|
||||
"/sitemap.xml": "<sitemapindex><sitemap><loc>https://popga.co.kr/sitemap/2.xml</loc></sitemap>"
|
||||
"<sitemap><loc>https://popga.co.kr/sitemap/5.xml</loc></sitemap></sitemapindex>",
|
||||
"/sitemap/2.xml": "<urlset><url><loc>https://popga.co.kr/popup/12</loc><lastmod>2026-10-06T00:00:00Z</lastmod></url>"
|
||||
"<url><loc>https://popga.co.kr/popup/11</loc></url></urlset>",
|
||||
"/sitemap/5.xml": "<urlset><url><loc>https://popga.co.kr/popup/12/review/3</loc><lastmod>2026-10-06</lastmod></url></urlset>",
|
||||
}
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(200, text=pages[req.url.path]))) as client:
|
||||
assert await fetch_popup_index(client) == {12: "2026-10-06T00:00:00Z", 11: ""}
|
||||
@@ -54,8 +54,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||
assert plan["outlook"].endswith("비슷해요")
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 4
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -104,14 +106,19 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
|
||||
|
||||
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import SkySituation
|
||||
|
||||
today = date(2026, 10, 6)
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 — 72점, 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today).startswith("오늘이 가장 나아요")
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == "내일·모레도 비슷해요"
|
||||
sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == ""
|
||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||
few, glow = SkySituation.FEW, SkySituation.GLOW
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
|
||||
@@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
CLEAR = Layers(0, 0, 0)
|
||||
@@ -43,7 +43,7 @@ def test_sunset_best_times_order():
|
||||
sunset = datetime(2026, 10, 2, 9, 15, tzinfo=timezone.utc)
|
||||
dusk = datetime(2026, 10, 2, 9, 41, tzinfo=timezone.utc)
|
||||
labels = [t["label"] for t in best_times(SkyType.SUNSET, sunset, dusk, 50)]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "블루아워"]
|
||||
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
@@ -65,3 +65,23 @@ def test_sunset_timeline_runs_golden_to_blue():
|
||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||
|
||||
|
||||
def test_situation_follows_reason_order():
|
||||
from common.enums import SkySituation
|
||||
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
|
||||
assert situation(clear, clear, clear) is SkySituation.FEW
|
||||
assert situation(glow, glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), Layers(70, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, glow, Layers(70, 0, 0)) is SkySituation.COVERED
|
||||
|
||||
|
||||
def test_ranking_summary_only_when_most_spots_share_a_situation():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import SkySituation
|
||||
from services.sky_service import ranking_summary
|
||||
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
|
||||
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
|
||||
+21
-10
@@ -8,12 +8,12 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.enums import RainType, Sky
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import _status
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -45,6 +45,15 @@ def test_event_status_labels():
|
||||
assert _status(ev(date(2026, 10, 20), date(2026, 10, 21)), today) == ("soon", "D-18")
|
||||
|
||||
|
||||
def test_mix_kinds_rotates_festival_popup_exhibition_concert():
|
||||
item = lambda name, kind: EventItem(event=Event(name=name, kind=kind), status="soon", status_label="", fit=None) # noqa: E731
|
||||
items = [item("연주회1", EventKind.CONCERT), item("연주회2", EventKind.CONCERT), item("전시1", EventKind.EXHIBITION),
|
||||
item("팝업1", EventKind.POPUP), item("연주회3", EventKind.CONCERT), item("축제1", EventKind.FESTIVAL)]
|
||||
assert [e.event.name for e in mix_kinds(items)] == ["축제1", "팝업1", "전시1", "연주회1", "연주회2", "연주회3"]
|
||||
only = [item(f"연주회{i}", EventKind.CONCERT) for i in range(3)]
|
||||
assert [e.event.name for e in mix_kinds(only)] == ["연주회0", "연주회1", "연주회2"]
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
@@ -67,6 +76,11 @@ def _mid(*_):
|
||||
return land, ta
|
||||
|
||||
|
||||
async def _collect(*sidos):
|
||||
for sido in sidos:
|
||||
await week_service.collect_events(sido, now_kst().date())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
today = now_kst().date()
|
||||
@@ -99,6 +113,7 @@ async def test_week_reaches_mid_forecast_end_with_holiday_and_rain(fakes):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -114,6 +129,7 @@ async def test_events_include_culture_exhibitions_with_their_credit(fakes, monke
|
||||
"seq": "123", "title": "가을 특별전", "place": "테스트 미술관", "startDate": (today + timedelta(days=1)).strftime("%Y%m%d"),
|
||||
"endDate": (today + timedelta(days=20)).strftime("%Y%m%d"), "thumbnail": "http://www.culture.go.kr/x.jpg", "gpsX": "126.97", "gpsY": "37.57",
|
||||
}]))
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
by_name = {e["name"]: e for e in body["events"]}
|
||||
@@ -129,6 +145,7 @@ async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypa
|
||||
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
|
||||
await _collect("11")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
@@ -145,16 +162,10 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
"41": [{"contentid": "41", "title": "연천 축제", "addr1": "경기 연천군", "mapy": "38.0963", "mapx": "127.0750", **span},
|
||||
{"contentid": "42", "title": "좌표 없는 경기 축제", "addr1": "경기", **span}],
|
||||
}
|
||||
asked = []
|
||||
|
||||
def festivals(client, sido, since):
|
||||
asked.append(sido)
|
||||
return _async(by_sido.get(sido, []))
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("11", "41")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "4113500000"})).json()
|
||||
assert {"11", "41"} <= set(asked) and "26" not in asked
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_weekend_rank
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_weekend_rank
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -20,8 +20,11 @@ async def main() -> None:
|
||||
# 주말 나들이 점수: 단기예보 05·17시 발표와 중기예보 06·18시 발표가 다 나온 뒤. 켤 때 캐시가 없으면 한 번.
|
||||
scheduler.add_job(refresh_weekend_rank, "cron", hour="6,18", minute=40, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_weekend_rank, kwargs={"only_if_missing": True}, max_instances=1)
|
||||
# 행사(축제·전시·콘서트·팝업): 7일에 한 번, 끝나면 Teams 알림. 켤 때 7일 안에 받은 기록이 없으면 한 번.
|
||||
scheduler.add_job(refresh_events, "cron", day_of_week="mon", hour=4, minute=0, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_events, kwargs={"only_if_missing": True}, max_instances=1)
|
||||
scheduler.start()
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST")
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
Reference in new issue
Block a user