Merge remote-tracking branch 'origin/main' into feat/watch-summary
This commit is contained in:
commit
f6ec296130
84 files changed
+3406
-879
No files matched your search
@@ -101,8 +101,9 @@ class WeatherWarning(Base):
|
||||
class CloudHourly(Base):
|
||||
__tablename__ = "cloud_hourly"
|
||||
|
||||
lat: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
lon: Mapped[Decimal] = mapped_column(Numeric(5, 2), primary_key=True)
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
kind: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
distance_km: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
model: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
cloud_low: Mapped[int] = mapped_column(SmallInteger)
|
||||
@@ -110,6 +111,23 @@ class CloudHourly(Base):
|
||||
cloud_high: Mapped[int] = mapped_column(SmallInteger)
|
||||
|
||||
|
||||
class OpenMeteoHourly(Base):
|
||||
__tablename__ = "openmeteo_hourly"
|
||||
|
||||
region_code: Mapped[str] = mapped_column(String(10), primary_key=True)
|
||||
forecast_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), primary_key=True)
|
||||
uv_index: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True)
|
||||
uv_index_clear_sky: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 2), nullable=True)
|
||||
visibility_m: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
wind_gust_ms: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
pressure_hpa: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 1), nullable=True)
|
||||
soil_temp_c: Mapped[Optional[Decimal]] = mapped_column(Numeric(4, 1), nullable=True)
|
||||
sunshine_s: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
shortwave_avg_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
shortwave_max_wm2: Mapped[Optional[int]] = mapped_column(SmallInteger, nullable=True)
|
||||
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SkyScore(Base):
|
||||
__tablename__ = "sky_score"
|
||||
|
||||
@@ -121,6 +139,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):
|
||||
@@ -153,6 +174,9 @@ class IndexDefinition(Base):
|
||||
weight_wind: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_humidity: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_air: Mapped[int] = mapped_column(SmallInteger)
|
||||
weight_uv: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_sun: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_view: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
weight_time: Mapped[int] = mapped_column(SmallInteger)
|
||||
factor_rules: Mapped[dict] = mapped_column(JSONB)
|
||||
zero_rules: Mapped[list] = mapped_column(JSONB)
|
||||
@@ -174,6 +198,9 @@ class IndexScore(Base):
|
||||
wind_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
humidity_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
air_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
uv_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
sun_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
view_score: Mapped[int] = mapped_column(SmallInteger, default=0, server_default="0")
|
||||
time_score: Mapped[int] = mapped_column(SmallInteger)
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
@@ -220,6 +247,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 = ""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import and_, delete, or_, select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -14,13 +14,13 @@ class SkyCRUD:
|
||||
for i in range(0, len(rows), _CHUNK):
|
||||
stmt = insert(CloudHourly).values(rows[i:i + _CHUNK])
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["lat", "lon", "forecast_at", "model"],
|
||||
index_elements=["region_code", "kind", "distance_km", "forecast_at", "model"],
|
||||
set_={k: stmt.excluded[k] for k in ("cloud_low", "cloud_mid", "cloud_high")},
|
||||
))
|
||||
|
||||
async def clouds_at(self, s: AsyncSession, points: list[tuple[float, float]], at: datetime) -> list[CloudHourly]:
|
||||
cond = or_(*[and_(CloudHourly.lat == round(lat, 2), CloudHourly.lon == round(lon, 2)) for lat, lon in points])
|
||||
return list((await s.scalars(select(CloudHourly).where(cond, CloudHourly.forecast_at == at))).all())
|
||||
async def clouds_at(self, s: AsyncSession, region_code: str, at: datetime) -> list[CloudHourly]:
|
||||
stmt = select(CloudHourly).where(CloudHourly.region_code == region_code, CloudHourly.forecast_at == at)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
@@ -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]:
|
||||
|
||||
@@ -5,7 +5,9 @@ from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import SunTime, WeatherDaily, WeatherHourly
|
||||
from common.database.model.models import OpenMeteoHourly, SunTime, WeatherDaily, WeatherHourly
|
||||
|
||||
_CHUNK = 1000
|
||||
|
||||
|
||||
def _upsert_newer(model, rows: list[dict], keys: list[str]):
|
||||
@@ -27,6 +29,26 @@ class WeatherCRUD:
|
||||
if rows:
|
||||
await s.execute(_upsert_newer(WeatherDaily, rows, ["region_code", "forecast_date"]))
|
||||
|
||||
async def upsert_openmeteo(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
"""같은 (구, 시각)이면 덮어쓰되, 새 응답에서 값이 비어 오면(NULL) 그 칼럼은 이전 값을 지키고 받은 시각만 갱신한다."""
|
||||
keys = ["region_code", "forecast_at"]
|
||||
table = OpenMeteoHourly.__table__
|
||||
for i in range(0, len(rows), _CHUNK):
|
||||
stmt = insert(OpenMeteoHourly).values(rows[i:i + _CHUNK])
|
||||
set_ = {
|
||||
c.name: stmt.excluded[c.name] if c.name == "fetched_at" else func.coalesce(stmt.excluded[c.name], table.c[c.name])
|
||||
for c in table.columns if c.name not in keys
|
||||
}
|
||||
await s.execute(stmt.on_conflict_do_update(index_elements=keys, set_=set_))
|
||||
|
||||
async def openmeteo_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[OpenMeteoHourly]:
|
||||
stmt = (
|
||||
select(OpenMeteoHourly)
|
||||
.where(OpenMeteoHourly.region_code == region_code, OpenMeteoHourly.forecast_at >= start, OpenMeteoHourly.forecast_at <= end)
|
||||
.order_by(OpenMeteoHourly.forecast_at)
|
||||
)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
|
||||
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
|
||||
|
||||
|
||||
@@ -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,8 @@
|
||||
|
||||
| 문서 | 내용 | 아티팩트 |
|
||||
|---|---|---|
|
||||
| `../../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 |
|
||||
| `openmeteo-data.md` | Open-Meteo로 받는 구름(JMA·ICON, 20·100km)과 보조값(자외선·가시거리·돌풍·기압·일조·일사·지면온도)의 변수, 3시간 집계, 저장·갱신, 호출량, 지수 활용 후보, DB 적용 SQL | - |
|
||||
| `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` 참고.
|
||||
|
||||
## 핵심
|
||||
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# Open-Meteo 데이터
|
||||
|
||||
Open-Meteo(`api.open-meteo.com/v1/forecast`)에서 받는 데이터와 저장 방식. 인증키는 쓰지 않는다. 전체 데이터 흐름은 `data-pipeline.md`, 이 문서는 Open-Meteo 쪽만 자세히 적는다.
|
||||
|
||||
> 수치(소요 시간, 값 분포 등)는 2026-10-06 로컬에서 실제 호출해 잰 값이다. 운영에서 달라질 수 있다.
|
||||
|
||||
## 한눈에
|
||||
|
||||
| 구분 | 테이블 | 담는 것 | 좌표 | 모델 | 언제 받나 |
|
||||
|---|---|---|---|---|---|
|
||||
| 층별 구름 | `cloud_hourly` | 저·중·상층 구름 %. 노을·일출 점수용 | 구마다 해 지는 쪽·뜨는 쪽 **20·100km 지점 4곳** | **JMA·ICON** 각각 | 사용자가 볼 때. 오전·13시 이후·21시 이후 구별 하루 3번 |
|
||||
| 보조값 | `openmeteo_hourly` | 자외선·가시거리·돌풍·기압·일조·일사·지면온도 | **구 중심 1곳** (256곳) | 지정 안 함 (Open-Meteo 기본) | worker가 03·09·15·21시 10분(KST)에 전국 일괄 |
|
||||
|
||||
두 테이블은 서로 다른 출처·좌표·주기로 쌓이고 합쳐지지 않는다. 보조값은 활동 지수 10개의 점수에 쓰인다 (3절).
|
||||
|
||||
## 1. 층별 구름 (`cloud_hourly`)
|
||||
|
||||
### 저장 구조
|
||||
|
||||
| 칼럼 | 설명 |
|
||||
|---|---|
|
||||
| `region_code`, `kind`, `distance_km`, `forecast_at`, `model` | 키. `kind` 1=일몰 방향 2=일출 방향, `distance_km` 20 또는 100, `model` 3=JMA 4=ICON |
|
||||
| `cloud_low`, `cloud_mid`, `cloud_high` | 낮은(약 2km 아래)·중간·높은(약 6km 위) 구름 % |
|
||||
|
||||
- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 저장한다. 구마다 2종류 × 2거리 × 3일 × 2모델 = **24행**.
|
||||
- 정리: 예보 시각이 **2일** 지난 행을 매일 03:00에 지운다.
|
||||
|
||||
### 좌표와 시각
|
||||
|
||||
1. 그날 일몰·일출 방위각을 계산한다 (`services/calc/sun.py`). 오늘 값 하나를 3일치에 같이 쓴다.
|
||||
2. 구 중심에서 그 방향으로 20km, 100km 떨어진 점을 구한다 (`common/utils/geo.py`의 `destination`, 소수 둘째 자리 반올림).
|
||||
3. 일몰(일출) 시각에서 가장 가까운 정시(30분을 더해 정시로 내림, GMT)의 값을 쓴다.
|
||||
|
||||
### 점수에 쓰는 방식 (`services/calc/sky_score.py`)
|
||||
|
||||
| 거리 | 쓰는 값 | 역할 |
|
||||
|---|---|---|
|
||||
| 20km | 저·중·상층 | 머리 위 하늘. 중·상층 구름이 50% 안팎이면 물들고, 저층이 많으면 가려져 감점 |
|
||||
| 100km | 저층 + 중층(절반) | 해 쪽 지평선. 막히면 햇빛이 못 들어와 전체를 최대 75% 깎음 |
|
||||
|
||||
```
|
||||
canvas = max(mid20, high20)
|
||||
f_canvas = 0.3 (canvas < 10) / max(0, 1 - |canvas-50|/50)
|
||||
f_near = 1 - 0.8 × low20 / 100
|
||||
light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
점수 = round(100 × (0.75×f_canvas + 0.25×f_near) × (0.25 + 0.75×light))
|
||||
```
|
||||
|
||||
- 모델마다 따로 계산해 **평균**을 최종 점수로 쓰고, 모델 점수의 표준편차로 신뢰도를 정한다 (8 미만 높음, 15 미만 보통, 그 이상 낮음). 모델이 2개 미만이면 낮음.
|
||||
- 등급: 80 이상 붉음, 60 이상 고움, 40 이상 은은함, 그 미만 흐림.
|
||||
|
||||
### 이렇게 정한 이유 (검증 기록)
|
||||
|
||||
- **20·100km 두 지점**: 기존 6점(20·50·100km)과 같은 구름 데이터로 비교하면 점수 차이 평균 0.4점, 최대 7점, 상관 0.97, 등급 일치 185/186 (구 31곳 × 3일 × 일몰/일출). 20km 한 점만 쓰면 상관이 0.18~0.28로 떨어져 구 순위가 맞지 않는다. 50km는 20km와 역할이 겹친다.
|
||||
- **JMA·ICON 두 모델**: 4모델(ECMWF·GFS·JMA·ICON) 평균과 비교하면 점수 차이 평균 1.9점, 최대 12점, 상관 0.91, 등급 일치 166/186. 모델 2개라 신뢰도 "낮음"이 186개 중 3개 나온다 (4모델은 0개). 구름이 거의 없는 날 데이터라 흐린 날에는 다를 수 있다.
|
||||
- 모델 성격(로컬 데이터 기준): ICON이 구름을 가장 많이 보고하고(저층 평균 10.4%), JMA는 중층을 상대적으로 많이 본다(평균 3.7%). 같은 지점·시각에서 한 층이라도 30%p 이상 갈리는 비율이 23%였다. 어느 모델이 한국 실제 구름과 맞는지는 관측으로 검증하지 않았다.
|
||||
|
||||
### 호출량
|
||||
|
||||
- 구마다 좌표 4개. 좌표 24개씩 나눠 동시에 요청하므로 요청 수는 `ceil(좌표 수 / 24)`.
|
||||
- 한 시간대에 전국 256곳을 한꺼번에 갱신하면 좌표 1,024개, 요청 43번. 구별로 따로 갱신하면 구마다 1번.
|
||||
- 구별 하루 최대 3번 갱신 (Redis 마커 `sky:{구}:{날짜}:{시간대}`, 24시간).
|
||||
|
||||
## 2. 보조값 (`openmeteo_hourly`)
|
||||
|
||||
### 받는 변수
|
||||
|
||||
요청: `hourly=<아래 8개>`, `wind_speed_unit=ms`, `forecast_days=4`, `timezone=GMT`, 모델 미지정. 좌표 24개씩 묶어 11번을 동시에 보낸다.
|
||||
|
||||
| Open-Meteo 변수 | 단위 | 칼럼 | 3시간 구간 값 |
|
||||
|---|---|---|---|
|
||||
| `uv_index` | 지수 | `uv_index` | 구간 끝 시각 값 |
|
||||
| `uv_index_clear_sky` | 지수 | `uv_index_clear_sky` | 구간 끝 시각 값. `uv_index ÷ 이 값` = 구름이 해를 가린 정도 |
|
||||
| `visibility` | m | `visibility_m` | 구간 끝 시각 값 |
|
||||
| `wind_gusts_10m` | m/s | `wind_gust_ms` | 구간 끝 시각 값 |
|
||||
| `pressure_msl` | hPa | `pressure_hpa` | 구간 끝 시각 값 |
|
||||
| `soil_temperature_0cm` | ℃ | `soil_temp_c` | 구간 끝 시각 값 |
|
||||
| `sunshine_duration` | 초 | `sunshine_s` | **직전 3시간 합** (0~10,800) |
|
||||
| `shortwave_radiation` | W/m² | `shortwave_avg_wm2`, `shortwave_max_wm2` | 직전 3시간 **평균**, 그중 가장 센 1시간 값 **최대** |
|
||||
|
||||
- 모델을 지정하지 않는 이유: `models`를 지정하면 자외선이 GFS에서만 값이 오고 ECMWF·JMA·ICON은 전부 null이었다. 지정하지 않으면 Open-Meteo가 고른 값 하나가 오는데 어느 모델인지는 응답에 없다. 그래서 이 테이블은 모델별 비교(신뢰도)를 할 수 없다.
|
||||
- 구 중심 256곳 전부, 4일(96시간) 동안 8개 변수 모두 값이 왔고 null은 없었다.
|
||||
|
||||
### 시각 규칙
|
||||
|
||||
- `forecast_at`은 3시간 구간의 **끝 시각**이다. GMT 0·3·6… 정시이고 KST로도 0·3·6… 정시라 단기예보 슬롯과 맞는다.
|
||||
- 일조·일사는 Open-Meteo가 "직전 1시간 값"으로 주므로, 끝 시각 t의 구간은 t-2·t-1·t 시 값 3개다. 3시간이 다 있는 구간만 저장한다.
|
||||
- 자외선·가시거리 등 나머지는 끝 시각 t의 순간값이다.
|
||||
- **밤 구간(21~06시 = 끝 시각 KST 00·03·06시)은 햇빛 값을 저장하지 않는다**: `uv_index`, `uv_index_clear_sky`, `sunshine_s`, `shortwave_avg_wm2`, `shortwave_max_wm2`는 NULL. 가시거리·돌풍·기압·지면온도는 그대로 저장한다. 지수 계산에서는 이 구간을 '정보 없음'이 아니라 자외선 0·일조 0으로 본다 (`is_dark_slot`).
|
||||
- 요청이 UTC 오늘 00시(= KST 09시)부터 96시간이라 한 번에 구간 31개가 나온다 (구 256곳 × 31 = 7,936행).
|
||||
- **KST 하루의 일조 합**은 끝 시각 09·12·15·18·21시 구간 5개를 더한다 (밤 구간은 NULL).
|
||||
- 일사 평균은 맑은 날에도 피크를 깎는다 (시간별 최대 762 → 3시간 평균 최대 694). 시각별 임계(예: 500W/m²)로 쓸 때는 `shortwave_max_wm2`를 같이 본다.
|
||||
|
||||
### 저장·갱신
|
||||
|
||||
| 항목 | 규칙 |
|
||||
|---|---|
|
||||
| 수집 | worker가 03·09·15·21시 10분(KST). 정각이 아닌 이유는 03:00 일일 작업과 겹치지 않게 하려는 것 |
|
||||
| 소요 시간 | 요청 11번 동시 호출 약 2.6~4.6초, 파싱 0.08초, 전체 약 5초 (DB 저장 7,936행 포함) |
|
||||
| 덮어쓰기 | `ON CONFLICT (region_code, forecast_at)`로 같은 (구, 시각)을 새 값으로 바꾼다. 이력은 남지 않는다 |
|
||||
| 값이 비어 올 때 | 새 값이 NULL이면 그 칼럼은 **이전 값을 유지**(`COALESCE`)하고 `fetched_at`만 갱신한다 |
|
||||
| 응답 범위 밖 지난 구간 | 새 응답에 없어서 덮이지 않고 마지막으로 받은 예보 값이 남는다 (실측값이 아님) |
|
||||
| 보관 | 예보 시각이 **7일** 지난 행을 매일 03:00에 지운다 |
|
||||
|
||||
- `fetched_at`은 "마지막 응답을 받은 시각"이다. 일부 칼럼이 계속 비어 오면 그 칼럼은 오래된 값이 남을 수 있다.
|
||||
- 오늘 KST 아침 구간(03·06·09시)은 03:10 수집이 채운다. 워커가 그 시각에 꺼져 있으면 그날 일조 합이 빈다 (요청에 `past_days=1`을 넣으면 해결, 아직 안 함).
|
||||
|
||||
### 호출량
|
||||
|
||||
- 한 번 11번 × 하루 4번 = **하루 44번**, 좌표로는 하루 1,024개.
|
||||
- 구름과 합치면 구름이 전국 일괄일 때 하루 약 4,100좌표 (구름 1,024좌표 × 3시간대 + 보조값 1,024).
|
||||
|
||||
## 3. 활동 지수에 쓰는 방식
|
||||
|
||||
활동 지수 27개 중 10개에 보조값을 적용했다 (`services/calc/index_calc.py`, `services/index_service.py`, `seed/index_definition.json`).
|
||||
|
||||
### 새 축 3개
|
||||
|
||||
| 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 |
|
||||
|---|---|---|---|
|
||||
| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` |
|
||||
| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` |
|
||||
| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` |
|
||||
|
||||
- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**.
|
||||
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다.
|
||||
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
|
||||
- 0점 조건에 쓰는 필드 2개가 늘었다: `gust_ms`(돌풍 최대), `ground_c`(지표면 온도 최대).
|
||||
|
||||
### 지수별 적용
|
||||
|
||||
| 지수 | 새 비중 | 바뀐 기존 비중 (기온·비·바람·습도·공기) | 추가 0점 조건 |
|
||||
|---|---|---|---|
|
||||
| 빨래각 | 햇빛 25 | 15·30·15·10·0 | |
|
||||
| 멍뭉산책각 | 자외선 5 | 35·25·10·5·15 | 지표면 온도 45° 이상 |
|
||||
| 피크닉각 | 자외선 10 | 25·25·15·5·10 | |
|
||||
| 등산각 | 자외선 5, 가시거리 5 | 25·25·20·5·10 | |
|
||||
| 러닝각 | 자외선 5 | 35·20·10·15·10 | |
|
||||
| 가드닝각 | 자외선 5 | 25·30·10·15·10 | |
|
||||
| 별보기각 | 가시거리 15 | 5·10·5·5·15 (시간대 45 그대로) | |
|
||||
| 사진산책각 | 가시거리 10 | 10·25·10·5·10 (시간대 30 그대로) | |
|
||||
| 자전거각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
| 캠핑각 | | 변경 없음 | 돌풍 15m/s 이상 |
|
||||
|
||||
- 나머지 17개 지수는 점수가 바뀌지 않는다 (적용 전후 비교로 확인).
|
||||
- 비중·기준값은 초안이다. 수치는 `seed/index_definition.json`에서 바꾸고 `load_seed.py`로 다시 넣는다.
|
||||
|
||||
### 3시간 구간을 계산 창에 연결하는 규칙
|
||||
|
||||
지수 계산 창(예: 7~10시)의 시각 h마다 아래 구간을 붙인다.
|
||||
|
||||
| 값 | 쓰는 구간 | 이유 |
|
||||
|---|---|---|
|
||||
| 자외선·가시거리·돌풍·지표면 온도 (순간값) | h시~h+1시 한가운데에 **가장 가까운** 구간 끝 시각 (9시→9시, 10시→12시) | 순간값이라 가까운 구간이 맞다. 덮는 구간을 쓰면 아침 창(7~10시)에 정오 자외선이 들어간다 |
|
||||
| 일조 (직전 3시간 합) | h시~h+1시를 **덮는** 구간 (7시→9시, 12시→15시) | 구간 값이 직전 3시간이다 |
|
||||
|
||||
- 처음에는 모두 덮는 구간으로 연결했다가, 가드닝각(7~10시)이 정오 자외선 때문에 86 → 79로 크게 떨어지는 것을 비교에서 발견해 순간값을 가장 가까운 구간으로 바꿨다.
|
||||
- 창과 구간이 어긋나는 곳(11~16시, 7~12시 등)은 근사다.
|
||||
|
||||
### 재계산
|
||||
|
||||
`IndexService.ensure`가 점수를 다시 계산하는 기준에 `openmeteo_hourly.fetched_at`을 추가했다. 보조값이 새로 와야 지수가 새로 계산된다 (6시간마다).
|
||||
|
||||
### 적용 전후 (성남시 분당구 4113500000, 2026-10-06 로컬)
|
||||
|
||||
| 지수 | 10/6 | 10/7 | 10/8 | 비고 |
|
||||
|---|---|---|---|---|
|
||||
| 빨래각 | 84→86 | 81→84 | 81→84 | 해 난 비율 100% |
|
||||
| 멍뭉산책각 | 93→94 | 93→93 | 91→92 | |
|
||||
| 피크닉각 | 81→75 | 85→78 | 85→78 | 낮 자외선 5.0 → 자외선 점수 49 |
|
||||
| 등산각 | 77→76 | 78→77 | 79→78 | |
|
||||
| 러닝각 | 76→78 | 80→82 | 74→77 | |
|
||||
| 가드닝각 | 86→84 | 83→83 | 86→86 | |
|
||||
| 별보기각 | 72→75 | 78→81 | 77→80 | |
|
||||
| 사진산책각 | 73→73 | 73→73 | 72→73 | |
|
||||
| 자전거각, 캠핑각 | 변화 없음 | | | 돌풍 15m/s 미만 |
|
||||
|
||||
- 자외선 5(보통 수준)에 49점은 가혹할 수 있다. 여름 한낮 자외선(8 이상)은 0점이 되어 피크닉각이 크게 내려간다. 필요하면 시드 JSON의 `uv` 규칙(`zero`, `full`)을 조정한다.
|
||||
- 이 비교는 한 지역, 3일, 맑은 날 기준이다.
|
||||
|
||||
### 아직 안 쓴 것
|
||||
|
||||
- 기압(`pressure_hpa`): 등산·캠핑의 "기압 하락" 규칙은 6시간 변화 계산이 필요해 이번에 넣지 않았다.
|
||||
- 일사(`shortwave_*`): 쓰는 지수가 없다.
|
||||
- 문서 `날씨 데이터 및 지수 산출.html`의 새 지수(드라이브·도파민·뽀송·감정기복·센치·안개감성)는 아직 만들지 않았다.
|
||||
- 시간대 해상도가 3시간이라 1~2시간짜리 계산 창에서는 정확도가 떨어진다.
|
||||
|
||||
## 4. 알려진 한계와 주의
|
||||
|
||||
- **429**: 짧은 시간에 좌표를 몰아서 보내면 Open-Meteo가 429를 준다. 로컬에서 좌표 256개 × 3번을 연달아 보냈더니 3번째에 났고, 75초 쉰 뒤 정상이었다. 현재 재시도는 1초·2초 간격 3번이라 분당 한도에 걸리면 그 회차는 11개 요청 중 하나만 실패해도 전체가 저장되지 않는다. 다음 수집(6시간 뒤)까지 옛 값이 남는다.
|
||||
- **한도**: 문서(`날씨 데이터 및 지수 산출.html`)는 하루 1만 건, 시간당 5천 건, 분당 600건이라고 적는다. 좌표 수 기준인지 요청 수 기준인지 확정하지 못했다. 로컬 429는 좌표 수 기준을 시사한다.
|
||||
- **상업 이용**: Open-Meteo 무료 API는 비상업용이다. 서비스에 붙이려면 유료 플랜(API 키)이 필요하다.
|
||||
- **관측값이 아니다**: 전부 예보 모델 값이다. 가시거리·일조·기압은 기상청 관측과 대조하지 않았다. 기상청 ASOS·생활기상지수는 이 키로 호출이 막혔다 (403, 400).
|
||||
- **보조값이 비어 있으면 해당 축은 70점(정보 없음)**으로 계산되어 지수가 평범하게 보일 수 있다. 수집 실패가 길어지면 알아채기 어렵다.
|
||||
- 자외선 등 임계값은 한국 기준으로 검증되지 않은 초안이다.
|
||||
|
||||
## 5. 코드 위치
|
||||
|
||||
| 파일 | 역할 |
|
||||
|---|---|
|
||||
| `services/external/open_meteo.py` | `fetch_clouds`·`parse_clouds`(구름), `fetch_weather`·`parse_weather`(보조값, 3시간 집계), `MODELS` |
|
||||
| `services/sky_service.py` | 구름 갱신(`_refresh`), 구 코드 키 저장, 점수 계산 |
|
||||
| `services/calc/sky_score.py` | 점수·등급·신뢰도·추천 시각 |
|
||||
| `scheduler/jobs.py`, `worker_main.py` | 보조값 수집 job(`refresh_openmeteo_weather`)과 스케줄, 7일 정리 |
|
||||
| `crud/sky_crud.py`, `crud/weather_crud.py` | `cloud_hourly` 저장, `openmeteo_hourly` 저장(`upsert_openmeteo`, NULL 유지) |
|
||||
| `services/calc/index_calc.py` | 새 축 `uv_score`·`sun_score`·`view_score`, 0점 필드 `gust_ms`·`ground_c`, `evaluate` 반영 |
|
||||
| `services/index_service.py` | 3시간 구간 연결(`windows_for`, `_nearest_slot_end_hour`, `_slot_end_hour`), 재계산 기준에 `fetched_at` 추가 |
|
||||
| `router/v1/index/index.py` | 새 축 이름표, 비중 있는 새 축만 상세에 노출 |
|
||||
| `seed/index_definition.json` | 10개 지수의 새 비중·규칙·0점 조건 |
|
||||
| `common/database/model/models.py`, `postgres-init/init.sql` | `CloudHourly`, `OpenMeteoHourly`, 지수 새 축 칼럼 모델과 DDL |
|
||||
| `tests/test_openmeteo_weather.py`, `tests/test_sky_api.py`, `tests/test_sky_score.py`, `tests/test_index_calc.py`, `tests/test_index_api.py` | 집계·저장·덮어쓰기·점수·새 축·구간 연결·재계산 테스트 |
|
||||
|
||||
## 6. 이미 만들어진 DB에 적용할 SQL
|
||||
|
||||
`init.sql`은 DB를 처음 만들 때만 실행된다. 이미 있는 DB에는 아래를 직접 적용한다 (운영 DB는 코드 배포와 순서를 맞춘다).
|
||||
|
||||
```sql
|
||||
BEGIN;
|
||||
|
||||
-- cloud_hourly 구조 변경 (좌표 키 → 구 코드 키). 기존 행은 삭제된다 (외부 API 캐시).
|
||||
DROP TABLE IF EXISTS public.cloud_hourly;
|
||||
CREATE TABLE public.cloud_hourly (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
kind SMALLINT NOT NULL, -- 1=일몰 방향 2=일출 방향
|
||||
distance_km SMALLINT NOT NULL, -- 20 또는 100
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
model SMALLINT NOT NULL, -- 3=JMA 4=ICON
|
||||
cloud_low SMALLINT NOT NULL,
|
||||
cloud_mid SMALLINT NOT NULL,
|
||||
cloud_high SMALLINT NOT NULL,
|
||||
PRIMARY KEY (region_code, kind, distance_km, forecast_at, model)
|
||||
);
|
||||
DELETE FROM public.sky_score; -- 옛 방식 점수를 비워 새 방식으로 다시 계산
|
||||
|
||||
-- openmeteo_hourly 신규 (추가만 함)
|
||||
CREATE TABLE IF NOT EXISTS public.openmeteo_hourly (
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
uv_index NUMERIC(4,2) NULL,
|
||||
uv_index_clear_sky NUMERIC(4,2) NULL,
|
||||
visibility_m INTEGER NULL,
|
||||
wind_gust_ms NUMERIC(4,1) NULL,
|
||||
pressure_hpa NUMERIC(5,1) NULL,
|
||||
soil_temp_c NUMERIC(4,1) NULL,
|
||||
sunshine_s SMALLINT NULL,
|
||||
shortwave_avg_wm2 SMALLINT NULL,
|
||||
shortwave_max_wm2 SMALLINT NULL,
|
||||
fetched_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (region_code, forecast_at)
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
지수 테이블에 새 축 칼럼을 추가한다 (삭제 없음). 이어서 `seed/index_definition.json`을 `load_seed.py`로 다시 넣어야 새 비중이 반영된다.
|
||||
|
||||
```sql
|
||||
BEGIN;
|
||||
ALTER TABLE public.index_definition
|
||||
ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score
|
||||
ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
옛 정의로 계산된 `index_score`는 새 비중과 다르다. 지수를 새로 계산하려면 해당 지역의 `index_score` 행을 지우거나 `openmeteo_hourly`가 새로 갱신될 때까지 기다린다.
|
||||
|
||||
점수를 새 방식으로 다시 계산하려면 Redis의 `sky:*` 마커도 지운다 (`redis-cli --scan --pattern "sky:*" | xargs -r redis-cli del`).
|
||||
@@ -39,16 +39,46 @@ CREATE TABLE IF NOT EXISTS public.weather_daily (
|
||||
PRIMARY KEY (region_code, forecast_date)
|
||||
);
|
||||
|
||||
-- 지점별 층별 구름. 노을·일출 점수용 (구마다 해 지는 쪽·뜨는 쪽 20·50·100km 지점).
|
||||
-- 구별 층별 구름. 출처: Open-Meteo. 노을·일출 점수용 (구 중심에서 해 지는 쪽·뜨는 쪽 20·100km 지점).
|
||||
-- 점수에 쓰는 시각(그날 일몰·일출에 가장 가까운 정시) 값만 넣는다.
|
||||
-- 예전 구조(좌표 키)면 지우고 새로 만든다. 외부 API 에서 받은 임시 값이라 지워도 다시 받는다. 옛 방식 노을 점수도 같이 비워 다시 계산.
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'cloud_hourly')
|
||||
AND NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'cloud_hourly' AND column_name = 'region_code') THEN
|
||||
DROP TABLE public.cloud_hourly;
|
||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'sky_score') THEN
|
||||
DELETE FROM public.sky_score;
|
||||
END IF;
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE TABLE IF NOT EXISTS public.cloud_hourly (
|
||||
lat NUMERIC(5,2) NOT NULL, -- 소수 둘째 자리 반올림 값
|
||||
lon NUMERIC(5,2) NOT NULL,
|
||||
forecast_at TIMESTAMPTZ NOT NULL,
|
||||
region_code VARCHAR(10) NOT NULL, -- region.code
|
||||
kind SMALLINT NOT NULL, -- SkyType: 1=일몰 방향 2=일출 방향
|
||||
distance_km SMALLINT NOT NULL, -- 구 중심에서 떨어진 거리: 20(머리 위) 또는 100(해 쪽 지평선)
|
||||
forecast_at TIMESTAMPTZ NOT NULL, -- 일몰·일출에 가장 가까운 정시
|
||||
model SMALLINT NOT NULL, -- CloudModel: 1=ECMWF 2=GFS 3=JMA 4=ICON (모델끼리 비교해 노을 확신을 낸다)
|
||||
cloud_low SMALLINT NOT NULL, -- 낮은 구름 % (약 2km 아래)
|
||||
cloud_mid SMALLINT NOT NULL, -- 중간 구름 %
|
||||
cloud_high SMALLINT NOT NULL, -- 높은 구름 % (약 6km 위)
|
||||
PRIMARY KEY (lat, lon, forecast_at, model)
|
||||
PRIMARY KEY (region_code, kind, distance_km, forecast_at, model)
|
||||
);
|
||||
|
||||
-- 구별 3시간 간격 날씨 보조값. 출처: Open-Meteo (구 중심 좌표, 모델 지정 없음). 6시간마다 새로 받아 같은 (구, 시각) 줄을 덮어쓴다.
|
||||
-- forecast_at 은 3시간 구간의 끝 시각(GMT 0·3·6… = KST 0·3·6…). 일조·일사는 그 직전 3시간 값이고 나머지는 끝 시각 순간값이다.
|
||||
CREATE TABLE IF NOT EXISTS public.openmeteo_hourly (
|
||||
region_code VARCHAR(10) NOT NULL, -- region.code
|
||||
forecast_at TIMESTAMPTZ NOT NULL, -- 3시간 구간의 끝 시각
|
||||
uv_index NUMERIC(4,2) NULL, -- 자외선지수 (순간값)
|
||||
uv_index_clear_sky NUMERIC(4,2) NULL, -- 구름이 없다고 볼 때의 자외선지수 (순간값). uv_index / 이 값 = 구름이 가린 정도
|
||||
visibility_m INTEGER NULL, -- 가시거리 m (순간값)
|
||||
wind_gust_ms NUMERIC(4,1) NULL, -- 돌풍 m/s
|
||||
pressure_hpa NUMERIC(5,1) NULL, -- 해면기압 hPa (순간값)
|
||||
soil_temp_c NUMERIC(4,1) NULL, -- 지표면 온도 ℃ (순간값)
|
||||
sunshine_s SMALLINT NULL, -- 직전 3시간 일조 합 초 (0~10800)
|
||||
shortwave_avg_wm2 SMALLINT NULL, -- 직전 3시간 전천일사량 평균 W/m²
|
||||
shortwave_max_wm2 SMALLINT NULL, -- 직전 3시간 중 가장 센 1시간 값 W/m²
|
||||
fetched_at TIMESTAMPTZ NOT NULL, -- 받은 시각
|
||||
PRIMARY KEY (region_code, forecast_at)
|
||||
);
|
||||
|
||||
-- 미세먼지 측정소. 출처: 에어코리아 측정소 정보 (하루 1번 갱신).
|
||||
@@ -100,6 +130,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 (
|
||||
@@ -113,6 +146,9 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
wind_score SMALLINT NOT NULL,
|
||||
humidity_score SMALLINT NOT NULL,
|
||||
air_score SMALLINT NOT NULL,
|
||||
uv_score SMALLINT NOT NULL DEFAULT 0, -- 자외선·햇빛·가시거리은 비중이 있는 지수만 값이 있다 (없으면 0)
|
||||
sun_score SMALLINT NOT NULL DEFAULT 0,
|
||||
view_score SMALLINT NOT NULL DEFAULT 0,
|
||||
time_score SMALLINT NOT NULL,
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
@@ -120,6 +156,9 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (region_code, score_date, index_id)
|
||||
);
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -234,11 +273,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
has_detail BOOLEAN NOT NULL DEFAULT TRUE, -- 계산 근거 화면이 있는지
|
||||
description VARCHAR(100) NOT NULL, -- 무엇을 재는지
|
||||
windows JSONB NOT NULL, -- 계산 시간대 [{"from": 18, "to": 24}] 여러 개면 가장 좋은 쪽, {"around": "sunset"} 은 일몰 ±1시간
|
||||
weight_temp SMALLINT NOT NULL, -- 6요소 비중 (합 100)
|
||||
weight_temp SMALLINT NOT NULL, -- 요소 비중 (합 100)
|
||||
weight_rain SMALLINT NOT NULL,
|
||||
weight_wind SMALLINT NOT NULL,
|
||||
weight_humidity SMALLINT NOT NULL,
|
||||
weight_air SMALLINT NOT NULL,
|
||||
weight_uv SMALLINT NOT NULL DEFAULT 0, -- 자외선 (Open-Meteo). 해당 지수만 0 이 아니다
|
||||
weight_sun SMALLINT NOT NULL DEFAULT 0, -- 햇빛 = 해 난 비율 (Open-Meteo 일조)
|
||||
weight_view SMALLINT NOT NULL DEFAULT 0, -- 가시거리 (Open-Meteo)
|
||||
weight_time SMALLINT NOT NULL,
|
||||
factor_rules JSONB NOT NULL, -- 요소별 점수 규칙 {"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {...}, ...}
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
@@ -246,6 +288,9 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
@@ -287,11 +332,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,18 +1,36 @@
|
||||
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
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.air_crud import AirCRUD
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
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.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
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",
|
||||
@@ -21,7 +39,9 @@ _CLEANUP_SQL = [
|
||||
"DELETE FROM public.sky_score WHERE score_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
||||
"DELETE FROM public.cloud_hourly WHERE forecast_at < now() - interval '2 days'",
|
||||
"DELETE FROM public.event WHERE end_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 30",
|
||||
"DELETE FROM public.openmeteo_hourly WHERE forecast_at < now() - interval '7 days'",
|
||||
]
|
||||
_OPENMETEO_DAYS = 4
|
||||
|
||||
|
||||
async def cleanup_old_rows() -> ErrorType:
|
||||
@@ -50,8 +70,120 @@ async def refresh_weekend_rank(only_if_missing: bool = False) -> ErrorType:
|
||||
return err
|
||||
|
||||
|
||||
async def refresh_openmeteo_weather() -> ErrorType:
|
||||
"""전국 구 중심 좌표의 자외선·가시거리·돌풍·기압·일조·일사·지면온도를 3시간 구간으로 묶어 저장한다."""
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
by_point: dict[tuple[float, float], list[str]] = {}
|
||||
for r in regions:
|
||||
by_point.setdefault((round(float(r.lat), 2), round(float(r.lon), 2)), []).append(r.code)
|
||||
points = sorted(by_point)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
data = await fetch_weather(client, points, days=_OPENMETEO_DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[scheduler] refresh_openmeteo_weather: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR
|
||||
fetched_at = now_kst()
|
||||
rows = [
|
||||
{"region_code": code, "fetched_at": fetched_at, **slot}
|
||||
for point, d in zip(points, data)
|
||||
for slot in parse_weather(d)
|
||||
for code in by_point[point]
|
||||
]
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
|
||||
LOG.info(f"[scheduler] refresh_openmeteo_weather {len(points)} points rows {len(rows)}: {err.name}")
|
||||
return err
|
||||
|
||||
|
||||
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")
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -61,7 +64,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "모기, 가게 영업 여부, 자리 경쟁은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 오거나 바람이 쌩쌩, 오늘 야장은 접어요. 실내 포차로 피신!",
|
||||
"30": "앉을 순 있는데 춥거나 덥거나 눅눅해요. 겉옷이나 부채 필수!",
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
},
|
||||
{
|
||||
@@ -79,11 +87,14 @@
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 10,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -111,6 +122,10 @@
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -121,7 +136,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "잔디 상태, 공원 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 돗자리는 집에 고이 두기!",
|
||||
"30": "햇볕이 뜨겁거나 바람이 쌀쌀해요. 그늘이나 담요 챙기면 버틸 만!",
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
},
|
||||
{
|
||||
@@ -144,6 +164,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -185,7 +208,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "야구 경기 같은 이벤트는 아직 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 10° 아래거나 비가 와요. 치킨은 배달, 맥주는 집에서!",
|
||||
"30": "바깥은 좀 쌀쌀하거나 후덥지근해요. 가게 안쪽 자리 추천!",
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
},
|
||||
{
|
||||
@@ -208,6 +236,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -247,7 +278,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "길 공사, 조명은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 쏟아지거나 초미세먼지가 매우 나빠요. 오늘은 실내 걷기로!",
|
||||
"30": "걸을 순 있는데 춥거나 덥거나 공기가 탁해요. 짧게 한 바퀴만!",
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
},
|
||||
{
|
||||
@@ -282,6 +318,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 45,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -314,7 +353,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "집 방향과 주변 공사 먼지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "초미세먼지가 매우 나빠요. 창문 꼭 닫고 공기청정기 ON!",
|
||||
"30": "공기가 탁하거나 비가 와요. 5분만 짧게 열고 닫기!",
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
},
|
||||
{
|
||||
@@ -332,11 +376,14 @@
|
||||
"to": 12
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 20,
|
||||
"weight_humidity": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 5,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -365,6 +412,14 @@
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 50
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -380,7 +435,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "등산로 통제, 낙석 정보는 산림청 안내를 확인하세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이나 강풍 특보가 있어요. 오늘 산은 쉬어요!",
|
||||
"30": "산 위는 꽤 춥거나 더워요(6° 낮게 쳐요). 옷차림 단단히!",
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
},
|
||||
{
|
||||
@@ -404,6 +464,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -436,7 +499,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "황사·꽃가루 같은 하늘 먼지는 일부만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "곧 비가 와요. 지금 세차하면 물 낭비!",
|
||||
"30": "비 기운이 남아 있어요. 하루쯤 미루는 게 이득!",
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
},
|
||||
{
|
||||
@@ -459,6 +527,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -494,10 +565,20 @@
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 14
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 15
|
||||
}
|
||||
],
|
||||
"limit_description": "캠핑장 예약 상황은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 너무 세요. 텐트 날아가요!",
|
||||
"30": "밤에 춥거나 습해요. 침낭은 두꺼운 걸로!",
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
},
|
||||
{
|
||||
@@ -522,8 +603,11 @@
|
||||
"weight_temp": 35,
|
||||
"weight_rain": 20,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 20,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -545,6 +629,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -560,7 +648,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 상태는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "체감 35° 넘거나 비가 쏟아져요. 오늘은 러닝머신으로!",
|
||||
"30": "덥거나 눅눅해서 금방 지쳐요. 거리 줄이고 물 꼭!",
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
},
|
||||
{
|
||||
@@ -579,10 +672,13 @@
|
||||
}
|
||||
],
|
||||
"weight_temp": 5,
|
||||
"weight_rain": 15,
|
||||
"weight_rain": 10,
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 20,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 15,
|
||||
"weight_time": 45,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -603,6 +699,10 @@
|
||||
},
|
||||
"time": {
|
||||
"type": "moon"
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -613,7 +713,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "도시 불빛은 지역 평균으로만 반영해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "구름이 하늘을 꽉 덮었어요. 별은 다음 기회에!",
|
||||
"30": "달이 밝거나 하늘이 뿌예서 큰 별 몇 개만 보여요.",
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
},
|
||||
{
|
||||
@@ -640,6 +745,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -663,7 +771,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "25° 넘게 더워요. 국물보다 냉면이 당길 날!",
|
||||
"30": "국물이 살짝 생각나는 정도예요.",
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
},
|
||||
{
|
||||
@@ -686,6 +799,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -711,7 +827,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 판매량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 없어요. 파전은 비 오는 날을 기다려요!",
|
||||
"30": "하늘이 꾸물꾸물, 막걸리 생각이 살짝 나요.",
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
},
|
||||
{
|
||||
@@ -734,6 +855,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -757,7 +881,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침부터 22° 넘어요. 아직은 아아의 계절!",
|
||||
"30": "아침이 살짝 선선해요. 아아 들다 손 시릴 수도?",
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
},
|
||||
{
|
||||
@@ -775,11 +904,14 @@
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 35,
|
||||
"weight_wind": 20,
|
||||
"weight_humidity": 20,
|
||||
"weight_temp": 15,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 10,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 25,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -799,6 +931,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -808,8 +944,13 @@
|
||||
"value": 60
|
||||
}
|
||||
],
|
||||
"limit_description": "집 일조량은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"limit_description": "집 방향·그늘 일조량은 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 오늘 빨래는 실내 건조로!",
|
||||
"30": "눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요.",
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
},
|
||||
{
|
||||
@@ -832,6 +973,9 @@
|
||||
"weight_wind": 30,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -871,10 +1015,20 @@
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 10
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 15
|
||||
}
|
||||
],
|
||||
"limit_description": "자전거 도로 공사는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요!",
|
||||
"30": "맞바람이 세거나 기온이 애매해요. 짧은 코스만!",
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
},
|
||||
{
|
||||
@@ -896,11 +1050,14 @@
|
||||
"to": 20
|
||||
}
|
||||
],
|
||||
"weight_temp": 40,
|
||||
"weight_temp": 35,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -925,6 +1082,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -937,10 +1098,20 @@
|
||||
"field": "pm25",
|
||||
"op": ">=",
|
||||
"value": 75
|
||||
},
|
||||
{
|
||||
"field": "ground_c",
|
||||
"op": ">=",
|
||||
"value": 45
|
||||
}
|
||||
],
|
||||
"limit_description": "노면 온도는 실측하지 못해요",
|
||||
"sentences": {},
|
||||
"limit_description": "지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요",
|
||||
"sentences": {
|
||||
"0": "체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로!",
|
||||
"30": "덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요.",
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
},
|
||||
{
|
||||
@@ -963,6 +1134,9 @@
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 30,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -986,7 +1160,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실내 온도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아침이 15° 넘게 따뜻해요. 안경 김 걱정 없어요!",
|
||||
"30": "실내 들어갈 때 살짝 뿌예질 수 있어요.",
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
},
|
||||
{
|
||||
@@ -1009,6 +1188,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 35,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1032,7 +1214,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "피부 타입은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "선선하고 보송해요. 화장 하루 종일 버텨요!",
|
||||
"30": "오후쯤 살짝 번들거릴 수 있어요.",
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
},
|
||||
{
|
||||
@@ -1055,6 +1242,9 @@
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1080,7 +1270,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 주문량으로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "점심이 18° 아래로 선선해요. 냉면보다 국밥!",
|
||||
"30": "시원한 게 살짝 당기는 정도예요.",
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
},
|
||||
{
|
||||
@@ -1103,6 +1298,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 15,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1128,7 +1326,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "행사·공연 종료 시간은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "맑고 포근한 밤, 택시 금방 잡혀요.",
|
||||
"30": "조금 기다릴 수 있어요. 앱 미리 켜두기!",
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
},
|
||||
{
|
||||
@@ -1151,6 +1354,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1177,7 +1383,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "실제 배달 앱 지표로 검증하기 전이에요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "날씨 멀쩡해요. 배달 평소처럼 와요.",
|
||||
"30": "살짝 늦을 수 있어요.",
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
},
|
||||
{
|
||||
@@ -1195,11 +1406,14 @@
|
||||
"to": 10
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 5,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1224,6 +1438,10 @@
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
},
|
||||
"uv": {
|
||||
"zero": 8,
|
||||
"full": 2
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1234,7 +1452,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "식물 종류는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 소식이 있어요. 물 주기는 하늘에 맡겨요!",
|
||||
"30": "춥거나 더워요. 화분은 안으로, 물은 조금만.",
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
},
|
||||
{
|
||||
@@ -1252,11 +1475,14 @@
|
||||
"hours": 1
|
||||
}
|
||||
],
|
||||
"weight_temp": 15,
|
||||
"weight_temp": 10,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 10,
|
||||
"weight_time": 30,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1280,6 +1506,10 @@
|
||||
},
|
||||
"time": {
|
||||
"type": "sunset_score"
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
@@ -1290,7 +1520,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "장소 혼잡도는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비가 와요. 카메라는 쉬어요!",
|
||||
"30": "노을이 약하거나 하늘이 흐려요. 골목 사진 위주로!",
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
},
|
||||
{
|
||||
@@ -1313,6 +1548,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 10,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1348,7 +1586,12 @@
|
||||
}
|
||||
],
|
||||
"limit_description": "경기 일정과 시즌(3~10월)은 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "비 70% 넘어요. 우천 취소 각!",
|
||||
"30": "쌀쌀하거나 비 기운이 있어요. 담요랑 우비 챙겨요.",
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
},
|
||||
{
|
||||
@@ -1371,6 +1614,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1397,7 +1643,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사람마다 달라서 재미로 봐 주세요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 공부는… 내일의 내가 할게요!",
|
||||
"30": "나가고 싶은 마음 반, 공부 반이에요.",
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
},
|
||||
{
|
||||
@@ -1420,6 +1671,9 @@
|
||||
"weight_wind": 15,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 15,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1445,7 +1699,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "밤 공기가 좋아서 밖이 더 끌려요.",
|
||||
"30": "한 편 정도 볼 만해요.",
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
},
|
||||
{
|
||||
@@ -1468,6 +1727,9 @@
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
@@ -1491,7 +1753,12 @@
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "군밤 노점이 있는지는 반영하지 못해요",
|
||||
"sentences": {},
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 군밤은 조금 더 추워지면!",
|
||||
"30": "저녁이 선선해졌어요. 군밤 노점이 슬슬 생각나요.",
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
}
|
||||
]
|
||||
@@ -8,7 +8,7 @@ from typing import Optional
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.text import hour_label
|
||||
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "time")
|
||||
AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
||||
_WEEKDAY = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
@@ -25,6 +25,12 @@ class Hour:
|
||||
wind_ms: Optional[float]
|
||||
humidity: int
|
||||
sky: Sky
|
||||
# Open-Meteo 보조값. 3시간 구간에서 가져오며 수집 전이면 None.
|
||||
uv: Optional[float] = None
|
||||
sunshine_ratio: Optional[float] = None # 해 난 비율 0~1
|
||||
visibility_km: Optional[float] = None
|
||||
gust_ms: Optional[float] = None
|
||||
ground_c: Optional[float] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -134,6 +140,24 @@ def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
if uv is None:
|
||||
return _UNKNOWN, "자외선 정보 없음"
|
||||
return _linear(uv, rule["zero"], rule["full"]), f"자외선 {uv:.1f}"
|
||||
|
||||
|
||||
def sun_score(rule: dict, ratio: Optional[float]) -> tuple[int, str]:
|
||||
if ratio is None:
|
||||
return _UNKNOWN, "햇빛 정보 없음"
|
||||
return _linear(ratio, rule["zero"], rule["full"]), f"해 난 비율 {round(ratio * 100)}%"
|
||||
|
||||
|
||||
def view_score(rule: dict, km: Optional[float]) -> tuple[int, str]:
|
||||
if km is None:
|
||||
return _UNKNOWN, "가시거리 정보 없음"
|
||||
return _linear(km, rule["zero"], rule["full"]), f"가시거리 {km:.1f}km"
|
||||
|
||||
|
||||
def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
kind = rule["type"]
|
||||
if kind == "weekday":
|
||||
@@ -153,10 +177,14 @@ _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower":
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
|
||||
def axis_label(axis: str, rules: dict) -> str:
|
||||
"""축 값은 '이 각에 좋은 정도'라서, 라벨도 바깥으로 갈수록 좋아지는 쪽으로 읽히게 쓴다."""
|
||||
if axis in _OM_LABEL:
|
||||
return _OM_LABEL[axis]
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
@@ -180,8 +208,11 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
return None, None
|
||||
|
||||
|
||||
_FIELD_TEXT = {"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%"}
|
||||
_FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
|
||||
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
@@ -232,7 +263,7 @@ def _until(definition) -> str:
|
||||
def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Result]:
|
||||
"""지수 하나를 하루치로 계산한다. 시간대가 여러 개면 가장 좋은 쪽."""
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
for hours in windows:
|
||||
@@ -243,12 +274,20 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
raining = any(h.rain_type is not RainType.NONE for h in hours)
|
||||
winds = [h.wind_ms for h in hours if h.wind_ms is not None]
|
||||
feels = mean(h.feels_c for h in hours)
|
||||
uvs = [h.uv for h in hours if h.uv is not None]
|
||||
suns = [h.sunshine_ratio for h in hours if h.sunshine_ratio is not None]
|
||||
views = [h.visibility_km for h in hours if h.visibility_km is not None]
|
||||
gusts = [h.gust_ms for h in hours if h.gust_ms is not None]
|
||||
grounds = [h.ground_c for h in hours if h.ground_c is not None]
|
||||
scored = {
|
||||
"temp": temp_score(rules["temp"], feels),
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
@@ -259,6 +298,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
@@ -277,11 +317,11 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
weights = {a: getattr(definition, f"weight_{a}") for a in AXES}
|
||||
weights = {a: getattr(definition, f"weight_{a}", 0) for a in AXES}
|
||||
rules = definition.factor_rules
|
||||
until = _until(definition)
|
||||
after = next_fc or fc
|
||||
@@ -301,6 +341,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
"wind": wind_score(rules["wind"], None),
|
||||
"humidity": humidity,
|
||||
"air": air_score(None, None),
|
||||
**{a: (_UNKNOWN, f"{_OM_LABEL[a]} 정보가 없어 {_UNKNOWN}점으로 둬요") if weights[a] else (0, "") for a in _OM_LABEL},
|
||||
"time": time_score(rules["time"], ctx),
|
||||
}
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
|
||||
@@ -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,9 +2,9 @@ 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)
|
||||
DISTANCES_KM = (20, 100)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -14,11 +14,11 @@ class Layers:
|
||||
high: float
|
||||
|
||||
|
||||
def score(near20: Layers, near50: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20·50km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = (max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2
|
||||
def score(near20: Layers, far100: Layers) -> int:
|
||||
"""머리 위(20km)는 중·상층 구름이 알맞게 있어야 물들고, 먼 쪽(100km)이 막히면 햇빛이 못 들어와 전체가 깎인다."""
|
||||
canvas = max(near20.mid, near20.high)
|
||||
f_canvas = 0.3 if canvas < 10 else max(0.0, 1 - abs(canvas - 50) / 50)
|
||||
f_near = 1 - 0.8 * (near20.low + near50.low) / 200
|
||||
f_near = 1 - 0.8 * near20.low / 100
|
||||
light = 1 - min(far100.low + 0.5 * far100.mid, 100) / 100
|
||||
return round(100 * (0.75 * f_canvas + 0.25 * f_near) * (0.25 + 0.75 * light))
|
||||
|
||||
@@ -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,13 +73,40 @@ 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 reason(near20: Layers, near50: Layers, far100: Layers) -> str:
|
||||
def situation(near20: Layers, far100: Layers) -> SkySituation:
|
||||
"""하늘 상황 하나. reason() 과 같은 순서로 본다: 먼 쪽이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return SkySituation.COVERED
|
||||
if near20.low >= 60:
|
||||
return SkySituation.LOW_CLOUD
|
||||
canvas = max(near20.mid, near20.high)
|
||||
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, far100: Layers) -> str:
|
||||
"""score() 가 깎는 순서대로 본다: 먼 쪽 빛이 막혔나 → 머리 위 낮은 구름 → 물들 중·높은 구름의 양."""
|
||||
if far100.low + 0.5 * far100.mid >= 60:
|
||||
return "해 지는 쪽 먼 하늘이 구름에 막혀 빛이 못 들어와요"
|
||||
if (near20.low + near50.low) / 2 >= 60:
|
||||
if near20.low >= 60:
|
||||
return "낮은 구름이 머리 위를 덮어 붉은빛을 가려요"
|
||||
canvas = round((max(near20.mid, near20.high) + max(near50.mid, near50.high)) / 2)
|
||||
canvas = round(max(near20.mid, near20.high))
|
||||
if canvas < 10:
|
||||
return "물들 구름이 거의 없어 하늘이 은은하게 끝나요"
|
||||
if canvas > 85:
|
||||
|
||||
+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
|
||||
+85
-7
@@ -1,13 +1,15 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, 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}
|
||||
MODELS = {"jma_seamless": CloudModel.JMA, "icon_seamless": CloudModel.ICON}
|
||||
_ATTEMPTS = 3
|
||||
_BUDGET_SEC = 10.0 # 좌표가 많으면 여러 묶음을 동시에 보내 평소보다 조금 더 걸린다
|
||||
|
||||
|
||||
class OpenMeteoRequestFailed(RuntimeError):
|
||||
@@ -15,13 +17,30 @@ class OpenMeteoRequestFailed(RuntimeError):
|
||||
|
||||
|
||||
_CHUNK = 24
|
||||
WEATHER_VARS = (
|
||||
"uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl",
|
||||
"sunshine_duration", "shortwave_radiation", "soil_temperature_0cm",
|
||||
)
|
||||
SLOT_HOURS = 3
|
||||
# 해가 없는 밤 구간(21~06시 = 끝 시각 KST 0·3·6시)은 햇빛 값(일조·일사·자외선)을 저장하지 않는다.
|
||||
DARK_SLOT_END_KST = (0, 3, 6)
|
||||
_SUN_FIELDS = ("uv_index", "uv_index_clear_sky", "sunshine_s", "shortwave_avg_wm2", "shortwave_max_wm2")
|
||||
_KST_OFFSET = timedelta(hours=9)
|
||||
|
||||
|
||||
def is_dark_slot(end: datetime) -> bool:
|
||||
return (end.astimezone(timezone.utc) + _KST_OFFSET).hour in DARK_SLOT_END_KST
|
||||
|
||||
|
||||
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]:
|
||||
@@ -31,6 +50,10 @@ async def _fetch_chunk(client: httpx.AsyncClient, points: list[tuple[float, floa
|
||||
"hourly": "cloud_cover_low,cloud_cover_mid,cloud_cover_high",
|
||||
"models": ",".join(MODELS), "past_days": 1, "forecast_days": days, "timezone": "GMT",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
async def _get_forecast(client: httpx.AsyncClient, params: dict, point_count: int) -> list[dict]:
|
||||
for attempt in range(_ATTEMPTS):
|
||||
try:
|
||||
res = await client.get(URL, params=params)
|
||||
@@ -39,8 +62,29 @@ 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 {point_count} points: {last}")
|
||||
|
||||
|
||||
async def fetch_weather(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 4) -> list[dict]:
|
||||
"""좌표마다 시간별 자외선·가시거리·돌풍·기압·일조·일사·지면온도 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
|
||||
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
|
||||
|
||||
async def all_chunks() -> list[dict]:
|
||||
results = await asyncio.gather(*[_fetch_weather_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
return await guarded("openmeteo:weather", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
|
||||
|
||||
|
||||
async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
|
||||
params = {
|
||||
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
|
||||
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
|
||||
"hourly": ",".join(WEATHER_VARS), "wind_speed_unit": "ms", "forecast_days": days, "timezone": "GMT",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
@@ -55,3 +99,37 @@ def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
continue
|
||||
rows.append({"lat": lat, "lon": lon, "forecast_at": at, "model": model.value, "cloud_low": low, "cloud_mid": mid, "cloud_high": high})
|
||||
return rows
|
||||
|
||||
|
||||
def _round(v, digits: int = 0):
|
||||
return None if v is None else (round(v, digits) if digits else int(round(v)))
|
||||
|
||||
|
||||
def parse_weather(data: dict) -> list[dict]:
|
||||
"""시간별 응답을 3시간 구간(끝 시각 GMT 0·3·6…)으로 묶는다. 일조는 합, 일사는 평균·최대, 나머지는 끝 시각 값.
|
||||
직전 3시간이 다 있는 구간만 만든다 (응답 맨 앞처럼 일부만 있는 구간은 건너뜀). 밤 구간은 햇빛 값을 비운다."""
|
||||
h = data["hourly"]
|
||||
times = [datetime.fromisoformat(t).replace(tzinfo=timezone.utc) for t in h["time"]]
|
||||
index = {t: i for i, t in enumerate(times)}
|
||||
rows = []
|
||||
for end, i in index.items():
|
||||
if end.hour % SLOT_HOURS:
|
||||
continue
|
||||
span = [index.get(end - timedelta(hours=k)) for k in range(SLOT_HOURS)]
|
||||
if None in span:
|
||||
continue
|
||||
sun = [h["sunshine_duration"][j] for j in span]
|
||||
rad = [h["shortwave_radiation"][j] for j in span]
|
||||
row = {
|
||||
"forecast_at": end,
|
||||
"uv_index": _round(h["uv_index"][i], 2), "uv_index_clear_sky": _round(h["uv_index_clear_sky"][i], 2),
|
||||
"visibility_m": _round(h["visibility"][i]), "wind_gust_ms": _round(h["wind_gusts_10m"][i], 1),
|
||||
"pressure_hpa": _round(h["pressure_msl"][i], 1), "soil_temp_c": _round(h["soil_temperature_0cm"][i], 1),
|
||||
"sunshine_s": None if None in sun else int(round(sum(sun))),
|
||||
"shortwave_avg_wm2": None if None in rad else int(round(sum(rad) / len(rad))),
|
||||
"shortwave_max_wm2": None if None in rad else int(round(max(rad))),
|
||||
}
|
||||
if is_dark_slot(end):
|
||||
row |= dict.fromkeys(_SUN_FIELDS)
|
||||
rows.append(row)
|
||||
return rows
|
||||
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
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Optional
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import IndexDefinition, IndexScore, Region, WeatherDaily, WeatherHourly
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from crud.index_crud import IndexCRUD
|
||||
@@ -19,6 +19,7 @@ from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
|
||||
@@ -89,13 +90,48 @@ def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
return out
|
||||
|
||||
|
||||
def windows_for(defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly]) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다."""
|
||||
def _slot_end_hour(h: int) -> int:
|
||||
"""h시~h+1시를 덮는 3시간 구간의 끝 시각. 일조처럼 '직전 3시간 합'인 값에 쓴다 (7시→9시, 12시→15시)."""
|
||||
return (h + 3) // 3 * 3
|
||||
|
||||
|
||||
def _nearest_slot_end_hour(h: int) -> int:
|
||||
"""h시~h+1시의 한가운데에 가장 가까운 3시간 구간 끝 시각. 자외선·가시거리·돌풍·지표면 온도처럼 '끝 시각 순간값'에 쓴다 (9시→9시, 10시→12시)."""
|
||||
return int((h + 0.5) / 3 + 0.5) * 3
|
||||
|
||||
|
||||
def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoHourly]) -> dict:
|
||||
"""3시간 구간 값을 지수 계산 입력으로 바꾼다. 없으면 빈 값(점수에서 '정보 없음'). 밤 구간은 햇빛 값을 받지 않으므로 0으로 본다."""
|
||||
fields = {}
|
||||
if instant is not None:
|
||||
fields |= {
|
||||
"uv": 0.0 if is_dark_slot(instant.forecast_at) else float(instant.uv_index) if instant.uv_index is not None else None,
|
||||
"visibility_km": instant.visibility_m / 1000 if instant.visibility_m is not None else None,
|
||||
"gust_ms": float(instant.wind_gust_ms) if instant.wind_gust_ms is not None else None,
|
||||
"ground_c": float(instant.soil_temp_c) if instant.soil_temp_c is not None else None,
|
||||
}
|
||||
if covering is not None and is_dark_slot(covering.forecast_at):
|
||||
fields["sunshine_ratio"] = 0.0
|
||||
elif covering is not None and covering.sunshine_s is not None:
|
||||
fields["sunshine_ratio"] = min(covering.sunshine_s / 10800, 1.0)
|
||||
return fields
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([replace(_hour(r), hour=h) for h, r in zip(hours, rows) if r is not None])
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
by_om.get(start + timedelta(hours=_nearest_slot_end_hour(h))), by_om.get(start + timedelta(hours=_slot_end_hour(h)))
|
||||
))
|
||||
for h, r in zip(hours, rows) if r is not None
|
||||
])
|
||||
return out
|
||||
|
||||
|
||||
@@ -114,10 +150,11 @@ def _lookahead_days(defn) -> int:
|
||||
|
||||
|
||||
def day_result(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], daily: dict[date, DayForecast], ctx: Context, short: bool,
|
||||
by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
) -> Optional[Result]:
|
||||
"""short(오늘~모레)이거나 시간대가 시간별 예보로 다 채워지면 그대로 계산, 아니면 중기예보로 예상 점수."""
|
||||
windows = windows_for(defn, day, region, by_at)
|
||||
windows = windows_for(defn, day, region, by_at, by_om)
|
||||
if short or all(len(w) == len(h) for w, h in zip(windows, window_hours(defn, day, region))):
|
||||
return evaluate(defn, windows, replace(ctx, lookahead_rain_prob=lookahead_rain(defn, day, by_at)))
|
||||
fc = daily.get(day)
|
||||
@@ -201,6 +238,10 @@ class IndexService:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
_, daily_rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.week.daily(s, region.code, today, days[-1] + timedelta(days=2)))
|
||||
daily = {d.forecast_date: day_forecast(d) for d in daily_rows or []}
|
||||
om_err, om_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather.openmeteo_between(s, region.code, start, start + timedelta(days=DAYS + 2))
|
||||
)
|
||||
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
base_ctx = dict(
|
||||
@@ -209,10 +250,12 @@ class IndexService:
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at), today_ctx)
|
||||
weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx)
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
if by_om:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
@@ -232,7 +275,7 @@ class IndexService:
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS))
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
out.append({
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -140,35 +150,47 @@ def _nearest_hour(at: datetime) -> datetime:
|
||||
|
||||
|
||||
def _score_rows(region: Region, today: date, clouds: dict, now: datetime) -> list[dict]:
|
||||
first = sun_times(today, float(region.lat), float(region.lon))
|
||||
rows = []
|
||||
for kind, azimuth in ((SkyType.SUNSET, first.sunset_azimuth), (SkyType.SUNRISE, first.sunrise_azimuth)):
|
||||
pts = _points(region, azimuth)
|
||||
for kind in (SkyType.SUNSET, SkyType.SUNRISE):
|
||||
for i in range(DAYS):
|
||||
d = today + timedelta(days=i)
|
||||
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 = []
|
||||
for model in {k[2] for k in clouds}:
|
||||
layers = [clouds.get((p[0], p[1], model, hour)) for p in pts]
|
||||
per_model, highs, model_layers = [], [], []
|
||||
for model in {k[4] for k in clouds}:
|
||||
layers = [clouds.get((region.code, kind.value, km, hour, model)) for km in DISTANCES_KM]
|
||||
if None in layers:
|
||||
continue
|
||||
per_model.append(score(*layers))
|
||||
highs.append((layers[0].high + layers[1].high) / 2)
|
||||
highs.append(layers[0].high)
|
||||
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(len(DISTANCES_KM))))
|
||||
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
|
||||
@@ -198,7 +220,7 @@ class SkyService:
|
||||
LOG.error(f"[sky] spots {region.code}: {err.name}")
|
||||
near = nearest_spots(lat, lon, spots or [])
|
||||
first = sun_times(now.date(), lat, lon)
|
||||
plan = await self._plan(region, first.sunset_azimuth, sunsets, near, now)
|
||||
plan = await self._plan(region, sunsets, near, now)
|
||||
return ErrorType.SUCCESS, SkyView(
|
||||
region=region,
|
||||
sunset_azimuth=first.sunset_azimuth,
|
||||
@@ -209,7 +231,7 @@ class SkyService:
|
||||
plan=plan,
|
||||
)
|
||||
|
||||
async def _plan(self, region: Region, azimuth: int, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
async def _plan(self, region: Region, sunsets: list[SkyScore], spots: list[Spot], now: datetime) -> Optional[SkyPlan]:
|
||||
"""블루아워가 끝나기 전엔 오늘, 지나면 내일 노을로 결론을 낸다. 구름 층은 점수 계산 때 받은 값을 다시 읽는다."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
target, st = None, None
|
||||
@@ -220,15 +242,15 @@ class SkyService:
|
||||
break
|
||||
if target is None or st is None:
|
||||
return None
|
||||
pts = _points(region, azimuth)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, pts, _nearest_hour(st.sunset_at)))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.clouds_at(s, region.code, _nearest_hour(st.sunset_at)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
LOG.error(f"[sky] plan clouds {region.code}: {err.name}")
|
||||
by_point: dict[tuple[float, float], list[Layers]] = {}
|
||||
by_km: dict[int, list[Layers]] = {}
|
||||
for r in rows or []:
|
||||
by_point.setdefault((float(r.lat), float(r.lon)), []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||
layers = [mean_layers(by_point[p]) for p in pts if p in by_point]
|
||||
return build_plan(target, st, layers if len(layers) == len(pts) else None, spots, sunsets, now.date())
|
||||
if r.kind == SkyType.SUNSET.value:
|
||||
by_km.setdefault(r.distance_km, []).append(Layers(r.cloud_low, r.cloud_mid, r.cloud_high))
|
||||
layers = [mean_layers(by_km[km]) for km in DISTANCES_KM if km in by_km]
|
||||
return build_plan(target, st, layers if len(layers) == len(DISTANCES_KM) else None, spots, sunsets, now.date())
|
||||
|
||||
async def ranking(self) -> tuple[ErrorType, list[RankItem]]:
|
||||
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.ranking_regions(s))
|
||||
@@ -276,24 +298,32 @@ class SkyService:
|
||||
plan = {}
|
||||
for r in regions:
|
||||
st = sun_times(today, float(r.lat), float(r.lon))
|
||||
plan[r.code] = _points(r, st.sunset_azimuth) + _points(r, st.sunrise_azimuth)
|
||||
points = sorted({p for pts in plan.values() for p in pts})
|
||||
plan[r.code] = {SkyType.SUNSET: _points(r, st.sunset_azimuth), SkyType.SUNRISE: _points(r, st.sunrise_azimuth)}
|
||||
points = sorted({p for kinds in plan.values() for pts in kinds.values() for p in pts})
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
data = await fetch_clouds(client, points, days=DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[sky] {len(regions)} regions: {e}")
|
||||
return
|
||||
needed_hours = {
|
||||
_nearest_hour(at)
|
||||
for r in regions
|
||||
for i in range(DAYS)
|
||||
for st in [sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))]
|
||||
for at in (st.sunset_at, st.sunrise_at)
|
||||
}
|
||||
cloud_rows = [row for p, d in zip(points, data) for row in parse_clouds(p, d) if row["forecast_at"] in needed_hours]
|
||||
by_point: dict[tuple[float, float], dict[datetime, list[dict]]] = {}
|
||||
for p, d in zip(points, data):
|
||||
for row in parse_clouds(p, d):
|
||||
by_point.setdefault(p, {}).setdefault(row["forecast_at"], []).append(row)
|
||||
cloud_rows = []
|
||||
for r in regions:
|
||||
for kind, pts in plan[r.code].items():
|
||||
for i in range(DAYS):
|
||||
st = sun_times(today + timedelta(days=i), float(r.lat), float(r.lon))
|
||||
hour = _nearest_hour(st.sunset_at if kind is SkyType.SUNSET else st.sunrise_at)
|
||||
for km, p in zip(DISTANCES_KM, pts):
|
||||
cloud_rows += [
|
||||
{"region_code": r.code, "kind": kind.value, "distance_km": km, "forecast_at": hour, "model": row["model"],
|
||||
"cloud_low": row["cloud_low"], "cloud_mid": row["cloud_mid"], "cloud_high": row["cloud_high"]}
|
||||
for row in by_point.get(p, {}).get(hour, [])
|
||||
]
|
||||
clouds = {
|
||||
(float(r["lat"]), float(r["lon"]), r["model"], r["forecast_at"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
|
||||
(r["region_code"], r["kind"], r["distance_km"], r["forecast_at"], r["model"]): Layers(r["cloud_low"], r["cloud_mid"], r["cloud_high"])
|
||||
for r in cloud_rows
|
||||
}
|
||||
score_rows = [row for r in regions for row in _score_rows(r, today, clouds, now)]
|
||||
|
||||
@@ -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
|
||||
@@ -41,7 +42,7 @@ def anyio_backend():
|
||||
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
|
||||
)
|
||||
|
||||
@@ -67,8 +68,9 @@ async def _async(v):
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
@@ -95,6 +97,17 @@ def offline(monkeypatch):
|
||||
h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)}
|
||||
return _async([{"hourly": h} for _ in points])
|
||||
|
||||
def openmeteo_weather(client, points, days=4):
|
||||
start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
|
||||
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)]
|
||||
n = len(times)
|
||||
h = {
|
||||
"time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n,
|
||||
"wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n,
|
||||
"shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n,
|
||||
}
|
||||
return _async([{"hourly": h} for _ in points])
|
||||
|
||||
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
@@ -105,6 +118,7 @@ def offline(monkeypatch):
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
|
||||
monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather)
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import date, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -6,9 +7,12 @@ from httpx import ASGITransport, AsyncClient
|
||||
import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import slot_days, slot_label
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -78,3 +82,111 @@ 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)
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
"visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0,
|
||||
"sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600,
|
||||
}
|
||||
return row | over
|
||||
|
||||
|
||||
async def _put_om(rows):
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
|
||||
|
||||
|
||||
async def _laundry_sun(client):
|
||||
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
|
||||
index_id = next(i["index_id"] for i in items if i["code"] == "laundry")
|
||||
body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json()
|
||||
return {f["axis"]: f for f in body["factors"]}
|
||||
|
||||
|
||||
def test_slot_end_hours_for_covering_and_nearest_slot():
|
||||
hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26)
|
||||
assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27]
|
||||
assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27]
|
||||
|
||||
|
||||
def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot():
|
||||
day = date(2026, 10, 6)
|
||||
start = kst_midnight(day)
|
||||
by_at = {
|
||||
start + timedelta(hours=h): WeatherHourly(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
|
||||
)
|
||||
for h in range(7, 16)
|
||||
}
|
||||
by_om = {
|
||||
start + timedelta(hours=end): OpenMeteoHourly(
|
||||
forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0
|
||||
)
|
||||
for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800))
|
||||
}
|
||||
morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om)
|
||||
assert [h.uv for h in morning] == [1.0, 1.0]
|
||||
assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시)
|
||||
assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합)
|
||||
assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0
|
||||
no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0]
|
||||
assert all(h.uv is None and h.sunshine_ratio is None for h in no_om)
|
||||
|
||||
|
||||
def test_dark_slots_count_as_no_sun_not_unknown():
|
||||
day = date(2026, 10, 6)
|
||||
start = kst_midnight(day)
|
||||
by_at = {
|
||||
start + timedelta(hours=h): WeatherHourly(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
|
||||
)
|
||||
for h in (22, 23)
|
||||
}
|
||||
by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)}
|
||||
hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0]
|
||||
assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
laundry = await _laundry_sun(client)
|
||||
yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"]
|
||||
assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음"
|
||||
assert sum(f["weight"] for f in laundry.values()) == 100
|
||||
assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"]
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
|
||||
stars_id = next(i["index_id"] for i in items if i["code"] == "stars")
|
||||
stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"]
|
||||
assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes):
|
||||
today = kst_midnight(now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
before = await _laundry_sun(client)
|
||||
assert before["sun"]["value"] == 70
|
||||
await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)])
|
||||
after = await _laundry_sun(client)
|
||||
assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%"
|
||||
@@ -4,8 +4,8 @@ from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, temp_score,
|
||||
zero_rules_text,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
@@ -24,8 +24,8 @@ def _defn(**kw):
|
||||
return SimpleNamespace(**{**base, **kw})
|
||||
|
||||
|
||||
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky)
|
||||
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR, **extra):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky, **extra)
|
||||
|
||||
|
||||
def test_perfect_evening_scores_100():
|
||||
@@ -111,6 +111,52 @@ def test_moon_full_and_new():
|
||||
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
|
||||
|
||||
|
||||
def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
|
||||
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
|
||||
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
|
||||
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
|
||||
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
|
||||
|
||||
|
||||
def _uv_defn():
|
||||
rules = _defn().factor_rules | {"uv": {"zero": 8, "full": 2}}
|
||||
return _defn(weight_temp=25, weight_humidity=5, weight_uv=10, factor_rules=rules)
|
||||
|
||||
|
||||
def test_weighted_uv_axis_lowers_score_when_uv_is_high_and_is_unknown_when_missing():
|
||||
low = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0)]], CTX)
|
||||
high = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
|
||||
missing = evaluate(_uv_defn(), [[_h(19, wind=1.0)]], CTX)
|
||||
assert low.score == 100 and low.factors["uv"] == 100
|
||||
assert high.factors["uv"] == 0 and high.score < 80
|
||||
assert missing.factors["uv"] == 70 and missing.notes["uv"] == "자외선 정보 없음"
|
||||
|
||||
|
||||
def test_unweighted_new_axes_do_not_affect_score_and_use_max_uv_in_window():
|
||||
plain = evaluate(_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
|
||||
assert plain.score == 100 and plain.factors["uv"] == 0
|
||||
window = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0), _h(20, wind=1.0, uv=9.0)]], CTX)
|
||||
assert window.factors["uv"] == 0
|
||||
|
||||
|
||||
def test_gust_and_ground_temperature_zero_rules():
|
||||
gust = _defn(zero_rules=[{"field": "gust_ms", "op": ">=", "value": 15}])
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=16.0)]], CTX).score == 0
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100
|
||||
assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다
|
||||
ground = [{"field": "ground_c", "op": ">=", "value": 45}]
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이라 0점"
|
||||
|
||||
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
|
||||
|
||||
|
||||
@@ -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,113 @@
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, parse_weather
|
||||
|
||||
SLOTS_PER_REGION = 31 # 96시간 응답에서 직전 3시간이 다 있는 3시간 구간 (끝 시각 03시 ~ 다음다음다음날 21시)
|
||||
|
||||
|
||||
def _hourly(**over):
|
||||
times = [f"2026-10-06T{h:02d}:00" for h in range(9)]
|
||||
base = {
|
||||
"time": times,
|
||||
"uv_index": [round(0.1 * h, 1) for h in range(9)],
|
||||
"uv_index_clear_sky": [round(0.2 * h, 1) for h in range(9)],
|
||||
"visibility": [10000.0 + h for h in range(9)],
|
||||
"wind_gusts_10m": [1.0 + h for h in range(9)],
|
||||
"pressure_msl": [1000.0 + h for h in range(9)],
|
||||
"sunshine_duration": [0, 600, 1200, 1800, 2400, 3000, 3600, 3600, 3600],
|
||||
"shortwave_radiation": [0, 10, 20, 30, 40, 60, 100, 200, 300],
|
||||
"soil_temperature_0cm": [10.0 + h for h in range(9)],
|
||||
}
|
||||
return {"hourly": base | over}
|
||||
|
||||
|
||||
def test_three_hour_slots_sum_sunshine_and_average_radiation():
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}
|
||||
assert sorted(rows) == [3, 6] # 00시 구간은 앞 두 시간이 없어 만들지 않는다
|
||||
assert rows[3]["sunshine_s"] == 600 + 1200 + 1800
|
||||
assert rows[3]["shortwave_avg_wm2"] == 20 and rows[3]["shortwave_max_wm2"] == 30
|
||||
assert rows[6]["sunshine_s"] == 2400 + 3000 + 3600
|
||||
assert rows[6]["shortwave_avg_wm2"] == 67 and rows[6]["shortwave_max_wm2"] == 100
|
||||
|
||||
|
||||
def test_other_values_are_taken_at_slot_end():
|
||||
row = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}[6]
|
||||
assert row["uv_index"] == 0.6 and row["uv_index_clear_sky"] == 1.2
|
||||
assert row["visibility_m"] == 10006 and row["wind_gust_ms"] == 7.0
|
||||
assert row["pressure_hpa"] == 1006.0 and row["soil_temp_c"] == 16.0
|
||||
|
||||
|
||||
def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values():
|
||||
sun = [0, 600, None, 1800, 2400, 3000, 3600, 3600, 3600]
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly(sunshine_duration=sun))}
|
||||
assert rows[3]["sunshine_s"] is None and rows[3]["uv_index"] == 0.3
|
||||
assert rows[6]["sunshine_s"] == 9000
|
||||
|
||||
|
||||
def test_dark_slots_drop_sun_values_but_keep_others():
|
||||
times = [f"2026-10-06T{h:02d}:00" for h in range(24)]
|
||||
full = {k: [1.0] * 24 for k in ("uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl", "soil_temperature_0cm")}
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather({"hourly": {"time": times, "sunshine_duration": [600] * 24, "shortwave_radiation": [50] * 24} | full})}
|
||||
dark = {15, 18, 21} # GMT 끝 시각 = KST 0·3·6시 (21~06시). KST 21시 구간(18~21시)은 남긴다
|
||||
assert sorted(rows) == [3, 6, 9, 12, 15, 18, 21]
|
||||
for hour, row in rows.items():
|
||||
sun = (row["uv_index"], row["uv_index_clear_sky"], row["sunshine_s"], row["shortwave_avg_wm2"], row["shortwave_max_wm2"])
|
||||
assert (sun == (None,) * 5) is (hour in dark)
|
||||
assert row["visibility_m"] == 1 and row["soil_temp_c"] == 1.0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_stores_every_region_and_is_repeatable(offline):
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
|
||||
first = await _counts()
|
||||
assert first["regions"] == 256 and first["rows"] == 256 * SLOTS_PER_REGION and first["slots"] == SLOTS_PER_REGION
|
||||
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
|
||||
assert (await _counts())["rows"] == first["rows"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_failure_returns_error_and_stores_nothing(offline, monkeypatch):
|
||||
async def fail(client, points, days=4):
|
||||
raise OpenMeteoRequestFailed("boom")
|
||||
|
||||
monkeypatch.setattr(jobs, "fetch_weather", fail)
|
||||
assert await jobs.refresh_openmeteo_weather() is ErrorType.EXTERNAL_API_ERROR
|
||||
assert (await _counts())["rows"] == 0
|
||||
|
||||
|
||||
async def _counts() -> dict:
|
||||
err, res = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT count(*) AS rows, count(DISTINCT region_code) AS regions, count(DISTINCT forecast_at) AS slots FROM openmeteo_hourly"))
|
||||
)
|
||||
return dict(res.one()._mapping)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upsert_keeps_previous_value_when_new_value_is_missing():
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
|
||||
at = datetime(2026, 10, 6, 3, tzinfo=timezone.utc)
|
||||
first = {
|
||||
"region_code": "1144000000", "forecast_at": at, "fetched_at": at, "uv_index": 3.0, "uv_index_clear_sky": 3.5,
|
||||
"visibility_m": 20000, "wind_gust_ms": 4.0, "pressure_hpa": 1015.0, "soil_temp_c": 18.0,
|
||||
"sunshine_s": 3600, "shortwave_avg_wm2": 300, "shortwave_max_wm2": 400,
|
||||
}
|
||||
second = first | {"fetched_at": at + timedelta(hours=6), "uv_index": None, "sunshine_s": None, "visibility_m": 15000}
|
||||
|
||||
for row in (first, second):
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s, r=row: WeatherCRUD().upsert_openmeteo(s, [r])])
|
||||
|
||||
err, res = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT uv_index, sunshine_s, visibility_m, fetched_at FROM openmeteo_hourly WHERE region_code = '1144000000'"))
|
||||
)
|
||||
row = res.one()
|
||||
assert float(row.uv_index) == 3.0 and row.sunshine_s == 3600 # 비어 온 값은 이전 값 유지
|
||||
assert row.visibility_m == 15000 # 값이 있으면 덮어씀
|
||||
assert row.fetched_at == second["fetched_at"]
|
||||
@@ -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"] == 2
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -104,14 +106,38 @@ 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) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
return _fake_response(points, days)
|
||||
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
await client.get("/v1/sky", params={"region": "1144000000"})
|
||||
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'"))
|
||||
)
|
||||
rows = rows.all()
|
||||
assert len(rows) == 2 * 2 * 3 * 2
|
||||
assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)}
|
||||
assert {r.model for r in rows} == {3, 4}
|
||||
assert len({r.forecast_at for r in rows}) == 6
|
||||
@@ -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)
|
||||
@@ -10,21 +10,21 @@ CLEAR = Layers(0, 0, 0)
|
||||
|
||||
def test_high_clouds_overhead_and_clear_horizon_is_best():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert score(canvas, canvas, CLEAR) == 100
|
||||
assert score(canvas, CLEAR) == 100
|
||||
|
||||
|
||||
def test_clear_sky_is_only_soft():
|
||||
assert grade(score(CLEAR, CLEAR, CLEAR)) is SkyGrade.SOFT
|
||||
assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT
|
||||
|
||||
|
||||
def test_low_clouds_toward_sun_block_the_light():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert grade(score(canvas, canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
||||
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
|
||||
|
||||
|
||||
def test_overcast_low_clouds_is_gray():
|
||||
gray = Layers(low=100, mid=100, high=100)
|
||||
assert grade(score(gray, gray, gray)) is SkyGrade.GRAY
|
||||
assert grade(score(gray, gray)) is SkyGrade.GRAY
|
||||
|
||||
|
||||
def test_confidence_from_model_spread():
|
||||
@@ -43,15 +43,15 @@ 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():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), Layers(80, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR, CLEAR)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
@@ -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) is SkySituation.FEW
|
||||
assert situation(glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(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_openmeteo_weather, refresh_weekend_rank
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -20,8 +20,12 @@ 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.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True)
|
||||
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, openmeteo job at 03·09·15·21:10 KST")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
Reference in new issue
Block a user