- 초단기실황(getUltraSrtNcst)을 받아 지금 정시 한 시각의 비·기온·습도·바람을 예보 대신 관측값으로 덮어씀 (체감·불쾌지수는 다시 계산). 지역별 1시간 캐시, 실패하면 초단기예보·단기예보로 되돌아감, 새 시각 실황이 나오면 각 점수를 다시 계산. 가이드대로 ±900 이상은 결측 처리. 테스트가 실제 기상청을 부르지 않게 실황 호출을 기본으로 막음 - 시간대 알맞음 요소를 31개 각에서 빼고 비중을 5% 단위로 나눔. 요소가 3개 미만이 된 뜨아각·파전각·감성노래각·감사각·선크림각에 요소를 더함. 러닝각의 활동 시간대 밖 점수 상한도 없앰. 요소가 하나뿐인 각은 가장 낮은 요소로 깎지 않음 - 우산각은 비 한 가지: 남은 하루(지금~자정) 비 확률 평균이 점수, 지금 비가 오면 70점에서 시작해 평균 × 30점을 더함. 내일·토·일 칸은 그날 6~24시 평균 × 100. 우산분실각도 비 한 가지 - 각 계산 기준 문서는 생성기를 새 규칙에 맞게 고쳐 다시 생성, 점수 계산식·서비스 동작 안내 문서 갱신
194 lines
8.9 KiB
Python
194 lines
8.9 KiB
Python
import re
|
|
from datetime import date, datetime, timedelta
|
|
from typing import Optional
|
|
|
|
import httpx
|
|
|
|
from common.enums import RainType, Sky
|
|
from common.utils.kma_time import KST
|
|
from services.external.data_go_kr import get_all_items
|
|
|
|
VILAGE_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
|
|
ULTRA_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst"
|
|
NCST_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst"
|
|
WARNING_URL = "https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd"
|
|
_SKY = {"1": Sky.CLEAR, "3": Sky.PARTLY, "4": Sky.CLOUDY}
|
|
# 단기예보 0~4, 초단기예보는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림이 더 있다
|
|
_PTY = {"0": RainType.NONE, "1": RainType.RAIN, "2": RainType.SLEET, "3": RainType.SNOW, "4": RainType.SHOWER,
|
|
"5": RainType.RAIN, "6": RainType.SLEET, "7": RainType.SNOW}
|
|
_REQUIRED = ("TMP", "SKY", "PTY", "POP", "REH")
|
|
|
|
|
|
def parse_amount(value: str) -> float:
|
|
"""기상청 강수량·적설 글자를 숫자로. "강수없음"→0, "1mm 미만"→0.5, "30.0~50.0mm"→30, "50.0mm 이상"→50."""
|
|
v = value.strip()
|
|
if v in ("", "강수없음", "적설없음"):
|
|
return 0.0
|
|
if "미만" in v:
|
|
return 0.5
|
|
m = re.search(r"\d+(\.\d+)?", v)
|
|
return float(m.group()) if m else 0.0
|
|
|
|
|
|
async def fetch_vilage(client: httpx.AsyncClient, nx: int, ny: int, base: datetime) -> list[dict]:
|
|
base = base.astimezone(KST)
|
|
params = {"dataType": "JSON", "base_date": base.strftime("%Y%m%d"), "base_time": base.strftime("%H%M"), "nx": nx, "ny": ny}
|
|
return await get_all_items(client, VILAGE_URL, params)
|
|
|
|
|
|
async def fetch_ultra(client: httpx.AsyncClient, nx: int, ny: int, base: datetime) -> list[dict]:
|
|
base = base.astimezone(KST)
|
|
params = {"dataType": "JSON", "base_date": base.strftime("%Y%m%d"), "base_time": base.strftime("%H%M"), "nx": nx, "ny": ny}
|
|
return await get_all_items(client, ULTRA_URL, params, page_size=100)
|
|
|
|
|
|
async def fetch_ncst(client: httpx.AsyncClient, nx: int, ny: int, base: datetime) -> list[dict]:
|
|
base = base.astimezone(KST)
|
|
params = {"dataType": "JSON", "base_date": base.strftime("%Y%m%d"), "base_time": base.strftime("%H%M"), "nx": nx, "ny": ny}
|
|
return await get_all_items(client, NCST_URL, params, page_size=100)
|
|
|
|
|
|
async def fetch_warning_events(client: httpx.AsyncClient, since: datetime, until: datetime) -> list[dict]:
|
|
params = {"dataType": "JSON", "fromTmFc": since.astimezone(KST).strftime("%Y%m%d"), "toTmFc": until.astimezone(KST).strftime("%Y%m%d")}
|
|
return await get_all_items(client, WARNING_URL, params)
|
|
|
|
|
|
def parse_vilage(items: list[dict]) -> tuple[dict[datetime, dict], dict[date, dict]]:
|
|
"""줄 단위 응답을 시각별·날짜별 우리 형식으로 묶는다."""
|
|
by_time: dict[datetime, dict[str, str]] = {}
|
|
for it in items:
|
|
at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST)
|
|
by_time.setdefault(at, {})[it["category"]] = it["fcstValue"]
|
|
|
|
hourly: dict[datetime, dict] = {}
|
|
daily: dict[date, dict] = {}
|
|
for at, v in sorted(by_time.items()):
|
|
if "TMN" in v:
|
|
daily.setdefault(at.date(), {})["temp_min_c"] = float(v["TMN"])
|
|
if "TMX" in v:
|
|
daily.setdefault(at.date(), {})["temp_max_c"] = float(v["TMX"])
|
|
if not all(k in v for k in _REQUIRED):
|
|
continue
|
|
hourly[at] = {
|
|
"temp_c": float(v["TMP"]),
|
|
"sky": _SKY[v["SKY"]],
|
|
"rain_type": _PTY[v["PTY"]],
|
|
"rain_prob": int(v["POP"]),
|
|
"rain_mm": parse_amount(v.get("PCP", "")),
|
|
"humidity": int(v["REH"]),
|
|
"wind_ms": float(v["WSD"]) if "WSD" in v else None,
|
|
}
|
|
return hourly, daily
|
|
|
|
|
|
def day_start_base(day: date) -> datetime:
|
|
"""그날 0시 칸부터 들어 있는 발표 = 전날 23시 발표."""
|
|
return datetime.combine(day - timedelta(days=1), datetime.min.time(), tzinfo=KST).replace(hour=23)
|
|
|
|
|
|
def parse_ultra(items: list[dict]) -> list[dict]:
|
|
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온·낙뢰(LGT, 0 이면 없음)."""
|
|
by_time: dict[datetime, dict[str, str]] = {}
|
|
for it in items:
|
|
at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST)
|
|
by_time.setdefault(at, {})[it["category"]] = it["fcstValue"]
|
|
return [
|
|
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"]), "lightning": parse_amount(v.get("LGT", "")) > 0}
|
|
for at, v in sorted(by_time.items())
|
|
if "PTY" in v and "T1H" in v
|
|
]
|
|
|
|
|
|
_NCST_FIELDS = ("PTY", "RN1", "T1H", "REH", "WSD")
|
|
_MISSING = 900 # 가이드: +900 이상, -900 이하 값은 결측
|
|
|
|
|
|
def parse_ncst(items: list[dict]) -> Optional[dict]:
|
|
"""초단기실황: 지금 관측한 비 형태·1시간 강수량·기온·습도·풍속. 하나라도 없거나 결측이면 None."""
|
|
v = {it["category"]: it["obsrValue"] for it in items}
|
|
if not all(k in v for k in _NCST_FIELDS):
|
|
return None
|
|
try:
|
|
nums = {k: float(v[k]) for k in ("RN1", "T1H", "REH", "WSD")}
|
|
rain_type = _PTY[v["PTY"]]
|
|
except (ValueError, KeyError):
|
|
return None
|
|
if any(abs(n) >= _MISSING for n in nums.values()):
|
|
return None
|
|
return {"rain_type": rain_type, "rain_mm": nums["RN1"], "temp_c": nums["T1H"], "humidity": round(nums["REH"]), "wind_ms": nums["WSD"]}
|
|
|
|
|
|
_ACTIVE_COMMANDS = {1, 3, 6, 7}
|
|
|
|
|
|
def active_warnings(events: list[dict]) -> list[dict]:
|
|
"""발표·해제 이력에서 구역·종류별 마지막 기록이 발표 쪽이면 지금 발효 중으로 본다. 육상 구역(L)만."""
|
|
latest: dict[tuple[str, int], dict] = {}
|
|
for e in sorted(events, key=lambda e: (int(e["tmFc"]), int(e["tmSeq"]))):
|
|
if str(e["areaCode"]).startswith("L"):
|
|
latest[(e["areaCode"], int(e["warnVar"]))] = e
|
|
return [
|
|
{"warning_zone_code": zone, "warning_type": var, "level": int(e["warnStress"]) + 1}
|
|
for (zone, var), e in latest.items()
|
|
if int(e["command"]) in _ACTIVE_COMMANDS and str(e.get("cancel", "0")) == "0"
|
|
]
|
|
|
|
|
|
MID_LAND_URL = "https://apis.data.go.kr/1360000/MidFcstInfoService/getMidLandFcst"
|
|
MID_TA_URL = "https://apis.data.go.kr/1360000/MidFcstInfoService/getMidTa"
|
|
MID_DAYS = range(4, 11)
|
|
|
|
|
|
async def fetch_mid(client: httpx.AsyncClient, land_code: str, temp_code: str, base: datetime) -> tuple[dict, dict]:
|
|
tm = base.astimezone(KST).strftime("%Y%m%d%H%M")
|
|
land = await get_all_items(client, MID_LAND_URL, {"dataType": "JSON", "regId": land_code, "tmFc": tm}, page_size=10)
|
|
ta = await get_all_items(client, MID_TA_URL, {"dataType": "JSON", "regId": temp_code, "tmFc": tm}, page_size=10)
|
|
return (land[0] if land else {}), (ta[0] if ta else {})
|
|
|
|
|
|
def mid_word(text: str) -> tuple[Sky, RainType]:
|
|
"""중기예보 날씨 글자("흐리고 비", "구름많고 소나기" 등)를 하늘·강수로."""
|
|
sky = Sky.CLEAR if text.startswith("맑") else Sky.PARTLY if text.startswith("구름") else Sky.CLOUDY
|
|
if "비/눈" in text or "비 또는 눈" in text:
|
|
return sky, RainType.SLEET
|
|
if "소나기" in text:
|
|
return sky, RainType.SHOWER
|
|
if "눈" in text:
|
|
return sky, RainType.SNOW
|
|
if "비" in text:
|
|
return sky, RainType.RAIN
|
|
return sky, RainType.NONE
|
|
|
|
|
|
def parse_mid(land: dict, ta: dict, base: datetime) -> dict[date, dict]:
|
|
"""발표일 기준 n일 뒤(4~10)의 하루 날씨. 오전·오후로 나뉜 날은 비가 오는 쪽·흐린 쪽을 대표로."""
|
|
days: dict[date, dict] = {}
|
|
base_day = base.astimezone(KST).date()
|
|
for n in MID_DAYS:
|
|
texts = [land.get(k) for k in (f"wf{n}Am", f"wf{n}Pm", f"wf{n}") if land.get(k)]
|
|
probs = [land.get(k) for k in (f"rnSt{n}Am", f"rnSt{n}Pm", f"rnSt{n}") if land.get(k) is not None]
|
|
if not texts or f"taMax{n}" not in ta:
|
|
continue
|
|
parsed = [mid_word(t) for t in texts]
|
|
rains = [r for _, r in parsed if r is not RainType.NONE]
|
|
days[base_day + timedelta(days=n)] = {
|
|
"temp_min_c": float(ta[f"taMin{n}"]), "temp_max_c": float(ta[f"taMax{n}"]),
|
|
"sky": max((s for s, _ in parsed), key=lambda s: s.value), "rain_type": rains[0] if rains else RainType.NONE,
|
|
"rain_prob": max(probs) if probs else 0,
|
|
"rain_prob_am": land.get(f"rnSt{n}Am", land.get(f"rnSt{n}", 0)),
|
|
"rain_prob_pm": land.get(f"rnSt{n}Pm", land.get(f"rnSt{n}", 0)),
|
|
}
|
|
return days
|
|
|
|
|
|
def latest_mid_base(now: datetime) -> datetime:
|
|
"""중기예보는 06·18시 발표. 30분 여유를 둔다."""
|
|
now = now.astimezone(KST)
|
|
for d in (0, 1):
|
|
day = (now - timedelta(days=d)).date()
|
|
for h in (18, 6):
|
|
base = datetime.combine(day, datetime.min.time(), tzinfo=KST).replace(hour=h)
|
|
if base + timedelta(minutes=30) <= now:
|
|
return base
|
|
raise AssertionError("unreachable")
|