Merge remote-tracking branch 'origin/main' into merge/festivals
# Conflicts: # backend/services/week_service.py
This commit is contained in:
commit
b4fcb313c7
56 files changed
+4132
-251
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):
|
||||
@@ -227,6 +228,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 +284,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 +294,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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -175,7 +175,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 +288,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 +307,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 +384,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;
|
||||
@@ -171,6 +171,8 @@ class BandArticle(WebPacketProtocol):
|
||||
title: str
|
||||
meta: str
|
||||
icon: str
|
||||
image: Optional[str] = None
|
||||
image_credit: Optional[str] = None
|
||||
|
||||
|
||||
class Bands(WebPacketProtocol):
|
||||
|
||||
@@ -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="이번 주 계절 책: 시, 절기, 계절 소식")
|
||||
|
||||
@@ -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
|
||||
])
|
||||
|
||||
@@ -98,8 +98,8 @@ 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
|
||||
|
||||
|
||||
@@ -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",
|
||||
@@ -142,7 +143,8 @@
|
||||
"60": "돗자리 펴기 괜찮은 날! 바람막이 하나면 완벽해요.",
|
||||
"80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺"
|
||||
},
|
||||
"sort_order": 2
|
||||
"sort_order": 2,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "chimaek",
|
||||
@@ -214,7 +216,8 @@
|
||||
"60": "바깥 테이블 괜찮아요! 얇은 겉옷 하나만 챙겨요.",
|
||||
"80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗"
|
||||
},
|
||||
"sort_order": 3
|
||||
"sort_order": 3,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "walk",
|
||||
@@ -284,7 +287,8 @@
|
||||
"60": "한 바퀴 돌기 좋은 저녁! 이어폰 챙겨서 가볍게 나가요.",
|
||||
"80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶"
|
||||
},
|
||||
"sort_order": 4
|
||||
"sort_order": 4,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "vent",
|
||||
@@ -359,7 +363,8 @@
|
||||
"60": "열어도 괜찮아요. 맞바람 나게 10분이면 충분!",
|
||||
"80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️"
|
||||
},
|
||||
"sort_order": 5
|
||||
"sort_order": 5,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "hiking",
|
||||
@@ -441,7 +446,8 @@
|
||||
"60": "오를 만해요! 바람막이 챙기고 일찍 출발해요.",
|
||||
"80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️"
|
||||
},
|
||||
"sort_order": 6
|
||||
"sort_order": 6,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "carwash",
|
||||
@@ -505,7 +511,8 @@
|
||||
"60": "세차해도 괜찮아요. 먼지는 좀 붙을 수 있어요.",
|
||||
"80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨"
|
||||
},
|
||||
"sort_order": 7
|
||||
"sort_order": 7,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "camping",
|
||||
@@ -579,7 +586,8 @@
|
||||
"60": "하룻밤 괜찮아요. 새벽엔 쌀쌀하니 담요 챙기기!",
|
||||
"80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥"
|
||||
},
|
||||
"sort_order": 8
|
||||
"sort_order": 8,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "running",
|
||||
@@ -654,7 +662,8 @@
|
||||
"60": "뛸 만해요! 아침·저녁 중 시원한 쪽 고르기.",
|
||||
"80": "8~18°에 공기 보송, 기록 갱신각 🏃"
|
||||
},
|
||||
"sort_order": 9
|
||||
"sort_order": 9,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "stars",
|
||||
@@ -719,7 +728,8 @@
|
||||
"60": "꽤 보여요! 불빛 적은 곳으로 조금만 나가요.",
|
||||
"80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨"
|
||||
},
|
||||
"sort_order": 10
|
||||
"sort_order": 10,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "jjamppong",
|
||||
@@ -777,7 +787,8 @@
|
||||
"60": "쌀쌀하거나 비 와서 국물 각 잡혀요!",
|
||||
"80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜"
|
||||
},
|
||||
"sort_order": 11
|
||||
"sort_order": 11,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "makgeolli",
|
||||
@@ -833,7 +844,8 @@
|
||||
"60": "비 기운이 있어요. 파전 반죽 준비각!",
|
||||
"80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶"
|
||||
},
|
||||
"sort_order": 12
|
||||
"sort_order": 12,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "iced_hot",
|
||||
@@ -887,7 +899,8 @@
|
||||
"60": "아침 공기가 차요. 오늘은 뜨아로 갈아탈 때!",
|
||||
"80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕"
|
||||
},
|
||||
"sort_order": 13
|
||||
"sort_order": 13,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "laundry",
|
||||
@@ -951,7 +964,8 @@
|
||||
"60": "잘 마르는 편이에요. 두꺼운 건 오후까지 두기!",
|
||||
"80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️"
|
||||
},
|
||||
"sort_order": 14
|
||||
"sort_order": 14,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "bike",
|
||||
@@ -1033,7 +1047,8 @@
|
||||
"60": "탈 만해요! 강변은 바람 좀 부니 바람막이 챙기기.",
|
||||
"80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲"
|
||||
},
|
||||
"sort_order": 15
|
||||
"sort_order": 15,
|
||||
"priority": 1
|
||||
},
|
||||
{
|
||||
"code": "dog",
|
||||
@@ -1116,7 +1131,8 @@
|
||||
"60": "산책 괜찮아요! 그늘 많은 길로 가요.",
|
||||
"80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶"
|
||||
},
|
||||
"sort_order": 16
|
||||
"sort_order": 16,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "glasses",
|
||||
@@ -1170,7 +1186,8 @@
|
||||
"60": "출근길 안경에 김 서려요. 닦을 천 챙기기!",
|
||||
"80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓"
|
||||
},
|
||||
"sort_order": 17
|
||||
"sort_order": 17,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "makeup",
|
||||
@@ -1224,7 +1241,8 @@
|
||||
"60": "덥고 습해서 무너지기 쉬워요. 픽서 챙기기!",
|
||||
"80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠"
|
||||
},
|
||||
"sort_order": 18
|
||||
"sort_order": 18,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "naengmyeon",
|
||||
@@ -1280,7 +1298,8 @@
|
||||
"60": "점심에 덥네요. 냉면 한 그릇 생각나요!",
|
||||
"80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶"
|
||||
},
|
||||
"sort_order": 19
|
||||
"sort_order": 19,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "taxi",
|
||||
@@ -1336,7 +1355,8 @@
|
||||
"60": "비나 추위로 택시 잡기 힘들어요. 막차 시간 확인!",
|
||||
"80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕"
|
||||
},
|
||||
"sort_order": 20
|
||||
"sort_order": 20,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "delivery",
|
||||
@@ -1393,7 +1413,8 @@
|
||||
"60": "비나 추위로 주문이 몰려요. 일찍 시키기!",
|
||||
"80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵"
|
||||
},
|
||||
"sort_order": 21
|
||||
"sort_order": 21,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "garden",
|
||||
@@ -1462,7 +1483,8 @@
|
||||
"60": "화분 돌보기 괜찮아요. 아침에 물 듬뿍!",
|
||||
"80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱"
|
||||
},
|
||||
"sort_order": 22
|
||||
"sort_order": 22,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "photo",
|
||||
@@ -1530,7 +1552,8 @@
|
||||
"60": "노을이 꽤 기대돼요. 해 지기 30분 전에 나가요.",
|
||||
"80": "노을 점수 높고 공기 맑음, 인생샷 각 📸"
|
||||
},
|
||||
"sort_order": 23
|
||||
"sort_order": 23,
|
||||
"priority": 2
|
||||
},
|
||||
{
|
||||
"code": "baseball",
|
||||
@@ -1596,7 +1619,8 @@
|
||||
"60": "직관 괜찮아요! 밤엔 선선하니 겉옷 하나.",
|
||||
"80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾"
|
||||
},
|
||||
"sort_order": 24
|
||||
"sort_order": 24,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "study",
|
||||
@@ -1653,7 +1677,8 @@
|
||||
"60": "밖이 애매해서 책상에 앉을 만해요.",
|
||||
"80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚"
|
||||
},
|
||||
"sort_order": 25
|
||||
"sort_order": 25,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "netflix",
|
||||
@@ -1709,7 +1734,8 @@
|
||||
"60": "비 오거나 쌀쌀한 밤, 이불 속이 최고!",
|
||||
"80": "비 오는 주말 앞 밤, 정주행 시작각 🍿"
|
||||
},
|
||||
"sort_order": 26
|
||||
"sort_order": 26,
|
||||
"priority": 3
|
||||
},
|
||||
{
|
||||
"code": "chestnut",
|
||||
@@ -1763,6 +1789,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
|
||||
|
@@ -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)
|
||||
@@ -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, ""),
|
||||
|
||||
@@ -25,6 +25,7 @@ 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.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 +63,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],
|
||||
@@ -223,17 +237,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)
|
||||
|
||||
|
||||
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 +272,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 +331,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 +362,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]
|
||||
@@ -362,7 +393,8 @@ class FeedService:
|
||||
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
|
||||
top5=[_top(i) for i in items[:5]],
|
||||
season=[
|
||||
BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon)
|
||||
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
|
||||
],
|
||||
),
|
||||
@@ -450,7 +482,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 +689,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}점"))
|
||||
|
||||
@@ -16,7 +16,7 @@ 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.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
|
||||
@@ -210,7 +210,7 @@ class IndexService:
|
||||
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)
|
||||
ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True)
|
||||
items = [
|
||||
IndexItem(
|
||||
definition=d, score=by_key[(d.index_id, today)], rank=i + 1,
|
||||
|
||||
@@ -79,10 +79,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,5 @@
|
||||
import asyncio
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
@@ -21,6 +22,7 @@ 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
|
||||
@@ -41,6 +43,10 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
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: "흐림"}
|
||||
@@ -67,6 +73,7 @@ class DayPlan:
|
||||
class PlaceItem:
|
||||
place: Place
|
||||
is_good: bool
|
||||
distance_km: float
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -144,6 +151,22 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return e.sido_code == region.code[:2]
|
||||
|
||||
|
||||
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]:
|
||||
if e.start_date <= today <= e.end_date:
|
||||
return "live", "진행 중"
|
||||
@@ -234,11 +257,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)
|
||||
@@ -258,19 +282,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)
|
||||
|
||||
@@ -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,14 @@ 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()}
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"]]
|
||||
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 +99,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) 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,40 @@ 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
|
||||
@@ -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"]
|
||||
@@ -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"
|
||||
|
||||
@@ -179,6 +179,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
|
||||
|
||||
Reference in new issue
Block a user