chore: main 병합 — 로그인 없이 댓글·좋아요, 구글 로그인만, 동네 이야기·카드뉴스 등 (차단 표 user_block 하나로 합침, 익명 댓글도 신고 가능)
This commit is contained in:
commit
dba34675c8
408 files changed
+36377
-725
No files matched your search
@@ -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 # 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")
|
||||
@@ -64,12 +64,16 @@ def tim(r):
|
||||
return "달이 어두울수록 좋음 (보름 20점 → 그믐 100점)"
|
||||
if t == "sunset_score":
|
||||
return "그날 노을 점수를 그대로 씀"
|
||||
if t == "sunrise_score":
|
||||
return "그날 일출 하늘 점수를 그대로 씀"
|
||||
return f"고정 {r['value']}점"
|
||||
|
||||
|
||||
def zero(z):
|
||||
if z["field"] == "warning":
|
||||
return f"{z['value']} 특보가 있으면"
|
||||
if z["field"] not in FIELD:
|
||||
return _cond(z)[2] + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
name, unit = FIELD[z["field"]]
|
||||
op = "이상" if z["op"] == ">=" else "미만"
|
||||
s = f"{name} {z['value']}{unit} {op}이면"
|
||||
@@ -83,7 +87,7 @@ def air(r):
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} {'이상이면' if r['full'] > r['zero'] else '이하면'} 만점, {r['zero']} {'이하면' if r['full'] > r['zero'] else '이상이면'} 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)"),
|
||||
("time", "시간·요일", tim)]
|
||||
@@ -105,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("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""나들이 점수 바꾸기 표(services/calc/outing_score_table.json)를 다시 만든다.
|
||||
|
||||
나들이 점수(index_calc.outing: 낮 10~17시, 기온·비·하늘·바람)의 원래 점수를 1년 치 분포의 순위로 보고,
|
||||
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다 (지금 날씨 점수와 같은 방식, scripts/gen_weather_score_table.py).
|
||||
1년 치 날씨는 Open-Meteo 과거 예보로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. 하늘은 구름양 40%·80% 이상을 구름 많음·흐림으로 본다.
|
||||
|
||||
나들이 점수 규칙(OUTING_*)이 바뀌면 실행: cd backend && python scripts/gen_outing_score_table.py
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
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 scripts.gen_weather_score_table import _WEATHER, DAYS, EVERY, MEAN, SIGMA, fetch, straighten_top, table # noqa: E402
|
||||
from services.calc.index_calc import OUTING_HOURS, Hour, outing # 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", "outing_score_table.json")
|
||||
_HOURLY = "apparent_temperature,precipitation,precipitation_probability,wind_speed_10m,cloud_cover"
|
||||
|
||||
|
||||
def region_scores(lat: float, lon: float, start: date, end: date) -> list[int]:
|
||||
"""한 지점의 날마다 나들이 점수(원래 점수). 10~17시가 모두 있는 날만."""
|
||||
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=end.isoformat(), timezone="Asia/Seoul")
|
||||
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
|
||||
at_index = {t: i for i, t in enumerate(w["time"])}
|
||||
out = []
|
||||
day = start
|
||||
while day <= end:
|
||||
hours = []
|
||||
for h in range(*OUTING_HOURS):
|
||||
i = at_index.get(f"{day.isoformat()}T{h:02d}:00")
|
||||
if i is None or w["apparent_temperature"][i] is None:
|
||||
break
|
||||
cloud = w["cloud_cover"][i] or 0
|
||||
hours.append(Hour(
|
||||
hour=h, feels_c=w["apparent_temperature"][i], rain_type=RainType.RAIN if (w["precipitation"][i] or 0) >= 0.1 else RainType.NONE,
|
||||
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=50,
|
||||
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
|
||||
))
|
||||
result = outing(hours) if len(hours) == OUTING_HOURS[1] - OUTING_HOURS[0] else None
|
||||
if result is not None:
|
||||
out.append(result.score)
|
||||
day += timedelta(days=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: list[int] = []
|
||||
for r in regions:
|
||||
scores += region_scores(float(r["lat"]), float(r["lon"]), start, end)
|
||||
LOG.info(f"[outing-table] {r['name']} 완료")
|
||||
time.sleep(1)
|
||||
doc = {
|
||||
"about": f"나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_outing_score_table.py 가 만든다",
|
||||
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": len(scores),
|
||||
"table": straighten_top(table(scores)), # 100점은 원래 점수 100(완벽한 날)일 때만
|
||||
}
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
json.dump(doc, f, ensure_ascii=False, indent=1)
|
||||
print(len(regions), "regions", len(scores), "samples")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""/faq 지역 질문에 넣을 지역별 장소를 시드로 다시 만든다. 시도마다 한 파일: frontend/seo/region_faq/seoul.json
|
||||
|
||||
region.json 이나 place*.csv, sunset_spot.csv 가 바뀌면 실행: python backend/scripts/gen_region_faq.py
|
||||
앱 번들에 들어가는 region.json 을 키우지 않으려고 따로 둔다. vite 빌드가 /faq 를 만들 때만 읽는다.
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SEED = os.path.join(ROOT, "backend", "seed")
|
||||
PAGES = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||
OUT = os.path.join(ROOT, "frontend", "seo", "region_faq")
|
||||
|
||||
OUTDOOR, INDOOR, SUNSET = 3, 2, 2
|
||||
|
||||
|
||||
def rows(name: str) -> list[dict]:
|
||||
return list(csv.DictReader(open(os.path.join(SEED, name), encoding="utf-8")))
|
||||
|
||||
|
||||
# 손으로 고른 장소를 관광공사 장소보다 먼저
|
||||
places = rows("place.csv") + rows("place_tourapi.csv")
|
||||
sunsets = rows("sunset_spot.csv")
|
||||
|
||||
|
||||
def pick(found: list[dict], n: int) -> list[str]:
|
||||
"""아이콘(산책·피크닉·사진…)이 겹치지 않게 먼저 고르고, 모자라면 순서대로 채운다."""
|
||||
out, icons = [], set()
|
||||
for p in found:
|
||||
if p["icon"] not in icons and p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
icons.add(p["icon"])
|
||||
for p in found:
|
||||
if p["name"] not in out:
|
||||
out.append(p["name"])
|
||||
return out[:n]
|
||||
|
||||
|
||||
result = {}
|
||||
for page in json.load(open(PAGES, encoding="utf-8")):
|
||||
names = {r["name"] for r in page["regions"]}
|
||||
mine = [p for p in places if p["region_name"] in names]
|
||||
result[page["path"]] = dict(
|
||||
outdoor=pick([p for p in mine if p["is_outdoor"] == "1"], OUTDOOR),
|
||||
indoor=pick([p for p in mine if p["is_outdoor"] == "0"], INDOOR),
|
||||
sunset=list(dict.fromkeys(s["name"] for s in sunsets if s["region_name"] in names))[:SUNSET],
|
||||
)
|
||||
# 시도마다 한 파일 (seoul.json). 지난번에 만든 시도 파일은 지우고 다시 쓴다
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
for f in os.listdir(OUT):
|
||||
if f.endswith(".json"):
|
||||
os.remove(os.path.join(OUT, f))
|
||||
by_sido = {}
|
||||
for path, spots in result.items():
|
||||
by_sido.setdefault(path.split("/")[0], {})[path] = spots
|
||||
for sido, part in by_sido.items():
|
||||
json.dump(part, open(os.path.join(OUT, f"{sido}.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
||||
print(len(result), "pages", sum(any(v.values()) for v in result.values()), "with places", len(by_sido), "files")
|
||||
@@ -24,6 +24,9 @@ R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin
|
||||
춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang
|
||||
전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split()
|
||||
ROMAN = dict(zip(R[::2], R[1::2]))
|
||||
G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji
|
||||
만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split()
|
||||
GU = dict(zip(G[::2], G[1::2]))
|
||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||
pages = {}
|
||||
@@ -36,8 +39,12 @@ for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||
p['regions'].append(r)
|
||||
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||
p['main'] = r['code']
|
||||
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
||||
if len(rest) == 2:
|
||||
gu = f"{path}/{GU[rest[1][:-1]]}"
|
||||
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
||||
out = list(pages.values())
|
||||
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||
assert sum(len(p['regions']) for p in out) == 256
|
||||
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
||||
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
||||
@@ -0,0 +1,148 @@
|
||||
"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다.
|
||||
|
||||
지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤,
|
||||
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. 맨 위는 straighten_top 으로 100점이 가장 좋은 원래 점수에서만 나오게 한다.
|
||||
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
|
||||
|
||||
|
||||
ANCHOR_SCORE = 83 # 위쪽 끝을 직선으로 잇기 시작하는 표시 점수
|
||||
|
||||
|
||||
def straighten_top(t: list[int], top: int = 100) -> list[int]:
|
||||
"""표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막는다.
|
||||
표시 점수가 ANCHOR_SCORE 이하인 마지막 원래 점수에서 top(그 구간에서 나올 수 있는 가장 높은 원래 점수)의 100점까지 직선으로 잇는다.
|
||||
100점은 원래 점수가 top 이상일 때만 나온다. 그 아래 점수는 바뀌지 않는다."""
|
||||
anchor = max(i for i, v in enumerate(t[: top + 1]) if v <= ANCHOR_SCORE)
|
||||
out = list(t)
|
||||
for raw in range(anchor + 1, 101):
|
||||
out[raw] = 100 if raw >= top else min(99, round(t[anchor] + (100 - t[anchor]) * (raw - anchor) / (top - anchor)))
|
||||
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()},
|
||||
# 밤은 해 난 비율이 늘 0점이라 원래 점수가 100 - 그 비중까지만 나온다
|
||||
"slots": {s: straighten_top(table(v), 100 - WEATHER_SCORE_DEF.weight_sun if s == "night" else 100) 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()
|
||||
Reference in new issue
Block a user