Compare commits

..
Author SHA1 Message Date
skkim d5f8b148b4 fix: 각 점수에 중요도 배율을 반영해 화면 점수와 순위를 일치시킴 2026-10-23 09:14:52 +09:00
skkim 621a0cf90d chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일
- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
2026-10-22 13:58:36 +09:00
skkim 799a46f53c fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영 2026-10-22 13:38:39 +09:00
skkim 3b5afba8a1 feat: 지금 날씨 점수를 평균 60 정규분포로 (가장 낮은 요소로 깎기 제거, 구간별 바꾸기 표, 90점 이상 약 2.4%)
- 지금 날씨 점수는 '가장 낮은 요소로 깎기'를 하지 않는다 (밤엔 해 난 비율이 늘 0점이라 밤 점수가 62점을 못 넘었음). 각 점수는 그대로
- 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿔 보여 준다
- 바꾸기 표는 scripts/gen_weather_score_table.py 가 Open-Meteo 과거 예보로 만든다 (weather_score_table.json)
2026-10-22 13:33:50 +09:00
21 changed files with 846 additions and 119 deletions

No files matched your search

+3 -2
View File
@@ -35,9 +35,10 @@ class IndexCRUD:
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")
IndexScore.region_code == region_code, IndexScore.score_date == day,
text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])")
).limit(1)
return (await s.scalar(stmt)) is not None
+2 -2
View File
@@ -86,7 +86,7 @@ class WeekDay(WebPacketProtocol):
temp_min_c: Optional[float] = None
temp_max_c: Optional[float] = None
rain_prob: Optional[int] = None
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음")
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음")
class WeekSlide(WebPacketProtocol):
@@ -154,7 +154,7 @@ class TopIndex(WebPacketProtocol):
summary: Optional[str] = None
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)")
class HeroStat(WebPacketProtocol):
+2 -2
View File
@@ -5,7 +5,7 @@ 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, _cond # noqa: E402
from services.calc.index_calc import _cond # noqa: E402
SEED = os.path.join(ROOT, "seed", "index_definition.json")
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
@@ -109,7 +109,7 @@ def main() -> None:
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n")
P("- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.\n")
P("## 한눈에 보기\n")
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
+133
View File
@@ -0,0 +1,133 @@
"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다.
지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤,
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다.
1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다.
WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py
"""
import csv
import json
import os
import sys
import time
import urllib.parse
import urllib.request
from datetime import date, datetime, timedelta
from statistics import NormalDist
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.enums import RainType, Sky # noqa: E402
from common.logger import LOG # noqa: E402
from services.calc.day_slot import SLOTS, slot_hours # noqa: E402
from services.calc.index_calc import Context, Hour, evaluate # noqa: E402
from services.calc.sun import sun_times # noqa: E402
from services.index_service import WEATHER_SCORE_DEF # noqa: E402
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
OUT = os.path.join(BACKEND, "services", "calc", "weather_score_table.json")
MEAN, SIGMA = 60, 15
DAYS = 364
EVERY = 8
_WEATHER = "https://historical-forecast-api.open-meteo.com/v1/forecast"
_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality"
_HOURLY = "apparent_temperature,precipitation,snowfall,precipitation_probability,wind_speed_10m,relative_humidity_2m,sunshine_duration,cloud_cover"
def fetch(url: str, params: dict) -> dict:
"""잠깐 막히면 쉬었다가 다시 부른다. 네 번 모두 안 되면 멈춘다."""
query = urllib.parse.urlencode(params)
for attempt in range(4):
try:
with urllib.request.urlopen(f"{url}?{query}", timeout=60) as r:
return json.load(r)
except OSError as e:
LOG.error(f"[weather-table] {url} 실패 {attempt + 1}회: {e}")
time.sleep(10 * (attempt + 1))
raise RuntimeError(f"{url} 를 받지 못함")
def region_scores(lat: float, lon: float, start: date, end: date) -> dict[str, list[int]]:
"""한 지점의 날마다 구간별 원래 점수. 앱과 같은 입력으로 맞춘다 (일조는 그 시각을 덮는 3시간 합 ÷ 3시간, 미세먼지는 구간 평균)."""
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=(end + timedelta(days=1)).isoformat(), timezone="Asia/Seoul")
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
air = fetch(_AIR, base | dict(hourly="pm2_5"))["hourly"]
pm = dict(zip(air["time"], air["pm2_5"]))
at_index = {t: i for i, t in enumerate(w["time"])}
def key(at: datetime) -> str:
return at.strftime("%Y-%m-%dT%H:%M")
def hour_at(at: datetime, h: int) -> tuple[Hour | None, float | None]:
i = at_index.get(key(at))
if i is None or w["apparent_temperature"][i] is None:
return None, None
end_at = datetime.combine(at.date(), datetime.min.time()) + timedelta(hours=(at.hour + 3) // 3 * 3)
sun = [w["sunshine_duration"][j] for j in (at_index.get(key(end_at - timedelta(hours=k))) for k in (3, 2, 1)) if j is not None and w["sunshine_duration"][j] is not None]
wet = (w["precipitation"][i] or 0) >= 0.1
cloud = w["cloud_cover"][i] or 0
return Hour(
hour=h, feels_c=w["apparent_temperature"][i],
rain_type=(RainType.SNOW if (w["snowfall"][i] or 0) > 0 else RainType.RAIN) if wet else RainType.NONE,
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=int(w["relative_humidity_2m"][i]),
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
sunshine_ratio=min(sum(sun) / 10800, 1.0) if len(sun) == 3 else None,
), pm.get(key(at))
out: dict[str, list[int]] = {s: [] for s in SLOTS}
day = start
while day <= end:
midnight = datetime.combine(day, datetime.min.time())
for slot, hours in slot_hours(day, sun_times(day, lat, lon).sunset_at).items():
got = [hour_at(midnight + timedelta(hours=h), h) for h in sorted(hours)]
if any(x is None for x, _ in got):
continue
pms = [p for _, p in got if p is not None]
ctx = Context(day=day, is_holiday=False, pm25=round(sum(pms) / len(pms)) if pms else None, air_label=None, moon=0, sunset_score=None,
wind_warning=False, lookahead_rain_prob=0)
r = evaluate(WEATHER_SCORE_DEF, [[x for x, _ in got]], ctx)
if r is not None:
out[slot].append(r.score)
day += timedelta(days=1)
return out
def table(scores: list[int]) -> list[int]:
"""원래 점수 0~100 각각을 '분포에서의 가운데 순위'로 정규분포 점수에 맞춘다. 순서는 그대로 (줄어들지 않게)."""
n = len(scores)
out = []
for v in range(101):
below = sum(1 for s in scores if s < v)
same = sum(1 for s in scores if s == v)
out.append(max(0, min(100, round(MEAN + SIGMA * NormalDist().inv_cdf((below + same / 2 + 0.5) / (n + 1))))))
for i in range(1, 101):
out[i] = max(out[i], out[i - 1])
return out
def main() -> None:
end = date.today() - timedelta(days=2)
start = end - timedelta(days=DAYS)
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
scores: dict[str, list[int]] = {s: [] for s in SLOTS}
for r in regions:
for slot, got in region_scores(float(r["lat"]), float(r["lon"]), start, end).items():
scores[slot] += got
LOG.info(f"[weather-table] {r['name']} 완료")
time.sleep(1)
doc = {
"about": f"지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_weather_score_table.py 가 만든다",
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": {s: len(v) for s, v in scores.items()},
"slots": {s: table(v) for s, v in scores.items()},
}
with open(OUT, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=1)
print(len(regions), "regions", doc["samples"])
if __name__ == "__main__":
main()
+20 -10
View File
@@ -18,13 +18,17 @@ _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]
def priority_score(score: int, priority: int) -> int:
"""중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
return round(score * PRIORITY_WEIGHT[priority])
def rank_score(score: int, priority: int) -> tuple[int, int]:
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
return score, -priority
@dataclass(frozen=True)
@@ -57,6 +61,7 @@ class Context:
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
@dataclass(frozen=True)
@@ -209,7 +214,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
)
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요")
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
@@ -296,9 +301,14 @@ def _summary(hours: list[Hour]) -> str:
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int:
worst = min((factors[a] for a in AXES if weights[a]), default=100)
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int:
"""비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다)."""
mixed = sum(factors[a] * weights[a] for a in AXES) / 100
if not worst_pull:
return round(mixed)
# 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다.
worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100)
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
def _until(definition) -> str:
@@ -338,7 +348,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
}
factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights)
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
agg = {
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
@@ -395,7 +405,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
}
factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights)
score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
@@ -0,0 +1,428 @@
{
"about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다",
"period": [
"2025-10-21",
"2026-10-20"
],
"regions": 32,
"samples": {
"morning": 11680,
"day": 11680,
"evening": 11680,
"night": 11680
},
"slots": {
"morning": [
1,
1,
1,
1,
1,
1,
1,
4,
5,
5,
9,
11,
14,
16,
17,
18,
20,
21,
23,
25,
26,
28,
29,
31,
31,
32,
33,
33,
34,
34,
35,
35,
35,
36,
37,
37,
38,
38,
39,
40,
41,
42,
43,
44,
45,
46,
46,
47,
48,
49,
50,
51,
53,
54,
55,
57,
59,
61,
62,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
68,
69,
69,
70,
71,
71,
72,
73,
73,
74,
74,
75,
76,
77,
78,
79,
80,
82,
83,
85,
88,
90,
93,
96,
99,
100,
100,
100,
100,
100,
100,
100
],
"day": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
6,
9,
12,
15,
19,
22,
24,
26,
27,
28,
29,
30,
31,
31,
32,
32,
33,
33,
34,
35,
36,
37,
37,
38,
39,
40,
41,
41,
42,
42,
43,
43,
44,
44,
45,
45,
46,
46,
47,
47,
47,
48,
48,
48,
49,
49,
50,
50,
51,
52,
54,
56,
59,
61,
62,
63,
63,
64,
64,
64,
65,
65,
66,
66,
66,
67,
67,
68,
68,
69,
70,
71,
72,
73,
74,
76,
77,
79,
81,
83,
85,
87,
91,
97,
100,
100
],
"evening": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
7,
11,
14,
17,
20,
23,
25,
27,
28,
29,
30,
31,
32,
32,
33,
34,
34,
35,
36,
37,
38,
38,
39,
39,
40,
40,
41,
41,
42,
42,
43,
43,
44,
45,
45,
46,
46,
47,
47,
48,
48,
48,
49,
50,
50,
51,
52,
53,
55,
56,
59,
60,
62,
63,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
69,
69,
70,
71,
72,
72,
74,
75,
76,
78,
79,
81,
84,
86,
89,
92,
96,
100,
100,
100,
100
],
"night": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
7,
10,
11,
13,
15,
17,
20,
22,
26,
28,
30,
32,
33,
34,
34,
35,
35,
35,
36,
36,
37,
38,
38,
39,
40,
41,
41,
42,
43,
44,
45,
47,
48,
49,
50,
52,
53,
55,
57,
59,
62,
63,
65,
65,
66,
66,
66,
67,
68,
68,
69,
69,
70,
70,
71,
71,
72,
73,
74,
74,
75,
77,
78,
80,
82,
85,
88,
92,
96,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100
]
}
}
+3 -3
View File
@@ -242,7 +242,7 @@ def _by_position(posts: list[Post]) -> list[Post]:
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도)."""
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
@@ -340,7 +340,7 @@ class FeedService:
now = now_kst()
sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at
slot = slot_of(now, sunset_at)
key = f"feed:{region.code}:{slot}"
key = f"feed:{region.code}:priority-score-v4:{slot}"
try:
cached = await REDIS.conn.get(key)
if cached:
@@ -813,7 +813,7 @@ _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로."""
"""그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로."""
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
+50 -41
View File
@@ -1,6 +1,8 @@
import asyncio
import json
from dataclasses import dataclass, field, replace
from datetime import date, datetime, time, timedelta
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
@@ -17,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService
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.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
@@ -39,15 +41,12 @@ WEATHER_SCORE_DEF = SimpleNamespace(
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
},
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다
worst_pull=False,
)
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
def strict_weather(raw: int) -> int:
"""날씨 점수는 높을수록 깐깐하게: 90점까지는 8/9, 그 위는 두 배로 깎아 100점은 모든 조건이 완벽할 때만 (96 → 92)."""
return round(raw * 8 / 9) if raw <= 90 else round(80 + (raw - 90) * 2)
@dataclass
class WeatherWhy:
label: str
@@ -61,6 +60,9 @@ def weather_why(r: Result) -> list[WeatherWhy]:
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다
WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"]
SEASONS = ("겨울", "봄", "여름", "가을")
@@ -90,8 +92,8 @@ class IndexItem:
trend: list[IndexScore]
slot: Optional[str] = None
slots: dict[str, int] = field(default_factory=dict)
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
slot_ranks: dict[str, int] = field(default_factory=dict) # 각 구간의 날씨·시간대 적합도로 계산한 순위
active: bool = True # 시간대와 관계없이 활성화. 제철이 아닌 각만 제외
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
@@ -109,7 +111,7 @@ class IndexBoard:
@property
def ranked(self) -> list[IndexItem]:
"""지금 구간에 해당하는 각만 (순위·피드용)."""
"""활성화된 각 (순위·피드용)."""
return [i for i in self.items if i.active]
@@ -199,7 +201,6 @@ def windows_for(
EARLY = "early" # 0~5시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
def current_slot(now: datetime, sunset_at: datetime) -> str:
@@ -216,6 +217,16 @@ def _shown_parts(parts: dict, cur: str) -> dict:
return {k: shown[k] for k in SLOTS if k in shown}
def calibrated_weather(slot: str, score: int) -> int:
"""지금 날씨 점수의 원래 점수를 그 구간 표로 바꾼다. 0~5시(전날 밤 구간)는 밤 표."""
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
def weather_slot_scores(results: dict[str, Result]) -> dict[str, Result]:
"""구간별 날씨 점수 결과의 점수를 표시 점수로 바꾼다 (점수 근거 factors 는 그대로)."""
return {k: replace(r, score=calibrated_weather(k, r.score)) for k, r in results.items()}
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
"""그날 비·눈 오는 시각(0~23)."""
start = kst_midnight(day)
@@ -226,16 +237,21 @@ def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
now: Optional[datetime] = None,
) -> dict[str, Result]:
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
"""각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다."""
hours_by_slot = slot_hours(day, sunset_at)
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR))
if now:
_trim_passed(hours_by_slot, day, sunset_at, now)
activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)]
out = {}
for key, windows in parts.items():
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
for key, hours in hours_by_slot.items():
if not hours:
continue
matches = any(any(h % 24 in w for h in hours) for w in activity)
# 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다.
window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}])
windows = windows_for(window, day, region, by_at, by_om, only=hours)
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
if result is not None:
out[key] = result
return out
@@ -263,6 +279,13 @@ def _with_slot(row: IndexScore, data: dict) -> IndexScore:
return out
def _with_priority(row: IndexScore, priority: int) -> IndexScore:
"""DB의 원점수·요소 점수는 보존하고 응답용 사본의 최종 점수에만 중요도를 적용한다."""
out = IndexScore(**{c.key: getattr(row, c.key, None) for c in IndexScore.__table__.columns})
out.score = priority_score(row.score, priority)
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,
@@ -344,37 +367,23 @@ class IndexService:
month = today.month
out_season = [d for d in defs if not in_season(d, month)]
defs = [d for d in defs if in_season(d, month)]
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
# 현재 구간의 날씨와 시간 요소로 계산한 점수만 사용한다.
now_score: dict[int, IndexScore] = {}
for d in defs:
row = by_key.get((d.index_id, today))
if row is None:
if row is None or cur not in row.slots:
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])
now_score[d.index_id] = _with_priority(_with_slot(row, row.slots[cur]), d.priority)
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_parts({k: v["score"] for k, v in row.slots.items()}, cur)
parts = _shown_parts({k: priority_score(v["score"], d.priority) for k, v in row.slots.items()}, cur)
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],
trend=[now_score[d.index_id] if day == today else _with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key],
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
))
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_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
))
for k in SLOTS:
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
for n, i in enumerate(in_slot):
@@ -383,8 +392,8 @@ class IndexService:
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
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], active=False, in_season=False,
definition=d, score=_with_priority(row, d.priority), rank=len(items) + 1,
trend=[_with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
))
return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items,
@@ -459,8 +468,8 @@ class IndexService:
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
weather_parts = {
today: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()},
tomorrow: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset).items()},
today: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)),
tomorrow: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset)),
}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
+3 -3
View File
@@ -22,7 +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.calc.index_calc import priority_score, 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
@@ -291,14 +291,14 @@ class WeekService:
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: rank_score(x.score, priority.get(x.index_id, 2)), 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(priority_score(x.score, priority.get(x.index_id, 2)), 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)
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
is_rainy = d.rain_type != RainType.NONE.value
if top:
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top)
summary = ", ".join(f"{names.get(x.index_id, '')} {priority_score(x.score, priority.get(x.index_id, 2))}점" for x in top)
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
else:
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
+21 -9
View File
@@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night():
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
def test_gak_hidden_in_slots_outside_its_window():
def test_gak_scores_every_slot_and_time_match_is_binary():
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"evening", "night"}
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0}
def test_rain_in_evening_lowers_only_later_slots():
@@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score():
assert wet < dry
def test_slot_needs_two_overlapping_hours():
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
def test_time_match_includes_one_overlapping_hour():
by_at = _rows()
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
for start, end in ((10, 17), (9, 17), (10, 11)):
assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100
def test_outside_window_uses_current_weather_instead_of_daily_weather():
parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
assert parts["morning"].score == 100
assert parts["night"].score < parts["morning"].score
assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0
def test_early_hours_match_windows_crossing_midnight():
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert parts[EARLY].factors["time"] == 100
now = datetime(2026, 10, 8, 2, 0, tzinfo=KST)
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
assert parts[EARLY].factors["time"] == 0
def test_current_slot_skips_passed_hours():
+6 -1
View File
@@ -8,10 +8,12 @@ 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.index_crud import IndexCRUD
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
from services.index_service import in_season
from services.week_service import collect_events
REGION = "1114000000"
@@ -61,7 +63,10 @@ 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"]) == 40
_, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
expected = {d.code for d in definitions if in_season(d, now_kst().month)}
assert {g["code"] for g in body["stories"]} == expected
assert all(g["active"] for g in body["stories"])
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
+54 -13
View File
@@ -8,7 +8,7 @@ import services.air_service as air_service
import services.warning_service as warning_service
import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import OpenMeteoHourly, WeatherHourly
from common.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly
from common.enums import ErrorType
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
@@ -27,6 +27,14 @@ async def _async(v):
return v
def _board_score(index_id, day, score, slot_score=None):
value = score if slot_score is None else slot_score
return IndexScore(index_id=index_id, score_date=day, score=score, slots={
k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}}
for k in ("morning", "day", "evening", "night", "early")
})
def _vilage(*_):
start = kst_midnight(now_kst().date())
items = []
@@ -64,14 +72,17 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
assert body["result"]["success"] is True
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
priority = {d["code"]: d["priority"] for d in _seed()}
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
# 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝.
assert all(i["active"] for i in body["items"] if i["in_season"])
actives = [i["active"] for i in body["items"]]
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
seasons = [i["in_season"] for i in body["items"]]
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
for group in (True, False):
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert weighted == sorted(weighted, reverse=True)
scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]]
assert scores == sorted(scores, reverse=True)
order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert order == sorted(order, 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)]
@@ -142,7 +153,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
]
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
scores = [_board_score(x, today, v) for x, v in ((1, 50), (2, 60), (3, 99))]
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, {now_kst().date(): _WEATHER_50})))
@@ -155,30 +166,38 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
@pytest.mark.anyio
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
async def test_board_displays_and_ranks_by_priority_adjusted_score(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))]
scores = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))]
scores += [_board_score(x, today + timedelta(days=1), 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, {now_kst().date(): _WEATHER_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)]
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 68, 2), ("low", 63, 3)]
for item in board.items:
assert item.trend[0].score == item.score.score
assert item.trend[1].score == item.score.score
assert all(value == item.score.score for value in item.slots.values())
# 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다.
assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70]
_, again = await service.board(REGION)
assert [i.score.score for i in again.items] == [70, 68, 63]
@pytest.mark.anyio
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
async def test_board_ranks_each_slot_by_displayed_score(monkeypatch):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
every = ("morning", "day", "evening", "night", "early")
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}}
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
@@ -186,10 +205,32 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
_, board = await service.board(REGION)
ranks = {i.definition.code: i.slot_ranks for i in board.items}
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
# 하 90점은 표시 63점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다.
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
assert "night" not in ranks["high"]
assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
@pytest.mark.anyio
@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"])
async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="outside", priority=1)]
row = _board_score(1, today, 85, slot_score=65)
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row]))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {today: {cur: _RESULT_50}})))
monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur)
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
assert len(board.ranked) == 1
item = board.ranked[0]
assert item.active and item.score.score == 65 and item.rank == 1
assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur)
assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")}
assert item.slot_ranks == {k: 1 for k in item.slots}
def _om_row(at, **over):
+31 -13
View File
@@ -9,7 +9,7 @@ import pytest
from common.enums import RainType, Sky
from services.calc.index_calc import (
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,
priority_score, rank_score, uv_score, view_score, zero_rules_text,
)
from services.calc.moon import illumination
@@ -38,6 +38,36 @@ def test_perfect_evening_scores_100():
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
shown = [(priority_score(score, priority), priority) for score, priority in items]
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
assert priority_score(91, 2) == 77
assert priority_score(89, 2) == 76
def test_rank_uses_priority_only_to_break_ties():
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
@pytest.mark.parametrize("weight", [5, 10, 20])
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
weight_time=weight, factor_rules=rules)
hours = [[_h(12)]]
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
assert matched.score == 100 and unmatched.score == 100 - weight
def test_time_matching_does_not_replace_weekday_score():
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
def test_good_but_not_perfect_stays_below_100():
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
@@ -342,18 +372,6 @@ def test_umbrella_lost_needs_rain_that_stopped():
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def test_weather_score_is_strict_near_top():
"""좋은 날(96)도 92 수준, 100점은 모든 조건이 완벽할 때만. 낮은 점수도 조금씩 내려간다."""
from services.index_service import strict_weather
assert strict_weather(100) == 100
assert strict_weather(96) == 92
assert strict_weather(99) < 100
assert strict_weather(75) < 75
scores = [strict_weather(s) for s in range(101)]
assert scores == sorted(scores)
def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why
+57
View File
@@ -0,0 +1,57 @@
from dataclasses import replace
from datetime import date
from services.calc.index_calc import Context, evaluate
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
from tests.test_index_calc import _defn, _h
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)
SLOTS = ("morning", "day", "evening", "night")
def test_weather_score_has_no_worst_factor_pull():
"""해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다."""
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)]
r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT)
assert r.factors["sun"] == 0
assert r.score == 85
def test_gak_scores_keep_worst_factor_pull():
"""각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다."""
defn = _defn(zero_rules=[])
r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT)
assert r.factors["wind"] == 0
plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100)
assert r.score == round(plain * 0.75)
def test_table_covers_every_slot_and_never_goes_down():
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert len(table) == 101
assert all(0 <= v <= 100 for v in table)
assert all(a <= b for a, b in zip(table, table[1:]))
assert table[100] == 100
def test_table_makes_90_rare_and_centers_60():
"""구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐."""
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert any(55 <= v <= 65 for v in table)
assert sum(v >= 90 for v in table) < sum(v < 90 for v in table)
def test_calibrated_uses_slot_table_and_last_night_for_early():
assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70]
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
def test_weather_slot_scores_keeps_results_with_calibrated_scores():
"""점수 근거(factors)는 그대로 두고 점수만 표시 점수로 바꾼 결과를 돌려준다."""
results = {k: replace(evaluate(WEATHER_SCORE_DEF, [[_h(12)]], PERFECT), score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
shown = weather_slot_scores(results)
assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
assert all(shown[k].factors == results[k].factors for k in results)
assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다
+1 -1
View File
@@ -10,7 +10,7 @@
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
## 한눈에 보기
+5 -5
View File
@@ -175,21 +175,21 @@
### 2-7. 각 점수 (오늘의 각 34개)
- **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다.
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다.
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다.
- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다.
- **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다.
- 각의 시간대가 지금 구간과 겹치지 않아도 현재 구간의 날씨 점수로 활성화하고 순위, 피드 카드, 맨 위 1위 후보에 포함합니다. 시간대 미리보기도 각 구간의 날씨로 계산합니다. 제철이 아닌 각의 비활성화는 유지합니다.
- **하루 점수**(내일·토·일 칸): 각의 시간대 전체로 계산한 점수입니다.
- **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다.
- **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다.
| 종류 | 식 | 쓰는 각 |
|---|---|---|
| 요일 | 요일·공휴일마다 정한 점수 | 19개 |
| 고정 | 정한 점수 하나 | 13개 |
| 시간대 알맞음 | 활동 시간대와 겹치면 100점, 아니면 0점. 가중치 10%라면 10점 또는 0점 반영(불일치 추가 감점 없음) | fixed 유형 |
| 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 |
| 노을 | 그날 노을 점수 (2-9) | 사진산책각 |
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다.
- **최종 점수**는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시에 같은 점수를 사용합니다.
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
+20 -7
View File
@@ -56,7 +56,7 @@
## 3. 지금 날씨 점수
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다.
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 섞되 **'가장 낮은 요소로 깎기'(1의 3번)는 하지 않고**, 섞은 점수를 아래 '표시 점수로 바꾸기'로 바꿔 보여 줍니다. 밤엔 해 난 비율이 늘 0점이라 깎기를 하면 밤 점수가 62점을 못 넘었습니다 (`WEATHER_SCORE_DEF.worst_pull = False`).
| 요소 | 비중 | 100점 조건 |
|---|---:|---|
@@ -67,18 +67,31 @@
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다.
위 표의 점수가 **원래 점수**입니다. 밤엔 해 난 비율이 0점이라 나머지가 모두 만점이어도 85점이 최대입니다.
### 표시 점수로 바꾸기
원래 점수는 40~60점대에 몰리고 좋은 계절 낮에 90점 이상이 자주 나와 점수 분포가 고르지 않았습니다. 그래서 원래 점수를 **구간(아침·낮·저녁·밤)마다 1년 치 분포에서의 순위**로 보고, 평균 60·표준편차 15인 정규분포의 같은 위치 점수로 바꿔 보여 줍니다. 순서는 그대로라 더 좋은 날씨가 더 낮은 점수를 받는 일은 없습니다.
- 표시 점수 평균은 구간마다 60. 90점 이상은 약 2.4% (구간마다 2~3%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 약 0.35%. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54).
- 구간마다 따로 바꾸는 이유: 한 표로 하면 밤 점수가 최대 70점대 초반에 머뭅니다. 구간별 표는 "그 시간대치고 얼마나 좋은 날씨인가"를 뜻합니다.
- 0~5시(전날 밤 구간)는 밤 표를 씁니다.
- 바꾸기 표: `backend/services/calc/weather_score_table.json` (`calibrated_weather`). 만드는 법: `cd backend && python scripts/gen_weather_score_table.py`. 지금 날씨 점수의 요소·비중·기준값(`WEATHER_SCORE_DEF`)이 바뀌면 다시 만들어야 합니다.
- 표 재료: Open-Meteo 과거 예보로 32개 지역(region.csv 8곳마다 1곳)의 최근 364일을 계산. 실제 앱은 기상청 단기예보를 쓰므로 분포가 조금 다를 수 있어, 기상청 자료가 쌓이면 다시 만드는 게 좋습니다.
- **각 점수에는 적용하지 않습니다.**
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 원래 점수는 95점 미만(깎기를 뺀 값).
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
## 4. 각 점수
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다.
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다.
- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'.
- **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다. 비가 오면 그 뒤 구간 점수가 내려갑니다.
- 각의 시간대가 지금 구간과 겹치지 않아도 **현재 구간의 날씨 점수로 활성화하고 순위·피드 카드·히어로 1위 후보에 포함합니다.** 제철이 아닌 각의 비활성화는 유지합니다.
- **시간대 알맞음:** 활동 시간대와 겹치면 요소 점수 100점, 아니면 0점입니다. 가중치가 10%라면 10점 또는 0점을 반영하고, 불일치에 따른 추가 최저 요소 감점은 없습니다. 요일·달·노을·일출 요소는 기존 계산을 유지합니다.
- 각 상세 창과 시간대 미리보기의 아침·낮·저녁·밤 점수도 각 구간의 날씨로 계산하며 하루 점수로 대체하지 않습니다.
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다.
- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
## 5. 나들이 점수 (주말 순위·당일치기)
+3 -3
View File
@@ -107,13 +107,13 @@
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
**히어로·띠의 순서**
- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤) 점수 높은 순. 각 시간대가 지금 구간과 안 겹치는 각은 맨 뒤에 '지금 아님'으로.
- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 지금 구간에 해당하는 각만, 지금 구간 점수 순.
- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤)의 날씨 점수로 순위를 매깁니다. 시간대 알맞음은 활동 시간대와 겹치면 가중치만큼, 아니면 0점을 반영합니다. 제철이 아닌 각은 비활성화합니다.
- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 제철인 각을 시간대와 관계없이 포함하고, 지금 구간 점수로 순위를 매깁니다.
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
### 같이 만드는 것
- 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지
- 오늘의 각 줄: 34개 이름·점수·순위 (지금 구간에 안 맞는 각은 '지금 아님')
- 오늘의 각 줄: 34개 이름·점수·순위 (시간대와 관계없이 활성화, 각 구간의 날씨·시간대 적합도로 계산)
- 띠: 행사 4개, 각 순위 5개, 계절 소식
## 3. 저장과 갱신
+2 -2
View File
@@ -2974,7 +2974,7 @@ export type TopIndex = {
/**
* Slot Ranks
*
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
* 오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)
*/
slot_ranks?: {
[key: string]: number;
@@ -3339,7 +3339,7 @@ export type WeekDay = {
/**
* Gaks
*
* 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음
* 그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음
*/
gaks?: Array<WeekGak>;
};
+1 -1
View File
@@ -363,7 +363,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
</div>
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
+1 -1
View File
@@ -106,7 +106,7 @@ const SLOT_KEY: Record<TimeKind, string> = {
night: 'night',
}
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
/** 미리보기 시간대면 서버가 해당 구간의 날씨·시간대 적합도로 계산한 점수·순위로 다시 줄 세운다. 구간 값이 없으면(예전 캐시) 그대로 */
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
const k = kind && SLOT_KEY[kind]
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items