Spaces:
Sleeping

forest-suitability / landslide_api.py
Assefore's picture
add all latest modules
67b3502
Raw History Blame Contribute Delete
3.28 kB
# -*- coding: utf-8 -*-
"""
landslide_api.py
────────────────
산사태위험지도 GeoTIFF에서 클릭 좌표(위경도)의 위험등급(1~5)을 읽는다.
- 래스터 전체를 메모리에 안 올리고 해당 좌표 픽셀 1개만 읽음(빠름).
- 위경도(EPSG:4326) → 산사태도 좌표계(EPSG:5181) 변환 후 조회.
- 시도 코드로 해당 도의 TIF 선택. 압축본({코드}_zip.tif) 우선.
- 로컬에 없으면 data_loader 로 HF dataset 에서 받음. 결과/핸들 캐시.
[등급 정의] 1=가장 위험 … 5=가장 안전. 배경(NoData)=127 → None.
"""
import os
import rasterio
from rasterio.warp import transform as warp_transform
try:
from sido_utils import get_sido_code
except Exception:
def get_sido_code(lat, lng): return None
try:
from data_loader import resolve_data
except Exception:
def resolve_data(p): return p # 로컬 경로 그대로
_BASE = os.path.dirname(os.path.abspath(__file__))
_DIR = os.path.join(_BASE, "tif", "landslide")
_RASTER_CRS = "EPSG:5181" # 산사태위험지도 좌표계 (KGD2002 / Central Belt)
_HANDLES = {} # code -> opened rasterio dataset (재사용)
_MISSING = set()
def _path_for(code):
"""{코드}_zip.tif(압축본) 우선, 없으면 {코드}.tif. 로컬 없으면 HF 다운로드."""
for name in (f"{code}_zip.tif", f"{code}.tif"):
local = os.path.join(_DIR, name)
if os.path.exists(local):
return local
# HF dataset 시도 (data_loader 가 tif/landslide/ 하위를 받도록 구성돼 있으면 사용)
try:
got = resolve_data(local)
if got and os.path.exists(got):
return got
except Exception:
pass
return None
def _dataset(code):
if code in _HANDLES:
return _HANDLES[code]
if code in _MISSING:
return None
path = _path_for(code)
if not path:
_MISSING.add(code)
return None
try:
ds = rasterio.open(path)
_HANDLES[code] = ds
return ds
except Exception:
_MISSING.add(code)
return None
def get_landslide_grade(lat, lng, sido_code=None):
"""
좌표의 산사태 위험등급(1~5) 반환. 데이터 없거나 범위 밖이면 None.
sido_code 를 주면 그 도의 TIF를, 없으면 좌표로 자동 판별.
"""
code = sido_code or get_sido_code(lat, lng)
if not code:
return None
ds = _dataset(code)
if ds is None:
return None
try:
# 위경도 → 래스터 좌표계로 변환
xs, ys = warp_transform("EPSG:4326", ds.crs or _RASTER_CRS, [lng], [lat])
x, y = xs[0], ys[0]
# 좌표 → 행/열 인덱스
row, col = ds.index(x, y)
if not (0 <= row < ds.height and 0 <= col < ds.width):
return None
# 픽셀 1개만 읽기 (windowed)
win = rasterio.windows.Window(col, row, 1, 1)
val = int(ds.read(1, window=win)[0, 0])
if val in (1, 2, 3, 4, 5):
return val
return None # 127(배경) 등
except Exception:
return None
def available(sido_code):
"""해당 도의 산사태 데이터가 있는지."""
return _dataset(sido_code) is not None