Merge branch 'main' into feat/open-meteo
This commit is contained in:
commit
aa05d870a2
80 files changed
+4893
-351
No files matched your search
@@ -183,6 +183,7 @@ class IndexDefinition(Base):
|
||||
limit_description: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
@@ -205,6 +206,7 @@ class IndexScore(Base):
|
||||
zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
notes: Mapped[dict] = mapped_column(JSONB)
|
||||
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
slots: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
||||
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
@@ -227,6 +229,9 @@ class Place(Base):
|
||||
reason: Mapped[str] = mapped_column(String(60))
|
||||
best_time: Mapped[str] = mapped_column(String(30))
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
lat: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
lon: Mapped[Optional[Decimal]] = mapped_column(Numeric(8, 5), nullable=True)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
@@ -280,6 +285,8 @@ class Article(Base):
|
||||
show_from: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
show_until: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger, default=0)
|
||||
image_url: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
image_credit: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)
|
||||
|
||||
|
||||
class Post(Base):
|
||||
@@ -288,6 +295,7 @@ class Post(Base):
|
||||
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
feed_date: Mapped[date] = mapped_column(Date)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
scope: Mapped[str] = mapped_column(String(2), default="00")
|
||||
post_type: Mapped[int] = mapped_column(SmallInteger)
|
||||
ref_type: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
ref_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
|
||||
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
|
||||
@@ -9,13 +9,13 @@ from common.database.model.models import Post
|
||||
|
||||
|
||||
class FeedCRUD:
|
||||
async def day(self, s: AsyncSession, day: date) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.deleted.is_(False)).order_by(Post.position)
|
||||
async def day(self, s: AsyncSession, day: date, scopes: list[str]) -> list[Post]:
|
||||
stmt = select(Post).where(Post.feed_date == day, Post.scope.in_(scopes), Post.deleted.is_(False)).order_by(Post.position, Post.scope)
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def positions(self, s: AsyncSession, day: date) -> set[int]:
|
||||
"""그날 이미 만든 카드 번호. 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return set((await s.scalars(select(Post.position).where(Post.feed_date == day))).all())
|
||||
async def positions(self, s: AsyncSession, day: date) -> set[tuple[str, int]]:
|
||||
"""그날 이미 만든 (scope, 카드 번호). 지운 카드도 넣어 다시 만들지 않게 한다."""
|
||||
return {(scope, pos) for scope, pos in (await s.execute(select(Post.scope, Post.position).where(Post.feed_date == day))).all()}
|
||||
|
||||
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if rows:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -34,6 +34,13 @@ class IndexCRUD:
|
||||
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
||||
return await s.scalar(stmt)
|
||||
|
||||
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
||||
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
||||
stmt = select(IndexScore.index_id).where(
|
||||
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
||||
).limit(1)
|
||||
return (await s.scalar(stmt)) is not None
|
||||
|
||||
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
|
||||
@@ -26,14 +26,18 @@ class WeekCRUD:
|
||||
if rows:
|
||||
await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"]))
|
||||
|
||||
async def places(self, s: AsyncSession, sido_code: str) -> list[Place]:
|
||||
stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order)
|
||||
async def places_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[Place]:
|
||||
stmt = select(Place).where(Place.lat.between(lat - dlat, lat + dlat), Place.lon.between(lon - dlon, lon + dlon))
|
||||
return list((await s.scalars(stmt)).all())
|
||||
|
||||
async def all_places(self, s: AsyncSession) -> list[Place]:
|
||||
return list((await s.scalars(select(Place).where(Place.lat.is_not(None)))).all())
|
||||
|
||||
async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
await s.execute(delete(Place))
|
||||
if rows:
|
||||
await s.execute(insert(Place).values(rows))
|
||||
# asyncpg 는 한 문장에 인자 32767개까지라 나눠 넣는다.
|
||||
for i in range(0, len(rows), 1000):
|
||||
await s.execute(insert(Place).values(rows[i:i + 1000]))
|
||||
|
||||
async def events(self, s: AsyncSession, sido_codes: list[str], since: date, until: date) -> list[Event]:
|
||||
stmt = select(Event).where(Event.sido_code.in_(sido_codes), Event.end_date >= since, Event.start_date <= until)
|
||||
|
||||
@@ -153,12 +153,14 @@ CREATE TABLE IF NOT EXISTS public.index_score (
|
||||
zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL)
|
||||
notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...}
|
||||
estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수
|
||||
slots JSONB NOT NULL DEFAULT '{}', -- 오늘만: 구간별 점수 {"morning"|"day"|"evening"|"night"|"early": {score, summary, factors, zero_reason, notes}}. 각 시간대와 안 겹치는 구간은 없음
|
||||
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;
|
||||
ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
-- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다.
|
||||
CREATE TABLE IF NOT EXISTS public.post (
|
||||
@@ -175,7 +177,9 @@ CREATE TABLE IF NOT EXISTS public.post (
|
||||
end_at TIMESTAMPTZ NULL, -- NULL = 그날 끝까지
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed ON public.post (feed_date, position) WHERE deleted = FALSE;
|
||||
ALTER TABLE public.post ADD COLUMN IF NOT EXISTS scope VARCHAR(2) NOT NULL DEFAULT '00'; -- '00'=전국, 그 외 시도 코드(region.code 앞 2자리). 좋아요·댓글이 이 단위로 나뉜다
|
||||
DROP INDEX IF EXISTS public.uq_post_feed;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date, position, scope) WHERE deleted = FALSE;
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
@@ -286,11 +290,13 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
zero_rules JSONB NOT NULL DEFAULT '[]', -- 바로 0점 조건 [{"field": "rain_prob", "op": ">=", "value": 80}]. 화면 문장은 여기서 만든다
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
);
|
||||
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;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
@@ -303,18 +309,24 @@ CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0 -- 0 해 지는 쪽이 트인 곳(먼저), 1 그 밖
|
||||
);
|
||||
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭).
|
||||
-- 날씨 맞춤 데이트 명소 (주말·행사 탭). 구 중심에서 가까운 곳을 고른다.
|
||||
CREATE TABLE IF NOT EXISTS public.place (
|
||||
place_id SERIAL PRIMARY KEY,
|
||||
region_code VARCHAR(10) NOT NULL,
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원")
|
||||
area VARCHAR(20) NOT NULL, -- 동네 묶음 ("성수", "연남·망원") 또는 구 이름
|
||||
name VARCHAR(40) NOT NULL,
|
||||
is_outdoor BOOLEAN NOT NULL, -- 맑으면 야외, 비 오면 실내를 먼저
|
||||
icon VARCHAR(30) NOT NULL,
|
||||
reason VARCHAR(60) NOT NULL, -- "돗자리 펴고 낮 피크닉"
|
||||
best_time VARCHAR(30) NOT NULL, -- "낮 12시~4시"
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
lat NUMERIC(8,5) NULL, -- 시드가 늘 채운다
|
||||
lon NUMERIC(8,5) NULL,
|
||||
image_url VARCHAR(500) NULL -- TourAPI firstimage
|
||||
);
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
|
||||
ALTER TABLE public.place ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
|
||||
|
||||
-- 축제·행사.
|
||||
CREATE TABLE IF NOT EXISTS public.event (
|
||||
@@ -374,5 +386,9 @@ CREATE TABLE IF NOT EXISTS public.article (
|
||||
body JSONB NOT NULL, -- 문단 목록
|
||||
show_from DATE NULL, -- 계절 소식이 보이는 기간 (NULL = 늘)
|
||||
show_until DATE NULL,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
image_url VARCHAR(200) NULL, -- 사진 (frontend/public/season/, NULL = 아이콘)
|
||||
image_credit VARCHAR(60) NULL -- 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0"), 표기가 필요 없으면 NULL
|
||||
);
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_url VARCHAR(200) NULL;
|
||||
ALTER TABLE public.article ADD COLUMN IF NOT EXISTS image_credit VARCHAR(60) NULL;
|
||||
@@ -131,6 +131,7 @@ class TopIndex(WebPacketProtocol):
|
||||
score: int
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -171,6 +172,8 @@ class BandArticle(WebPacketProtocol):
|
||||
title: str
|
||||
meta: str
|
||||
icon: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class Bands(WebPacketProtocol):
|
||||
|
||||
@@ -5,7 +5,8 @@ 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, ScoreBand, TrendPoint
|
||||
from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, SlotPoint, TrendPoint
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.index_calc import AXES, axis_label, zero_rules_text
|
||||
from services.index_service import IndexItem, IndexService, slot_label
|
||||
|
||||
@@ -18,10 +19,11 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)")
|
||||
@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)")
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
@@ -32,8 +34,9 @@ async def list_indices(
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered)
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
@router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거")
|
||||
|
||||
@@ -14,6 +14,12 @@ class TrendPoint(WebPacketProtocol):
|
||||
estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수")
|
||||
|
||||
|
||||
class SlotPoint(WebPacketProtocol):
|
||||
slot: str = Field(description="morning / day / evening / night")
|
||||
label: str = Field(description="아침 / 낮 / 저녁 / 밤")
|
||||
score: int
|
||||
|
||||
|
||||
class IndexSummary(WebPacketProtocol):
|
||||
index_id: int
|
||||
code: str
|
||||
@@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol):
|
||||
rank: int
|
||||
summary: str
|
||||
trend: list[TrendPoint] = []
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slot: Optional[str] = Field(default=None, description="score 가 어느 구간 점수인지 (지금 구간)")
|
||||
slots: list[SlotPoint] = Field(default=[], description="오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class Res_IndexList(Res_WebPacketProtocol):
|
||||
region_code: Optional[str] = None
|
||||
day: Optional[date] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)")
|
||||
top3: list[IndexSummary] = []
|
||||
items: list[IndexSummary] = []
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ class ArticleSummary(WebPacketProtocol):
|
||||
title: str
|
||||
read_minutes: int
|
||||
icon: str
|
||||
image: Optional[str] = None # 있으면 아이콘 대신 사진
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ저작자 · CC BY-SA 4.0")
|
||||
|
||||
|
||||
class Res_SeasonWeek(Res_WebPacketProtocol):
|
||||
|
||||
@@ -12,7 +12,8 @@ router = APIRouter(prefix="/v1/season", tags=["season"])
|
||||
|
||||
|
||||
def _summary(a: Article) -> ArticleSummary:
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon)
|
||||
return ArticleSummary(article_id=a.article_id, code=a.code, category=ArticleCategory(a.category), title=a.title, read_minutes=a.read_minutes, icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
|
||||
|
||||
@router.get("/week", response_model=Res_SeasonWeek, response_model_exclude_none=True, summary="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||
|
||||
@@ -97,7 +97,7 @@ async def get_watch_summary(
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
res.top = [_top(i) for i in board.items[:TOP_N]]
|
||||
res.top = [_top(i) for i in board.ranked[:TOP_N]]
|
||||
codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS]
|
||||
by_code = {i.definition.code: i for i in board.items}
|
||||
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
|
||||
|
||||
@@ -32,6 +32,9 @@ class PlaceData(WebPacketProtocol):
|
||||
reason: str
|
||||
best_time: str
|
||||
is_good: bool
|
||||
distance_km: float # 구 중심에서 떨어진 거리
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
|
||||
|
||||
|
||||
class Res_PlaceList(Res_WebPacketProtocol):
|
||||
|
||||
@@ -9,7 +9,7 @@ from common.utils.kma_time import now_kst
|
||||
from router.v1.week.protocol import (
|
||||
DayData, EventData, PlaceData, Res_EventList, Res_PlaceList, Res_Week, Res_WeekRanking, WeekRankDay, WeekRankItem,
|
||||
)
|
||||
from services.week_service import WeekService, image_credit
|
||||
from services.week_service import WeekService, image_credit, place_credit
|
||||
from services.weekend_rank import WeekendRank, rank_days, weekend_days
|
||||
|
||||
router = APIRouter(prefix="/v1/week", tags=["week"])
|
||||
@@ -45,20 +45,20 @@ async def get_week_ranking() -> Res_WeekRanking:
|
||||
])
|
||||
|
||||
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소")
|
||||
@router.get("/place/list", response_model=Res_PlaceList, response_model_exclude_none=True, summary="날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)")
|
||||
async def list_places(
|
||||
region: str = Query(...), day: Optional[date] = Query(None, description="기본은 오늘"), area: Optional[str] = Query(None),
|
||||
service: WeekService = Depends(),
|
||||
) -> Res_PlaceList:
|
||||
target = day or now_kst().date()
|
||||
err, items, areas = await service.places(region, target, area)
|
||||
err, items, areas, rainy = await service.places(region, target, area)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_PlaceList(result=error_info(err))
|
||||
rainy = any(not i.place.is_outdoor and i.is_good for i in items)
|
||||
return Res_PlaceList(areas=areas, rainy=rainy, places=[
|
||||
PlaceData(
|
||||
place_id=i.place.place_id, area=i.place.area, name=i.place.name, is_outdoor=i.place.is_outdoor, icon=i.place.icon,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good,
|
||||
reason=i.place.reason, best_time=i.place.best_time, is_good=i.is_good, distance_km=i.distance_km,
|
||||
image=i.place.image_url, image_credit=place_credit(i.place),
|
||||
)
|
||||
for i in items
|
||||
])
|
||||
|
||||
@@ -21,10 +21,10 @@ 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.week_service import collect_events, drop_known
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다
|
||||
_POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
|
||||
_POPGA_BATCH = 100
|
||||
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
|
||||
_EVENTS_TTL_SEC = 7 * 86400
|
||||
@@ -98,13 +98,14 @@ async def refresh_openmeteo_weather() -> ErrorType:
|
||||
|
||||
|
||||
async def build_today_feed() -> ErrorType:
|
||||
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
||||
"""그날 피드 칸(전국·시도별)을 넣고, 구별 피드 캐시를 비운다."""
|
||||
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await clear_feed_cache()
|
||||
return err
|
||||
|
||||
|
||||
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
|
||||
rows = await drop_known(rows)
|
||||
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)
|
||||
@@ -147,7 +148,7 @@ async def refresh_popups() -> ErrorType:
|
||||
|
||||
|
||||
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")
|
||||
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND kind = 4 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
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""TourAPI 분류(lclsSystm3)에서 데이트에 맞는 관광지를 전국으로 모아 seed/place_tourapi.csv 로 쓴다 (일회성, 다시 돌리면 덮어씀).
|
||||
|
||||
손으로 고른 seed/place.csv 와 같은 곳(contentid)은 뺀다.
|
||||
실행: docker exec o2o-weather-backend-1 python scripts/fetch_date_places.py
|
||||
"""
|
||||
import asyncio
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from common.utils.geo import haversine_km # noqa: E402
|
||||
from scripts.load_seed import SEED_DIR, read_regions # noqa: E402
|
||||
from services.external.data_go_kr import get_all_items # noqa: E402
|
||||
|
||||
LIST_URL = "https://apis.data.go.kr/B551011/KorService2/areaBasedList2"
|
||||
OUT = os.path.join(SEED_DIR, "place_tourapi.csv")
|
||||
_BASE = {"_type": "json", "MobileOS": "ETC", "MobileApp": "nalssigak", "arrange": "A"}
|
||||
# lclsSystm3 → (야외, 아이콘, 한 줄 이유, 추천 시간). 이유는 분류에서 나오는 말만 쓴다.
|
||||
CATEGORIES = {
|
||||
"VE030100": (True, "picnic", "공원 산책·피크닉", "낮 12시~4시"),
|
||||
"VE010200": (True, "stars", "전망대에서 보는 경치·야경", "해 진 뒤"),
|
||||
"VE010300": (True, "stars", "다리 위 야경 산책", "해 진 뒤"),
|
||||
"VE040300": (True, "walk", "둘레길 함께 걷기", "선선한 오후"),
|
||||
"NA010200": (True, "walk", "숲길 산책", "오전 10시~"),
|
||||
"NA020200": (True, "walk", "호숫가 산책", "선선한 저녁"),
|
||||
"NA040700": (True, "garden", "수목원·정원 꽃길 산책", "오전 10시~"),
|
||||
"VE040100": (True, "photo", "골목·카페거리 구경", "오후 2시~"),
|
||||
"NA020900": (True, "sunset", "바닷가 산책", "노을 무렵"),
|
||||
"VE020400": (False, "rain", "비 와도 실내 아쿠아리움", "비 오는 오후"),
|
||||
"VE070600": (False, "bulb", "비 오면 미술관으로", "비 오는 날"),
|
||||
}
|
||||
FIELDS = ["source", "region_name", "area", "name", "is_outdoor", "icon", "reason", "best_time", "lat", "lon", "image_url"]
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
return re.sub(r"\s+", " ", text or "").strip()
|
||||
|
||||
|
||||
def _manual_ids() -> set[str]:
|
||||
with open(os.path.join(SEED_DIR, "place.csv"), encoding="utf-8") as f:
|
||||
return {r["source"].removeprefix("tourapi:") for r in csv.DictReader(f) if r["source"].startswith("tourapi:")}
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
regions = read_regions()
|
||||
skip = _manual_ids()
|
||||
rows: dict[str, dict] = {}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
for code, (outdoor, icon, reason, best_time) in CATEGORIES.items():
|
||||
params = {**_BASE, "lclsSystm1": code[:2], "lclsSystm2": code[:4], "lclsSystm3": code}
|
||||
items = await get_all_items(client, LIST_URL, params, page_size=500)
|
||||
kept = 0
|
||||
for it in items:
|
||||
cid, title = str(it["contentid"]), _clean(it.get("title", ""))
|
||||
if cid in skip or cid in rows or not title or not it.get("mapx") or not it.get("mapy"):
|
||||
continue
|
||||
lat, lon = round(float(it["mapy"]), 5), round(float(it["mapx"]), 5)
|
||||
if not (33 <= lat <= 39 and 124 <= lon <= 132):
|
||||
print(f"skip {cid} {title}: 좌표가 국내 밖 ({lat}, {lon})")
|
||||
continue
|
||||
near = min(regions, key=lambda r: haversine_km(lat, lon, r["lat"], r["lon"]))
|
||||
rows[cid] = {
|
||||
"source": f"tourapi:{cid}", "region_name": near["name"], "area": near["short_name"], "name": title[:60],
|
||||
"is_outdoor": int(outdoor), "icon": icon, "reason": reason, "best_time": best_time, "lat": lat, "lon": lon,
|
||||
"image_url": (it.get("firstimage") or "").replace("http://", "https://", 1),
|
||||
}
|
||||
kept += 1
|
||||
print(f"{code}: {len(items)} -> {kept}")
|
||||
out = sorted(rows.values(), key=lambda r: (r["region_name"], r["name"]))
|
||||
with open(OUT, "w", encoding="utf-8", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=FIELDS)
|
||||
w.writeheader()
|
||||
w.writerows(out)
|
||||
print(f"place {len(out)} -> {OUT}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -1,11 +1,17 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
|
||||
|
||||
SEED = os.path.join(ROOT, "seed", "index_definition.json")
|
||||
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
PRIO = {1: "상", 2: "중", 3: "하"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%"), "gust_ms": ("돌풍", "m/s"), "ground_c": ("지면 온도", "°")}
|
||||
|
||||
@@ -70,7 +76,13 @@ def zero(z):
|
||||
return s + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None),
|
||||
def air(r):
|
||||
if r["full"] > r["zero"]:
|
||||
return f"초미세먼지 높을수록 좋음 ({r['zero']}㎍/㎥=0점 → {r['full']}㎍/㎥=100점)"
|
||||
return "초미세먼지 낮을수록 좋음"
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
@@ -91,27 +103,28 @@ def main() -> None:
|
||||
P("- 최종 점수 = 비중대로 섞은 점수 × (0.75 + 0.25 × 가장 낮은 요소 점수 ÷ 100). 비중 0%인 요소는 '가장 낮은 요소'에서 뺍니다. 가장 낮은 요소가 0점이면 25%가 깎입니다.")
|
||||
P("- '0점 조건'에 걸리면 0점, '최대 N점' 조건에 걸리면 N점을 넘지 못합니다.")
|
||||
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
|
||||
P("- 미세먼지는 모든 각이 같은 규칙입니다: 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.\n")
|
||||
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
|
||||
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
|
||||
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
|
||||
P("## 한눈에 보기\n")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
|
||||
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
P(f"| {x['sort_order']} | {x['name']} | `{x['code']}` | {CAT[x['category']]} | {PRIO[x['priority']]} | {' / '.join(win(w) for w in x['windows'])} | "
|
||||
+ " | ".join(f"{x['weight_' + a]}%" for a in ("temp", "rain", "wind", "humidity", "air", "time"))
|
||||
+ f" | {'○' if x['is_fun'] else ''} | {'○' if x['is_core'] else ''} |")
|
||||
P("\n## 각별 자세히\n")
|
||||
for x in sorted(d, key=lambda x: x["sort_order"]):
|
||||
P(f"### {x['name']} (`{x['code']}`)\n")
|
||||
P(f"- 설명: {x['description']}")
|
||||
P(f"- 분류: {CAT[x['category']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 분류: {CAT[x['category']]} · 중요도 {PRIO[x['priority']]} · 아이콘 `{x['icon']}` · 재미 각 {'예' if x['is_fun'] else '아니오'} · 계절 핵심 {'예' if x['is_core'] else '아니오'} · 계산 근거 화면 {'있음' if x['has_detail'] else '없음'}")
|
||||
P(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||
P("- 요소별 규칙 (비중):")
|
||||
for key, label, fn in AX:
|
||||
w = x.get("weight_" + key, 0)
|
||||
if key in _OPTIONAL and not w:
|
||||
continue
|
||||
rule = "초미세먼지 낮을수록 좋음" if fn is None else fn(x["factor_rules"][key])
|
||||
rule = fn(x["factor_rules"].get(key, {"zero": 75, "full": 15}))
|
||||
P(f" - {label} {w}%: {rule}")
|
||||
zs = [zero(z) for z in x["zero_rules"]]
|
||||
P(f"- 점수 깎이는 조건: {', '.join(zs) if zs else '없음'}")
|
||||
|
||||
@@ -56,10 +56,12 @@ async def main() -> int:
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "sort_order": 0 if r["west_open"] == "1" else 1}
|
||||
for r in _read("sunset_spot.csv")
|
||||
]
|
||||
# 손으로 고른 place.csv 와 TourAPI 에서 모은 place_tourapi.csv (scripts/fetch_date_places.py). source 는 출처 기록용.
|
||||
places = [
|
||||
{"region_code": code_by_name[r["region_name"]], "area": r["area"], "name": r["name"], "is_outdoor": r["is_outdoor"] == "1",
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r["sort_order"])}
|
||||
for r in _read("place.csv")
|
||||
"icon": r["icon"], "reason": r["reason"], "best_time": r["best_time"], "sort_order": int(r.get("sort_order") or 0),
|
||||
"lat": float(r["lat"]), "lon": float(r["lon"]), "image_url": r.get("image_url") or None}
|
||||
for r in _read("place.csv") + _read("place_tourapi.csv")
|
||||
]
|
||||
# 직접 넣는 행사 (TourAPI 에 없는 것). source_id 가 없는 줄만 이 파일로 바꿔 넣는다.
|
||||
events = [
|
||||
@@ -70,7 +72,8 @@ async def main() -> int:
|
||||
]
|
||||
articles = [
|
||||
{**a, "show_from": date.fromisoformat(a["show_from"]) if a["show_from"] else None,
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None}
|
||||
"show_until": date.fromisoformat(a["show_until"]) if a["show_until"] else None,
|
||||
"image_url": a.get("image_url"), "image_credit": a.get("image_credit")}
|
||||
for a in _json("article.json")
|
||||
]
|
||||
weeks = _json("season_week.json")
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"title": "설악산 첫 단풍, 절정은 언제?",
|
||||
"read_minutes": 3,
|
||||
"icon": "maple",
|
||||
"image_url": "/season/maple.jpg",
|
||||
"image_credit": "ⓒJoycekim77 · CC BY-SA 3.0",
|
||||
"show_from": "2026-09-20",
|
||||
"show_until": "2026-10-25",
|
||||
"body": [
|
||||
@@ -20,6 +22,8 @@
|
||||
"title": "하늘공원 억새가 반짝이는 시간",
|
||||
"read_minutes": 2,
|
||||
"icon": "sheaf",
|
||||
"image_url": "/season/reed.jpg",
|
||||
"image_credit": "ⓒJocelyndurrey · CC BY-SA 4.0",
|
||||
"show_from": "2026-09-25",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -34,6 +38,8 @@
|
||||
"title": "대관령 첫서리, 서울은 한 달 뒤",
|
||||
"read_minutes": 2,
|
||||
"icon": "snow",
|
||||
"image_url": "/season/frost.jpg",
|
||||
"image_credit": "ⓒSally V · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-01",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -77,6 +83,7 @@
|
||||
"title": "노을은 왜 해 지고 15분 뒤가 더 붉을까?",
|
||||
"read_minutes": 3,
|
||||
"icon": "sunset",
|
||||
"image_url": "/season/sunset.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -91,6 +98,7 @@
|
||||
"title": "비 확률 30%면 우산을 챙겨야 할까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "umbrella",
|
||||
"image_url": "/season/umbrella.jpg",
|
||||
"show_from": null,
|
||||
"show_until": null,
|
||||
"body": [
|
||||
@@ -251,6 +259,7 @@
|
||||
"title": "햇밤, 바로 먹을까 두었다 먹을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "chestnut",
|
||||
"image_url": "/season/chestnut_new.jpg",
|
||||
"show_from": "2026-09-15",
|
||||
"show_until": "2026-10-31",
|
||||
"body": [
|
||||
@@ -281,6 +290,8 @@
|
||||
"title": "은행 냄새 나는 길, 언제까지일까",
|
||||
"read_minutes": 2,
|
||||
"icon": "fallen_leaf",
|
||||
"image_url": "/season/ginkgo.jpg",
|
||||
"image_credit": "ⓒKorea.net · CC BY-SA 2.0",
|
||||
"show_from": "2026-10-10",
|
||||
"show_until": "2026-11-15",
|
||||
"body": [
|
||||
@@ -296,6 +307,8 @@
|
||||
"title": "군고구마가 생각나는 첫 추위",
|
||||
"read_minutes": 2,
|
||||
"icon": "sweet_potato",
|
||||
"image_url": "/season/sweet_potato.jpg",
|
||||
"image_credit": "ⓒ국립국어원 · CC BY-SA 2.0 KR",
|
||||
"show_from": "2026-10-15",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -311,6 +324,7 @@
|
||||
"title": "노지 귤이 나오기 시작해요",
|
||||
"read_minutes": 2,
|
||||
"icon": "tangerine",
|
||||
"image_url": "/season/tangerine.jpg",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-12-31",
|
||||
"body": [
|
||||
@@ -326,6 +340,8 @@
|
||||
"title": "부사 사과가 나오는 때",
|
||||
"read_minutes": 2,
|
||||
"icon": "apple",
|
||||
"image_url": "/season/apple_fuji.jpg",
|
||||
"image_credit": "ⓒAomorikuma · CC BY-SA 4.0",
|
||||
"show_from": "2026-10-20",
|
||||
"show_until": "2026-11-30",
|
||||
"body": [
|
||||
@@ -341,6 +357,7 @@
|
||||
"title": "김장, 언제 하면 좋을까?",
|
||||
"read_minutes": 2,
|
||||
"icon": "kimchi",
|
||||
"image_url": "/season/kimjang.jpg",
|
||||
"show_from": "2026-11-01",
|
||||
"show_until": "2026-12-15",
|
||||
"body": [
|
||||
|
||||
@@ -70,7 +70,8 @@
|
||||
"60": "꽤 괜찮은 저녁! 바람만 살랑 불어 주면 딱이에요.",
|
||||
"80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻"
|
||||
},
|
||||
"sort_order": 1
|
||||
"sort_order": 1,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "picnic",
|
||||
@@ -146,7 +147,8 @@
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
"sort_order": 2,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "chimaek",
|
||||
@@ -218,7 +220,8 @@
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
"sort_order": 3,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "walk",
|
||||
@@ -288,7 +291,8 @@
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
"sort_order": 4,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "vent",
|
||||
@@ -363,7 +367,8 @@
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
"sort_order": 5,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "hiking",
|
||||
@@ -449,7 +454,8 @@
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
"sort_order": 6,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "carwash",
|
||||
@@ -521,7 +527,8 @@
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
"sort_order": 7,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "camping",
|
||||
@@ -595,7 +602,8 @@
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
"sort_order": 8,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "running",
|
||||
@@ -666,7 +674,8 @@
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
"sort_order": 9,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "stars",
|
||||
@@ -731,7 +740,8 @@
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
"sort_order": 10,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jjamppong",
|
||||
@@ -789,7 +799,8 @@
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
"sort_order": 11,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "makgeolli",
|
||||
@@ -845,7 +856,8 @@
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
"sort_order": 12,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "iced_hot",
|
||||
@@ -899,7 +911,8 @@
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
"sort_order": 13,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "laundry",
|
||||
@@ -963,7 +976,8 @@
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
"sort_order": 14,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "bike",
|
||||
@@ -1049,7 +1063,8 @@
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
"sort_order": 15,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "dog",
|
||||
@@ -1128,7 +1143,8 @@
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
"sort_order": 16,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "glasses",
|
||||
@@ -1182,7 +1198,8 @@
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
"sort_order": 17,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "makeup",
|
||||
@@ -1236,7 +1253,8 @@
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
"sort_order": 18,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "naengmyeon",
|
||||
@@ -1292,7 +1310,8 @@
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
"sort_order": 19,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "taxi",
|
||||
@@ -1348,7 +1367,8 @@
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
"sort_order": 20,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "delivery",
|
||||
@@ -1405,7 +1425,8 @@
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
"sort_order": 21,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "garden",
|
||||
@@ -1478,7 +1499,8 @@
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
"sort_order": 22,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "photo",
|
||||
@@ -1546,7 +1568,8 @@
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
"sort_order": 23,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "baseball",
|
||||
@@ -1612,7 +1635,8 @@
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
"sort_order": 24,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "study",
|
||||
@@ -1669,7 +1693,8 @@
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
"sort_order": 25,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "netflix",
|
||||
@@ -1725,7 +1750,8 @@
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
"sort_order": 26,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "chestnut",
|
||||
@@ -1779,6 +1805,524 @@
|
||||
"60": "손이 시려요. 따끈한 군밤 한 봉지!",
|
||||
"80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰"
|
||||
},
|
||||
"sort_order": 27
|
||||
"sort_order": 27,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "golf",
|
||||
"name": "골프각",
|
||||
"icon": "golf",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 7시~오후 5시, 필드에서 라운딩하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 7,
|
||||
"to": 12
|
||||
},
|
||||
{
|
||||
"from": 12,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 25,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 3,
|
||||
"limit": 9
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 12
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "골프장 예약, 잔디 상태, 낙뢰는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 너무 세요. 오늘은 스크린으로!",
|
||||
"30": "춥거나 덥거나 바람이 공을 흔들어요. 타수는 기대 말기!",
|
||||
"60": "칠 만해요! 바람 방향만 잘 읽으면 돼요.",
|
||||
"80": "15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳"
|
||||
},
|
||||
"sort_order": 28,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jipkok",
|
||||
"name": "집콕각",
|
||||
"icon": "jipkok",
|
||||
"category": 3,
|
||||
"is_fun": true,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 6시, 나가기 싫어 집에 있고 싶은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 18
|
||||
}
|
||||
],
|
||||
"weight_temp": 30,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 20,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "away",
|
||||
"lo": 15,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "wet"
|
||||
},
|
||||
"wind": {
|
||||
"type": "strong"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "higher"
|
||||
},
|
||||
"air": {
|
||||
"zero": 15,
|
||||
"full": 75
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "재미로 보는 지수예요",
|
||||
"sentences": {
|
||||
"0": "밖이 너무 좋아요. 집에만 있기 아까운 날!",
|
||||
"30": "나갈까 말까, 소파와 밀당 중이에요.",
|
||||
"60": "덥거나 춥거나 공기가 탁해요. 집이 최고!",
|
||||
"80": "비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️"
|
||||
},
|
||||
"sort_order": 29,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "fishing",
|
||||
"name": "낚시각",
|
||||
"icon": "fishing",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "새벽 5~9시·오후 4~7시, 물가에서 낚시하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 5,
|
||||
"to": 9
|
||||
},
|
||||
{
|
||||
"from": 16,
|
||||
"to": 19
|
||||
}
|
||||
],
|
||||
"weight_temp": 25,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 35,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 12,
|
||||
"hi": 24
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": ">=",
|
||||
"value": 10
|
||||
},
|
||||
{
|
||||
"field": "warning",
|
||||
"op": "==",
|
||||
"value": "wind"
|
||||
}
|
||||
],
|
||||
"limit_description": "물때·수온·파도 높이는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비 70% 넘거나 바람이 거세요. 물가는 위험, 오늘은 쉬어요!",
|
||||
"30": "바람에 찌가 흔들리거나 손이 시려요. 짧게 손맛만!",
|
||||
"60": "물가 나가볼 만해요! 새벽엔 쌀쌀하니 겉옷 챙기기.",
|
||||
"80": "12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣"
|
||||
},
|
||||
"sort_order": 30,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "drive",
|
||||
"name": "드라이브각",
|
||||
"icon": "drive",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 10시~오후 5시, 창문 열고 드라이브하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 10,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 30,
|
||||
"weight_wind": 5,
|
||||
"weight_humidity": 5,
|
||||
"weight_air": 15,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 15,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 15,
|
||||
"hi": 25
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 6,
|
||||
"limit": 15
|
||||
},
|
||||
"humidity": {
|
||||
"type": "range",
|
||||
"lo": 30,
|
||||
"hi": 60,
|
||||
"best": 35
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"view": {
|
||||
"zero": 5,
|
||||
"full": 20
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70,
|
||||
"cap": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "길 막힘과 도로 공사는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 쏟아져요. 와이퍼만 바쁜 날, 드라이브는 다음에!",
|
||||
"30": "하늘이 뿌옇거나 비 기운이 있어요. 가까운 곳만 슬쩍!",
|
||||
"60": "달릴 만해요! 창문 반쯤 열고 음악 크게.",
|
||||
"80": "공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗"
|
||||
},
|
||||
"sort_order": 31,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "kite",
|
||||
"name": "연날리기각",
|
||||
"icon": "kite",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 4시, 연 날리기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 20,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 45,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 8,
|
||||
"hi": 22
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "moderate"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 70
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 70
|
||||
},
|
||||
{
|
||||
"field": "gust_ms",
|
||||
"op": ">=",
|
||||
"value": 13
|
||||
},
|
||||
{
|
||||
"field": "wind_ms",
|
||||
"op": "<",
|
||||
"value": 1,
|
||||
"cap": 30
|
||||
}
|
||||
],
|
||||
"limit_description": "전깃줄·나무 없는 넓은 곳인지는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "비가 오거나 돌풍이 불어요. 연이 날아가 버려요!",
|
||||
"30": "바람이 너무 약하거나 너무 세요. 뛰어다녀야 겨우 떠요.",
|
||||
"60": "연 띄울 만해요! 실은 넉넉하게 감아 가요.",
|
||||
"80": "초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁"
|
||||
},
|
||||
"sort_order": 32,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "waterplay",
|
||||
"name": "물놀이각",
|
||||
"icon": "waterplay",
|
||||
"category": 1,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 11시~오후 5시, 바다·계곡에서 물놀이하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 11,
|
||||
"to": 17
|
||||
}
|
||||
],
|
||||
"weight_temp": 40,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 20,
|
||||
"weight_view": 0,
|
||||
"weight_time": 5,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 27,
|
||||
"hi": 34,
|
||||
"best": 30
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 12
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 60
|
||||
},
|
||||
"sun": {
|
||||
"zero": 0.2,
|
||||
"full": 0.8
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_prob",
|
||||
"op": ">=",
|
||||
"value": 60
|
||||
},
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": "<",
|
||||
"value": 20
|
||||
}
|
||||
],
|
||||
"limit_description": "수온, 파도 높이, 계곡 물살은 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "체감 20° 아래거나 비 소식이 있어요. 물놀이는 여름에!",
|
||||
"30": "물에 들어가면 으슬으슬해요. 발만 담그기!",
|
||||
"60": "물놀이 괜찮아요! 그늘막이랑 선크림 챙기기.",
|
||||
"80": "30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️"
|
||||
},
|
||||
"sort_order": 33,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "kimjang",
|
||||
"name": "김장각",
|
||||
"icon": "kimchi",
|
||||
"category": 3,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 9시~오후 4시, 김장하기 좋은 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 9,
|
||||
"to": 16
|
||||
}
|
||||
],
|
||||
"weight_temp": 50,
|
||||
"weight_rain": 25,
|
||||
"weight_wind": 10,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 5,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 10,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 0,
|
||||
"hi": 10,
|
||||
"best": 5
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "calm",
|
||||
"ok": 4,
|
||||
"limit": 10
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"sat": 100,
|
||||
"sun": 100,
|
||||
"holiday": 100,
|
||||
"default": 50
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "feels_c",
|
||||
"op": ">=",
|
||||
"value": 18
|
||||
}
|
||||
],
|
||||
"limit_description": "배추 작황과 값, 집집마다 김장 날짜는 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "아직 18° 넘어요. 지금 담그면 김치가 금방 쉬어요!",
|
||||
"30": "조금 이르거나 손이 꽁꽁 얼어요. 날을 다시 골라 봐요.",
|
||||
"60": "김장할 만해요! 고무장갑 안에 면장갑 하나 더.",
|
||||
"80": "0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬"
|
||||
},
|
||||
"sort_order": 34,
|
||||
"priority": 3
|
||||
}
|
||||
]
|
||||
+11
-11
@@ -1,11 +1,11 @@
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10
|
||||
region_name,area,name,is_outdoor,icon,reason,best_time,sort_order,lat,lon,source
|
||||
서울 성동구,성수,서울숲,1,picnic,돗자리 펴고 낮 피크닉,낮 12시~4시,1,37.54307,127.04180,tourapi:128611
|
||||
서울 성동구,성수,성수 갤러리 골목,0,photo,작은 전시와 팝업을 걸어서,비 오는 오후,2,37.54320,127.05660,tourapi:2930901
|
||||
서울 마포구,연남·망원,경의선숲길,1,walk,해 질 녘 산책 데이트,저녁 6시 이후,3,37.56170,126.92306,tourapi:2553819
|
||||
서울 마포구,연남·망원,망원한강공원,1,sunset,노을 명소 1위 강 건너 서쪽,노을 무렵,4,37.55140,126.90050,tourapi:1059638
|
||||
서울 영등포구,여의도,여의도한강공원,1,chimaek,한강 치맥,저녁 7시,5,37.52640,126.93361,tourapi:1059479
|
||||
서울 영등포구,여의도,더현대 서울,0,calendar,비 와도 하루 종일 실내,비 오는 날,6,37.52710,126.92730,tourapi:2708109
|
||||
서울 송파구,잠실,석촌호수,1,walk,호수 한 바퀴 2.5km,선선한 저녁,7,37.50792,127.09894,tourapi:754052
|
||||
서울 송파구,잠실,롯데월드 아쿠아리움,0,rain,비 오는 날 실내 데이트,비 오는 오후,8,37.51417,127.10407,tourapi:2476731
|
||||
서울 종로구,북촌·익선,북촌한옥마을,1,photo,맑은 날 한옥 골목 사진,오전 10시~,9,37.57905,126.98671,tourapi:126537
|
||||
서울 종로구,북촌·익선,국립현대미술관 서울관,0,bulb,비 오면 미술관으로,비 오는 날,10,37.57865,126.98000,tourapi:1934593
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -154,3 +154,24 @@ region_name,name,description,lat,lon,west_open,source
|
||||
충남 홍성군,궁리포구,바다 너머 서쪽이 트임 · 충남 홍성군,36.58845,126.45721,1,tourapi:1937784
|
||||
충남 홍성군,남당노을전망대,바다 너머 서쪽이 트임 · 충남 홍성군,36.54428,126.4656,1,tourapi:3065226
|
||||
충남 홍성군,어사리 노을공원,바다 너머 서쪽이 트임 · 충남 홍성군,36.55615,126.46837,1,tourapi:2678991
|
||||
광주 동구,서석대,높은 곳에서 서쪽이 트임 · 광주 북구,35.14415,126.98900,1,tourapi:2614826
|
||||
세종 세종특별자치시,고운뜰공원,높은 곳에서 보는 도심 노을 · 세종,36.51255,127.23913,0,tourapi:2758467
|
||||
세종 세종특별자치시,청벽산,높은 곳에서 금강 너머 노을 · 충남 공주시,36.42857,127.22094,0,tourapi:2755172
|
||||
충남 금산군,대둔산도립공원(금산),낙조대까지 산행 · 충남 금산군,36.13746,127.34167,0,tourapi:128001
|
||||
충북 단양군,양방산전망대,높은 곳에서 남한강 너머 노을 · 충북 단양군,36.96837,128.38202,0,tourapi:1626685
|
||||
충북 음성군,백야둘레길,물가 노을 · 충북 음성군,36.96775,127.60332,0,tourapi:2782402
|
||||
강원 강릉시,강릉항여객터미널,육지 쪽 산으로 지는 해 · 강원 강릉시,37.77289,128.95289,0,tourapi:3546554
|
||||
경남 밀양시,낙동강철교전망대,물가 노을 · 경남 김해시,35.37512,128.82347,0,tourapi:2782619
|
||||
경북 영덕군,영덕조각공원,풍력단지 언덕 노을 · 경북 영덕군,36.42193,129.41761,0,tourapi:128718
|
||||
경기 연천군,임진강 주상절리,석양에 붉어지는 절벽 · 경기 연천군,38.01993,127.01545,0,tourapi:2569474
|
||||
강원 춘천시,구봉산 전망대 카페거리,높은 곳에서 서쪽이 트임 · 강원 춘천시,37.89250,127.77700,1,tourapi:129686
|
||||
경북 상주시,경천섬(경천섬공원),물가 노을 · 경북 상주시,36.45323,128.25506,0,tourapi:2756567
|
||||
강원 속초시,영랑호,물가 노을 · 강원 속초시,38.21422,128.58075,0,tourapi:127565;web:https://lady.khan.co.kr/finance/article/6492
|
||||
경남 함안군,함안 악양루,남강 절벽 위 노을 · 경남 함안군,35.33513,128.39847,0,tourapi:702331;web:https://www.knnews.co.kr/news/articleView.php?idxno=1425
|
||||
전북 완주군,비비정,만경강 낙조 · 전북 완주군,35.89901,127.06849,0,osm;web:https://jjan.kr/article/20251209500596
|
||||
경기 여주시,흥원창,남한강 물가 노을 · 강원 원주시,37.22665,127.75142,0,osm;web:https://xn--ok0b236bp0a.com/place/26309
|
||||
경북 영양군,선바위,강가 바위 위 석양 · 경북 영양군,36.60598,129.07461,0,osm;web:https://weekly.khan.co.kr/article/201111221629101
|
||||
경북 경주시,금장대,형산강 너머 서쪽 노을 · 경북 경주시,35.86066,129.20093,1,osm;web:https://www.telltrip.com/domestic-travel/gyeongju-geumjangdae-night-view-travel-tips/
|
||||
전남 강진군,강진만생태공원,물가 노을 · 전남 강진군,34.61961,126.77254,0,osm;web:https://m.seoul.co.kr/news/2022/11/24/20221124018005
|
||||
충북 영동군,함벽정,금강가 정자에서 보는 낙조 · 충북 영동군,36.13424,127.67067,0,osm;web:https://www.nhis.or.kr/static/alim/paper/oldpaper/202209/sub/14.html
|
||||
강원 평창군,육백마지기,높은 곳에서 서쪽이 트임 · 강원 평창군,37.41025,128.50836,1,osm;web:https://v.daum.net/v/Wr8Os0nbtv
|
||||
|
@@ -0,0 +1,27 @@
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
||||
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
NIGHT_END_HOUR = 5
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if NIGHT_END_HOUR <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]:
|
||||
"""그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다."""
|
||||
out: dict[str, set[int]] = {s: set() for s in SLOTS}
|
||||
start = datetime.combine(day, time(0), tzinfo=KST)
|
||||
for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR):
|
||||
out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h)
|
||||
return out
|
||||
@@ -18,6 +18,13 @@ _FALL_FLOOR = exp(-0.5)
|
||||
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||
_TEMP_PLATEAU = 2
|
||||
_HUMIDITY_PLATEAU = 5
|
||||
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
|
||||
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
|
||||
|
||||
|
||||
def rank_score(score: int, priority: int) -> float:
|
||||
"""각 순위를 정하는 값 = 점수 × 중요도 가중치."""
|
||||
return score * PRIORITY_WEIGHT[priority]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -108,7 +115,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
return _range(t, lo, hi, rule.get("best"), rule.get("plateau", _TEMP_PLATEAU), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
if rule["type"] == "away":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
@@ -154,10 +161,15 @@ def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
return 50, f"{note}, 이 각엔 상관없어 50점으로 둬요"
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str]) -> tuple[int, str]:
|
||||
_AIR_RULE = {"zero": 75, "full": 15}
|
||||
|
||||
|
||||
def air_score(pm25: Optional[int], label: Optional[str], rule: Optional[dict] = None) -> tuple[int, str]:
|
||||
"""rule 이 없으면 맑을수록 좋음. 집콕각처럼 탁할수록 좋은 각은 {"zero": 15, "full": 75} 로 뒤집는다."""
|
||||
if pm25 is None:
|
||||
return _UNKNOWN, f"미세먼지 정보가 없어 {_UNKNOWN}점으로 둬요"
|
||||
return _linear(pm25, 75, 15), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
rule = rule or _AIR_RULE
|
||||
return _linear(pm25, rule["zero"], rule["full"]), f"초미세먼지 {pm25}㎍/㎥{', ' + label if label else ''}"
|
||||
|
||||
|
||||
def uv_score(rule: dict, uv: Optional[float]) -> tuple[int, str]:
|
||||
@@ -208,7 +220,8 @@ def axis_label(axis: str, rules: dict) -> str:
|
||||
if axis == "rain":
|
||||
return "비 옴" if rules["rain"]["dir"] == "wet" else "비 안 옴"
|
||||
if axis == "air":
|
||||
return "공기 맑음"
|
||||
rule = rules.get("air", _AIR_RULE)
|
||||
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
|
||||
@@ -304,7 +317,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"rain": rain_score(rules["rain"], max_prob, raining, until if max_prob > own_prob else ""),
|
||||
"wind": wind_score(rules["wind"], max(winds) if winds else None),
|
||||
"humidity": humidity_score(rules["humidity"], mean(h.humidity for h in hours)),
|
||||
"air": air_score(ctx.pm25, ctx.air_label),
|
||||
"air": air_score(ctx.pm25, ctx.air_label, rules.get("air")),
|
||||
"uv": uv_score(rules["uv"], max(uvs, default=None)) if weights["uv"] else (0, ""),
|
||||
"sun": sun_score(rules["sun"], mean(suns) if suns else None) if weights["sun"] else (0, ""),
|
||||
"view": view_score(rules["view"], min(views, default=None)) if weights["view"] else (0, ""),
|
||||
|
||||
+4
-2
@@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items
|
||||
|
||||
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||
BUDGET_SEC = 45.0
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict:
|
||||
"""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)
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
@@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict)
|
||||
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]:
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page})
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec)
|
||||
raw = body.get("items") or []
|
||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
||||
|
||||
Vendored
+21
-7
@@ -13,9 +13,19 @@ from common.enums import EVENT_ICON, EventKind
|
||||
SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
|
||||
POPUP_URL = "https://popga.co.kr/popup/{id}"
|
||||
SOURCE_PREFIX = "popga:"
|
||||
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제
|
||||
# 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
|
||||
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
|
||||
# 팝가 '축제' 중 연극제·음악제의 공연 한 편. 극장·홀에서 하거나 이름이 공연이면 공연으로 넣는다
|
||||
_SHOW_PLACE = ("극장", "홀", "아트센터", "예술의전당", "씨어터", "시어터", "문화회관", "공연장")
|
||||
_SHOW_NAME = ("연극", "뮤지컬", "오페라", "독주회", "리사이틀", "콘서트")
|
||||
|
||||
|
||||
def is_show(name: str, place: str) -> bool:
|
||||
return any(w in place for w in _SHOW_PLACE) or any(w in name for w in _SHOW_NAME)
|
||||
|
||||
|
||||
_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>")
|
||||
@@ -86,10 +96,11 @@ def _coord(v) -> Optional[float]:
|
||||
|
||||
|
||||
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)
|
||||
"""팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
|
||||
found = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
|
||||
kind = _KINDS.get(found.group(1)) if found else None
|
||||
ld = _event_ld(page)
|
||||
if kind is None or kind.group(1) != STORE or ld is None:
|
||||
if kind is None 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:
|
||||
@@ -99,9 +110,12 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
|
||||
if sido is None:
|
||||
return None
|
||||
geo = loc.get("geo") or {}
|
||||
name, place = html.unescape(ld.get("name") or ""), html.unescape(loc.get("name") or "")
|
||||
if kind is EventKind.FESTIVAL and is_show(name, place):
|
||||
kind = EventKind.CONCERT
|
||||
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_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
|
||||
"place_name": place[: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],
|
||||
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import asyncio
|
||||
import html
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from common.enums import EVENT_ICON, EventKind
|
||||
|
||||
# 서울문화포털 문화행사 중 축제. 공개 API 는 키가 따로 있어 robots.txt 가 허용하는 /culture/culture/ 목록을 읽는다.
|
||||
LIST_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/jsonList.json"
|
||||
VIEW_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/view.do?cultcode={code}&menuNo=200010"
|
||||
IMAGE_URL = "https://culture.seoul.go.kr/cmmn/file/getImage.do?atchFileId={id}&thumb=Y"
|
||||
IMAGE_CREDIT = "ⓒ서울문화포털"
|
||||
SOURCE_PREFIX = "seoul:"
|
||||
SEOUL = "11"
|
||||
REQUEST_GAP_SEC = 0.3
|
||||
_MAX_PAGES = 30
|
||||
# 이름 앞 주최 기관 "[서울시청] ", "[마포문화재단] " 은 카드 제목에서 뗀다
|
||||
_HOST_PREFIX = re.compile(r"^(\s*\[[^\]]*\]\s*)+")
|
||||
|
||||
|
||||
async def fetch_seoul_festivals(client: httpx.AsyncClient, since: date, days: int) -> list[dict]:
|
||||
"""since 부터 days 일 안에 열리는 서울 축제. 한 쪽에 10개씩, 빈 쪽이 나올 때까지."""
|
||||
form = {"menuNo": "200010", "searchCate": "FESTIVAL", "sdate": since.isoformat(), "edate": (since + timedelta(days=days)).isoformat()}
|
||||
items: list[dict] = []
|
||||
for page in range(1, _MAX_PAGES + 1):
|
||||
res = await client.post(LIST_URL, data={**form, "pageIndex": str(page)})
|
||||
res.raise_for_status()
|
||||
chunk = res.json().get("resultList") or []
|
||||
if not chunk:
|
||||
break
|
||||
items.extend(chunk)
|
||||
await asyncio.sleep(REQUEST_GAP_SEC)
|
||||
return items
|
||||
|
||||
|
||||
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_seoul_festivals(items: list[dict]) -> list[dict]:
|
||||
rows = []
|
||||
for it in items:
|
||||
start, end = _date(it.get("strtdate")), _date(it.get("endDate"))
|
||||
name = _HOST_PREFIX.sub("", html.unescape(it.get("title") or "")).strip()
|
||||
if start is None or end is None or not name or it.get("cultcode") is None:
|
||||
continue
|
||||
rows.append({
|
||||
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
|
||||
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
|
||||
"source_url": VIEW_URL.format(code=it["cultcode"]),
|
||||
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
|
||||
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
|
||||
"lat": _coord(it.get("xCoord")), "lon": _coord(it.get("yCoord")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
|
||||
})
|
||||
return rows
|
||||
@@ -25,6 +25,8 @@ 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.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
@@ -62,6 +64,19 @@ LINEUP = [
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
]
|
||||
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
|
||||
NATIONAL_SCOPE = "00"
|
||||
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
|
||||
|
||||
|
||||
def sido_of(region_code: str) -> str:
|
||||
"""구 행정코드의 시도 부분(앞 2자리)."""
|
||||
return region_code[:2]
|
||||
|
||||
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
@@ -74,7 +89,6 @@ _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory
|
||||
_FEED_TTL_MAX = 3600
|
||||
_PARTIAL_TTL = 60
|
||||
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
|
||||
_NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
_RAIN_PROB = 40
|
||||
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
|
||||
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
|
||||
@@ -140,22 +154,12 @@ def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET,
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
@@ -223,17 +227,33 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
return head + rest
|
||||
|
||||
|
||||
def _by_position(posts: list[Post]) -> list[Post]:
|
||||
"""번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다)."""
|
||||
out: dict[int, Post] = {}
|
||||
for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)):
|
||||
out.setdefault(p.position, p)
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
|
||||
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
|
||||
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
lineup = [x for x in LINEUP if x[0] not in made]
|
||||
err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
sidos = sorted({sido_of(r.code) for r in all_regions})
|
||||
lineup = [
|
||||
(scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos)
|
||||
if (scope, x[0]) not in made and (NATIONAL_SCOPE, x[0]) not in made
|
||||
]
|
||||
if not lineup:
|
||||
return err
|
||||
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
|
||||
@@ -242,12 +262,12 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
|
||||
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
|
||||
end = start + timedelta(days=1)
|
||||
rows = []
|
||||
for position, post_type, ref_type, rank in lineup:
|
||||
for scope, position, post_type, ref_type, rank in lineup:
|
||||
ref = refs.get(post_type)
|
||||
if ref_type is RefType.ARTICLE and ref is None:
|
||||
continue
|
||||
rows.append({
|
||||
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"feed_date": day, "position": position, "scope": scope, "post_type": post_type.value, "ref_type": ref_type.value,
|
||||
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
|
||||
"published_at": start, "end_at": end,
|
||||
})
|
||||
@@ -301,7 +321,7 @@ class FeedService:
|
||||
|
||||
day = feed_day(now)
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(day, self.crud, self.season_crud)
|
||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||
try:
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||
@@ -332,7 +352,8 @@ class FeedService:
|
||||
_, hourly = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
|
||||
)
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
|
||||
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
|
||||
posts = _by_position(posts or [])
|
||||
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
@@ -340,7 +361,7 @@ class FeedService:
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
for p in posts or []:
|
||||
if PostType(p.post_type) is PostType.GAK:
|
||||
@@ -360,9 +381,10 @@ class FeedService:
|
||||
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 mix_kinds(events)[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
top5=[_top(i) for i in board.ranked[:5]] if board else [],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon,
|
||||
image=a.image_url, image_credit=a.image_credit)
|
||||
for a in articles or [] if a.category == ArticleCategory.SEASON.value
|
||||
],
|
||||
),
|
||||
@@ -402,7 +424,7 @@ class FeedService:
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
@@ -450,7 +472,8 @@ class FeedService:
|
||||
if t in (PostType.SEASON, PostType.TIP) and p.ref_id in c.articles:
|
||||
a = c.articles[p.ref_id]
|
||||
return PostData(**base, title=a.title, icon=a.icon, caption=" ".join(a.body[1:2]) or a.body[0],
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title])
|
||||
slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon, image=a.image_url, image_credit=a.image_credit)],
|
||||
share_messages=[a.title])
|
||||
if t is PostType.EVENT:
|
||||
soon = mix_kinds([e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()])
|
||||
rank = p.index_rank or 1
|
||||
@@ -656,7 +679,7 @@ class FeedService:
|
||||
best = None
|
||||
for i in c.board.items if c.board else []:
|
||||
s = next((x for x in i.trend if x.score_date == tomorrow), None)
|
||||
if s is not None and (best is None or s.score > best[1].score):
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
if best is not None:
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
@@ -16,7 +16,8 @@ from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
|
||||
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score
|
||||
from services.calc.moon import illumination
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
@@ -28,14 +29,15 @@ DAYS = 3
|
||||
_LOOKAHEAD_HOURS = (9, 18)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
|
||||
# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도.
|
||||
# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도.
|
||||
WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=30, weight_wind=15, weight_humidity=0, weight_air=15, weight_time=0,
|
||||
weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"},
|
||||
"wind": {"type": "calm", "ok": 2, "limit": 10}, "humidity": {"type": "range", "lo": 40, "hi": 60, "best": 50},
|
||||
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 9, "to": 21}],
|
||||
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
|
||||
|
||||
@@ -45,6 +47,9 @@ class IndexItem:
|
||||
score: IndexScore
|
||||
rank: int
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -54,6 +59,11 @@ class IndexBoard:
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
"""지금 구간에 해당하는 각만 (순위·피드용)."""
|
||||
return [i for i in self.items if i.active]
|
||||
|
||||
|
||||
def _hour(r: WeatherHourly) -> Hour:
|
||||
return Hour(
|
||||
@@ -118,13 +128,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH
|
||||
|
||||
|
||||
def windows_for(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None,
|
||||
only: Optional[set[int]] = None,
|
||||
) -> list[list[Hour]]:
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간)."""
|
||||
"""시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).
|
||||
only 가 있으면 그 시각만 남긴다."""
|
||||
by_om = by_om or {}
|
||||
start = kst_midnight(day)
|
||||
out = []
|
||||
for hours in window_hours(defn, day, region):
|
||||
if only is not None:
|
||||
hours = [h for h in hours if h in only]
|
||||
rows = [by_at.get(start + timedelta(hours=h)) for h in hours]
|
||||
out.append([
|
||||
replace(_hour(r), hour=h, **_om_fields(
|
||||
@@ -135,6 +149,44 @@ def windows_for(
|
||||
return out
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
return EARLY if now.hour < NIGHT_END_HOUR else slot_of(now, sunset_at)
|
||||
|
||||
|
||||
def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다."""
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
result = evaluate(defn, windows, ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
|
||||
def _with_slot(row: IndexScore, data: dict) -> IndexScore:
|
||||
"""저장된 하루 점수 행을 구간 점수로 바꾼 사본 (DB에 붙지 않음)."""
|
||||
out = IndexScore(**{c.key: getattr(row, c.key) for c in IndexScore.__table__.columns})
|
||||
out.score, out.summary, out.zero_reason, out.notes = data["score"], data["summary"], data["zero_reason"], data["notes"]
|
||||
for a in AXES:
|
||||
setattr(out, f"{a}_score", data["factors"].get(a, 0))
|
||||
return out
|
||||
|
||||
|
||||
def day_forecast(d: WeatherDaily) -> DayForecast:
|
||||
return DayForecast(
|
||||
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
|
||||
@@ -204,20 +256,44 @@ class IndexService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
|
||||
slots = slot_days(today)
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, slots[-1]))
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: by_key[(d.index_id, today)].score, reverse=True)
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key],
|
||||
)
|
||||
for i, d in enumerate(ranked)
|
||||
]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
row = by_key.get((d.index_id, today))
|
||||
if row is None:
|
||||
continue
|
||||
if not row.slots:
|
||||
now_score[d.index_id] = row
|
||||
elif cur in row.slots:
|
||||
now_score[d.index_id] = _with_slot(row, row.slots[cur])
|
||||
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
|
||||
)
|
||||
for d in off:
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
@@ -250,7 +326,8 @@ 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, by_om), today_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
|
||||
|
||||
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
|
||||
@@ -258,8 +335,9 @@ class IndexService:
|
||||
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]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
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)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()):
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
@@ -278,10 +356,12 @@ class IndexService:
|
||||
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
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
"estimated": result.estimated, "computed_at": now,
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
@@ -80,10 +80,12 @@ class RankItem:
|
||||
|
||||
|
||||
def nearest_spots(lat: float, lon: float, spots: list[SunsetSpot]) -> list[Spot]:
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순."""
|
||||
near = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in near if x.distance_km <= SPOT_RADIUS_KM]
|
||||
"""반경 안에서 해 지는 쪽이 트인 곳(sort_order 0)을 먼저, 그 안에서는 가까운 순. 반경 안에 없으면 가장 가까운 한 곳."""
|
||||
every = [Spot(spot=p, distance_km=round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1), direction=bearing_deg(lat, lon, float(p.lat), float(p.lon)))
|
||||
for p in spots]
|
||||
near = [x for x in every if x.distance_km <= SPOT_RADIUS_KM]
|
||||
if not near:
|
||||
return sorted(every, key=lambda x: x.distance_km)[:1]
|
||||
return sorted(near, key=lambda x: (x.spot.sort_order, x.distance_km))[:SPOT_LIMIT]
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import Optional
|
||||
@@ -20,11 +22,16 @@ from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
|
||||
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
|
||||
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kasi import fetch_holidays
|
||||
from services.external.seoul_culture import IMAGE_CREDIT as SEOUL_CREDIT
|
||||
from services.external.seoul_culture import SEOUL
|
||||
from services.external.seoul_culture import SOURCE_PREFIX as SEOUL_PREFIX
|
||||
from services.external.seoul_culture import fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
|
||||
from services.external.tour_api import fetch_festivals, parse_festivals
|
||||
from services.index_service import IndexService
|
||||
@@ -36,6 +43,12 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다.
|
||||
_EVENT_SIDOS = {"12": ("29", "46")}
|
||||
PLACE_RADIUS_KM = EVENT_RADIUS_KM
|
||||
PLACE_LIMIT = 10
|
||||
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
|
||||
PLACE_FALLBACK = 3
|
||||
_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
@@ -62,6 +75,7 @@ class DayPlan:
|
||||
class PlaceItem:
|
||||
place: Place
|
||||
is_good: bool
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -97,6 +111,8 @@ def image_credit(e: Event) -> Optional[str]:
|
||||
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
|
||||
if not e.image_url or e.source_id is None:
|
||||
return None
|
||||
if e.source_id.startswith(SEOUL_PREFIX):
|
||||
return SEOUL_CREDIT
|
||||
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
|
||||
|
||||
|
||||
@@ -115,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
return mixed
|
||||
|
||||
|
||||
def event_sidos(region_code: str) -> tuple[str, ...]:
|
||||
"""구가 속한 시도의 행사 시도 코드들."""
|
||||
sido = region_code[:2]
|
||||
return _EVENT_SIDOS.get(sido, (sido,))
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM}
|
||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
||||
own = event_sidos(region.code)
|
||||
near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)}
|
||||
return list(own) + sorted(near - set(own))
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
@@ -134,7 +157,23 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return distance_km <= EVENT_RADIUS_KM
|
||||
if e.region_code is not None:
|
||||
return e.region_code == region.code
|
||||
return e.sido_code == region.code[:2]
|
||||
return e.sido_code in event_sidos(region.code)
|
||||
|
||||
|
||||
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
|
||||
"""구 중심에서 반경 안의 명소를 날씨에 맞는 것 먼저, 같으면 가까운 순으로. 반경 안에 없으면 가장 가까운 몇 곳."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dist = sorted(((p, round(haversine_km(lat, lon, float(p.lat), float(p.lon)), 1)) for p in places if p.lat is not None and p.lon is not None), key=lambda x: x[1])
|
||||
near = [x for x in dist if x[1] <= PLACE_RADIUS_KM] or dist[:PLACE_FALLBACK]
|
||||
areas = list(dict.fromkeys(p.area for p, _ in near))
|
||||
items = [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor, distance_km=d) for p, d in near if area is None or p.area == area]
|
||||
items.sort(key=lambda i: (not i.is_good, i.distance_km))
|
||||
return items[:PLACE_LIMIT], areas
|
||||
|
||||
|
||||
def place_credit(p: Place) -> Optional[str]:
|
||||
"""명소 사진은 TourAPI 것만 넣는다."""
|
||||
return TOUR_CREDIT if p.image_url else None
|
||||
|
||||
|
||||
def _status(e: Event, today: date) -> tuple[str, str]:
|
||||
@@ -155,17 +194,59 @@ async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str
|
||||
return []
|
||||
|
||||
|
||||
# 같은 축제를 두 출처가 다르게 적는다: "[성동문화재단] 2026 크리에이티브X성수" ↔ "2026 크리에이티브X성수"
|
||||
_NAME_NOISE = re.compile(r"\[[^\]]*\]|\([^)]*\)|20\d\d|제\s*\d+\s*회|[^\w]")
|
||||
|
||||
|
||||
def _name_key(name: str) -> str:
|
||||
return _NAME_NOISE.sub("", name).lower()
|
||||
|
||||
|
||||
async def drop_known(rows: list[dict]) -> list[dict]:
|
||||
"""다른 출처로 이미 들어 있는 행사(같은 시도, 이름이 같고 기간이 겹침)는 뺀다. 먼저 넣은 출처를 남긴다."""
|
||||
if not rows:
|
||||
return rows
|
||||
since, until = min(r["start_date"] for r in rows), max(r["end_date"] for r in rows)
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(lambda s: WeekCRUD().events(s, sorted({r["sido_code"] for r in rows}), since, until))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return rows
|
||||
known: dict[tuple[str, str], list[Event]] = {}
|
||||
for e in existing or []:
|
||||
known.setdefault((e.sido_code, _name_key(e.name)), []).append(e)
|
||||
|
||||
def dup(r: dict) -> bool:
|
||||
key = _name_key(r["name"])
|
||||
return bool(key) and any(e.source_id != r["source_id"] and e.start_date <= r["end_date"] and r["start_date"] <= e.end_date
|
||||
for e in known.get((r["sido_code"], key), []))
|
||||
|
||||
return [r for r in rows if not dup(r)]
|
||||
|
||||
|
||||
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
|
||||
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
|
||||
if sido != SEOUL:
|
||||
return []
|
||||
try:
|
||||
rows = parse_seoul_festivals(await fetch_seoul_festivals(client, today, EVENT_DAYS))
|
||||
except (httpx.HTTPError, ValueError) as e:
|
||||
LOG.error(f"[week] seoul festivals: {type(e).__name__} {e}")
|
||||
return []
|
||||
names = {_name_key(r["name"]) for r in known}
|
||||
return [r for r in rows if _name_key(r["name"]) not in names]
|
||||
|
||||
|
||||
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)
|
||||
festivals += await _seoul(client, sido, today, festivals)
|
||||
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())
|
||||
rows = await drop_known(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)}
|
||||
@@ -205,11 +286,12 @@ class WeekService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
names = {d.index_id: d.name for d in defs or []}
|
||||
priority = {d.index_id: d.priority for d in defs or []}
|
||||
plans = []
|
||||
for d in daily:
|
||||
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
|
||||
rain_hours = _rain_hours(rows)
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: x.score, reverse=True)[:2]
|
||||
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2]
|
||||
holiday = (holidays or {}).get(d.forecast_date)
|
||||
weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
|
||||
word = _weather_word(d, rain_hours)
|
||||
@@ -229,19 +311,21 @@ class WeekService:
|
||||
))
|
||||
return ErrorType.SUCCESS, plans
|
||||
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str]]:
|
||||
async def places(self, region_code: str, day: date, area: Optional[str]) -> tuple[ErrorType, list[PlaceItem], list[str], bool]:
|
||||
err, region = await self._region(region_code)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places(s, region.code[:2]))
|
||||
return err, [], [], False
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
dlat, dlon = PLACE_RADIUS_KM / 111, PLACE_RADIUS_KM / (111 * math.cos(math.radians(lat)))
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.places_in_box(s, lat, lon, dlat, dlon))
|
||||
if err is ErrorType.SUCCESS and not any(haversine_km(lat, lon, float(p.lat), float(p.lon)) <= PLACE_RADIUS_KM for p in places):
|
||||
err, places = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.all_places(s))
|
||||
_, daily = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.daily(s, region.code, day, day))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, [], []
|
||||
return err, [], [], False
|
||||
rainy = bool(daily) and daily[0].rain_type != RainType.NONE.value
|
||||
areas = list(dict.fromkeys(p.area for p in places))
|
||||
picked = [p for p in places if area is None or p.area == area]
|
||||
picked.sort(key=lambda p: (p.is_outdoor if rainy else not p.is_outdoor, p.sort_order))
|
||||
return ErrorType.SUCCESS, [PlaceItem(place=p, is_good=(not p.is_outdoor) if rainy else p.is_outdoor) for p in picked], areas
|
||||
items, areas = pick_places(region, places, rainy, area)
|
||||
return ErrorType.SUCCESS, items, areas, rainy
|
||||
|
||||
async def events(self, region_code: str, area: Optional[str]) -> tuple[ErrorType, list[EventItem]]:
|
||||
err, region = await self._region(region_code)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
@@ -158,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
h = int(re.match(r"\d+", t).group())
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
|
||||
@@ -65,6 +65,14 @@ async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_seoul_crawl(monkeypatch):
|
||||
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
|
||||
import services.week_service as week_service
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
|
||||
@@ -5,7 +5,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external import airkorea, data_go_kr, guard, open_meteo
|
||||
from services.external.airkorea import fetch_realtime
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
|
||||
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
|
||||
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
|
||||
|
||||
async def slow(req: httpx.Request) -> httpx.Response:
|
||||
await asyncio.sleep(0.5)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
|
||||
|
||||
async with _client(slow) as client:
|
||||
assert await fetch_realtime(client) == [{"stationName": "x"}]
|
||||
@@ -0,0 +1,63 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
REGION = SimpleNamespace(lat=37.5, lon=127.0)
|
||||
CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
|
||||
|
||||
def _rows(rain_from: int = 99):
|
||||
start = kst_midnight(DAY)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value,
|
||||
rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(0, 30)
|
||||
}
|
||||
|
||||
|
||||
def _defn(windows):
|
||||
return SimpleNamespace(
|
||||
weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[], windows=windows,
|
||||
)
|
||||
|
||||
|
||||
def test_slot_hours_split_by_sunset():
|
||||
hours = slot_hours(DAY, SUNSET)
|
||||
assert hours["morning"] == set(range(5, 11))
|
||||
assert hours["day"] == set(range(11, 16))
|
||||
assert hours["evening"] == {16, 17, 18}
|
||||
assert hours["night"] == set(range(19, 29))
|
||||
|
||||
|
||||
def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score > 80
|
||||
assert parts["evening"].score < parts["morning"].score
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
|
||||
|
||||
def test_weather_score_covers_every_slot():
|
||||
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
@@ -8,6 +8,7 @@ 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.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
@@ -16,17 +17,19 @@ from services.week_service import collect_events
|
||||
REGION = "1114000000"
|
||||
|
||||
|
||||
async def _posts(day: date):
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position")))
|
||||
async def _posts(day: date, sido: str = REGION[:2]):
|
||||
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(
|
||||
f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') ORDER BY position")))
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_weekend_post_every_day():
|
||||
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
@@ -36,10 +39,10 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
@@ -58,7 +61,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
assert len(body["stories"]) == 34
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -155,7 +158,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_every_card_at_three():
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'")))
|
||||
rows = list(rows)
|
||||
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
||||
|
||||
@@ -9,10 +9,13 @@ 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.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,13 +54,18 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -95,13 +103,40 @@ async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
def _seed() -> list[dict]:
|
||||
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"))
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
seed = _seed()
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="low", priority=3),
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
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, sun_score, temp_score,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, air_score, 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
|
||||
@@ -222,3 +226,51 @@ def test_outing_estimate_from_mid_forecast():
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
|
||||
|
||||
def test_air_rule_can_reverse_so_dusty_air_scores_high():
|
||||
rule = {"zero": 15, "full": 75}
|
||||
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
|
||||
assert air_score(10, None)[0] == 100
|
||||
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
|
||||
|
||||
|
||||
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
|
||||
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
|
||||
|
||||
|
||||
def _seed_score(code, day=_SAT, pm25=10, **hour):
|
||||
d = _SEED[code]
|
||||
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
|
||||
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
|
||||
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
|
||||
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
|
||||
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
|
||||
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
|
||||
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
|
||||
])
|
||||
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
assert _seed_score("golf", day=_WED, **perfect) < 100
|
||||
|
||||
|
||||
def test_weather_score_100_only_on_perfect_day():
|
||||
from services.index_service import WEATHER_SCORE_DEF
|
||||
|
||||
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
|
||||
|
||||
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
|
||||
@@ -28,6 +28,16 @@ def test_parse_popup_maps_store():
|
||||
}
|
||||
|
||||
|
||||
def test_parse_popup_maps_festival():
|
||||
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
|
||||
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
|
||||
|
||||
|
||||
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
|
||||
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
|
||||
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,end,address", [
|
||||
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
|
||||
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
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.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
|
||||
|
||||
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
|
||||
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
def _ids(feed: dict) -> dict[int, set[int]]:
|
||||
out: dict[int, set[int]] = defaultdict(set)
|
||||
for p in feed["posts"]:
|
||||
out[p["post_type"]].add(p["post_id"])
|
||||
return out
|
||||
|
||||
|
||||
def test_every_region_maps_to_one_sido():
|
||||
with open(REGION_CSV, encoding="utf-8") as f:
|
||||
regions = list(csv.DictReader(f))
|
||||
assert len(regions) == 256
|
||||
by_name: dict[str, set[str]] = defaultdict(set)
|
||||
for r in regions:
|
||||
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
|
||||
assert all(len(codes) == 1 for codes in by_name.values()), by_name
|
||||
sidos = {sido_of(r["code"]) for r in regions}
|
||||
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
|
||||
sejong = [r for r in regions if r["name"].startswith("세종")]
|
||||
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
|
||||
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_national_once_and_regional_per_sido():
|
||||
day = date(2026, 10, 15)
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
|
||||
rows = list(rows)
|
||||
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
sidos = {sido_of(r.code) for r in regions}
|
||||
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
|
||||
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
|
||||
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
|
||||
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
|
||||
async with client() as c:
|
||||
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
|
||||
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
|
||||
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
|
||||
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
|
||||
for t in regional:
|
||||
if t in ib:
|
||||
assert ia[t] == ib[t], PostType(t)
|
||||
if t in ibusan:
|
||||
assert not ia[t] & ibusan[t], PostType(t)
|
||||
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
|
||||
assert PostType.MOON.value in national
|
||||
for t in national:
|
||||
assert ia[t] == ib[t] == ibusan[t], PostType(t)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
|
||||
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
|
||||
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
|
||||
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
|
||||
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
|
||||
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
|
||||
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
|
||||
day = feed_day(now_kst())
|
||||
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
|
||||
for pos, t, ref, rank in LINEUP if ref.value == 1)
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
|
||||
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
|
||||
async with client() as c:
|
||||
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
|
||||
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
|
||||
assert n == 0
|
||||
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
|
||||
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5
|
||||
@@ -2,8 +2,10 @@ from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.season_service as season_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
|
||||
@@ -38,3 +40,15 @@ async def test_article_detail_and_not_found():
|
||||
missing = (await client.get("/v1/season/article/9999")).json()
|
||||
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
||||
assert missing["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_article_photo_only_when_seeded():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
listed = {a["code"]: a for a in (await client.get("/v1/season/article/list")).json()["articles"]}
|
||||
umbrella = (await client.get(f"/v1/season/article/{listed['umbrella']['article_id']}")).json()["article"]
|
||||
_, maple_id = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text("SELECT article_id FROM article WHERE code = 'maple'")))
|
||||
maple = (await client.get(f"/v1/season/article/{maple_id}")).json()["article"]
|
||||
assert umbrella["image"] == "/season/umbrella.jpg" and "image_credit" not in umbrella
|
||||
assert maple["image"] == "/season/maple.jpg" and maple["image_credit"] == "ⓒJoycekim77 · CC BY-SA 3.0"
|
||||
assert "image" not in listed["howgak"] and "image" not in listed["di"]
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import services.week_service as week_service
|
||||
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
|
||||
from services.week_service import _seoul
|
||||
|
||||
ITEM = {
|
||||
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
|
||||
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
|
||||
}
|
||||
|
||||
|
||||
def test_parse_reads_lat_from_x_and_builds_image_and_link():
|
||||
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
|
||||
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
|
||||
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
|
||||
assert row["name"] == "2026 중랑용마폭포축제"
|
||||
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
|
||||
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_pages_until_empty(monkeypatch):
|
||||
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
|
||||
pages = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
assert str(req.url) == LIST_URL
|
||||
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
|
||||
pages.append(page)
|
||||
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
|
||||
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
|
||||
assert len(items) == 20 and pages == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
|
||||
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
|
||||
|
||||
async def fake(client, since, days):
|
||||
return [ITEM, other]
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
|
||||
known = [{"name": "제3회 중랑용마폭포축제"}]
|
||||
rows = await _seoul(None, "11", date(2026, 10, 8), known)
|
||||
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
|
||||
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_seoul_failure_keeps_other_sources(monkeypatch):
|
||||
async def broken(client, since, days):
|
||||
raise httpx.ConnectError("down")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
|
||||
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
|
||||
|
||||
|
||||
def _row(source_id, name, start, end, sido="11"):
|
||||
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
|
||||
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_drop_known_skips_same_festival_from_another_source():
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from crud.week_crud import WeekCRUD
|
||||
from services.week_service import drop_known
|
||||
|
||||
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
|
||||
rows = [
|
||||
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
|
||||
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
|
||||
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
@@ -93,7 +93,7 @@ async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
def test_nearest_spots_west_first_and_nearest_one_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
@@ -103,7 +103,7 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
|
||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(37.0, 127.0, spots)] == ["먼 서쪽", "가까운 동쪽"]
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
|
||||
|
||||
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
|
||||
@@ -7,13 +7,13 @@ import services.air_service as air_service
|
||||
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.database.model.models import Event, Place, Region
|
||||
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 EventItem, _status, mix_kinds
|
||||
from services.week_service import PLACE_FALLBACK, PLACE_RADIUS_KM, EventItem, _status, mix_kinds, pick_places
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
|
||||
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
|
||||
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
|
||||
}
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("29", "46")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
|
||||
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
@@ -179,6 +195,46 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
def _place(name: str, lat: float, lon: float, outdoor: bool = True, area: str = "가") -> Place:
|
||||
return Place(name=name, lat=lat, lon=lon, is_outdoor=outdoor, area=area)
|
||||
|
||||
|
||||
def test_pick_places_within_radius_good_first_then_near():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [
|
||||
_place("먼 공원", 37.2, 127.0), _place("가까운 공원", 37.01, 127.0, area="나"),
|
||||
_place("미술관", 37.1, 127.0, outdoor=False), _place("반경 밖", 37.5, 127.0),
|
||||
]
|
||||
items, areas = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["가까운 공원", "먼 공원", "미술관"]
|
||||
assert all(i.distance_km <= PLACE_RADIUS_KM for i in items) and items[0].distance_km == 1.1
|
||||
assert areas == ["나", "가"]
|
||||
items, _ = pick_places(region, places, rainy=True, area=None)
|
||||
assert [i.place.name for i in items][0] == "미술관" and items[0].is_good
|
||||
items, _ = pick_places(region, places, rainy=False, area="가")
|
||||
assert [i.place.name for i in items] == ["먼 공원", "미술관"]
|
||||
|
||||
|
||||
def test_pick_places_falls_back_to_nearest_when_none_in_radius():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [_place(f"{k}km", 37.0 + k / 111, 127.0) for k in (90, 40, 60, 200)]
|
||||
items, _ = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["40km", "60km", "90km"][:PLACE_FALLBACK]
|
||||
assert items[0].distance_km > PLACE_RADIUS_KM
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region", ["2635000000", "5013000000", "4794000000"])
|
||||
async def test_places_outside_seoul_come_by_distance(fakes, region):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/place/list", params={"region": region, "day": now_kst().date().isoformat()})).json()
|
||||
places = body["places"]
|
||||
assert places and all(p["distance_km"] <= PLACE_RADIUS_KM for p in places)
|
||||
good = [p["distance_km"] for p in places if p["is_good"]]
|
||||
assert good == sorted(good)
|
||||
assert all(p["image_credit"] == "ⓒ한국관광공사" for p in places if p.get("image"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
@@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_morning_rain_then_outdoor_after_it_ends():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
|
||||
Reference in new issue
Block a user