python-arus 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- arus/__init__.py +44 -0
- arus/client.py +144 -0
- arus/exceptions.py +32 -0
- arus/models.py +370 -0
- python_arus-0.1.0.dist-info/METADATA +67 -0
- python_arus-0.1.0.dist-info/RECORD +9 -0
- python_arus-0.1.0.dist-info/WHEEL +5 -0
- python_arus-0.1.0.dist-info/licenses/LICENSE +21 -0
- python_arus-0.1.0.dist-info/top_level.txt +1 -0
arus/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Asynchronous Python client for ARUS, JKM InfoBencana, and METMalaysia feeds."""
|
|
2
|
+
|
|
3
|
+
from .client import ArusClient, DEFAULT_ARUS_BASE_URL
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
ArusApiError,
|
|
6
|
+
ArusConnectionError,
|
|
7
|
+
ArusError,
|
|
8
|
+
ArusRateLimitError,
|
|
9
|
+
)
|
|
10
|
+
from .models import (
|
|
11
|
+
BasinContext,
|
|
12
|
+
BasinGrid,
|
|
13
|
+
BasinGridSummary,
|
|
14
|
+
BasinMeta,
|
|
15
|
+
PointFloodSample,
|
|
16
|
+
Shelter,
|
|
17
|
+
ShelterSummary,
|
|
18
|
+
WeatherPoint,
|
|
19
|
+
WeatherPointStep,
|
|
20
|
+
WeatherWarning,
|
|
21
|
+
classify_flood_risk,
|
|
22
|
+
haversine_km,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"ArusApiError",
|
|
27
|
+
"ArusClient",
|
|
28
|
+
"ArusConnectionError",
|
|
29
|
+
"ArusError",
|
|
30
|
+
"ArusRateLimitError",
|
|
31
|
+
"BasinContext",
|
|
32
|
+
"BasinGrid",
|
|
33
|
+
"BasinGridSummary",
|
|
34
|
+
"BasinMeta",
|
|
35
|
+
"DEFAULT_ARUS_BASE_URL",
|
|
36
|
+
"PointFloodSample",
|
|
37
|
+
"Shelter",
|
|
38
|
+
"ShelterSummary",
|
|
39
|
+
"WeatherPoint",
|
|
40
|
+
"WeatherPointStep",
|
|
41
|
+
"WeatherWarning",
|
|
42
|
+
"classify_flood_risk",
|
|
43
|
+
"haversine_km",
|
|
44
|
+
]
|
arus/client.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Asynchronous client for ARUS, JKM InfoBencana, and METMalaysia feeds."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import aiohttp
|
|
9
|
+
|
|
10
|
+
from .exceptions import ArusApiError, ArusConnectionError, ArusRateLimitError
|
|
11
|
+
from .models import (
|
|
12
|
+
BasinContext,
|
|
13
|
+
BasinGrid,
|
|
14
|
+
BasinMeta,
|
|
15
|
+
ShelterSummary,
|
|
16
|
+
WeatherPoint,
|
|
17
|
+
WeatherWarning,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
DEFAULT_ARUS_BASE_URL = "https://arus.mata.ngo"
|
|
21
|
+
DEFAULT_JKM_URL = "https://infobencanajkmv2.jkm.gov.my/api/pusat-buka.php?a=0&b=0"
|
|
22
|
+
DEFAULT_DATAGOV_WARNING_URL = "https://api.data.gov.my/weather/warning/"
|
|
23
|
+
DEFAULT_USER_AGENT = "python-arus/0.1.0 (+https://github.com/zubirjamal/python-arus)"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ArusClient:
|
|
27
|
+
"""Async API client combining official Malaysian feeds with ARUS physics outlook."""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
session: aiohttp.ClientSession | None = None,
|
|
32
|
+
base_url: str = DEFAULT_ARUS_BASE_URL,
|
|
33
|
+
timeout: float = 20.0,
|
|
34
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
35
|
+
) -> None:
|
|
36
|
+
self._session = session
|
|
37
|
+
self._owns_session = session is None
|
|
38
|
+
self._base_url = base_url.rstrip("/")
|
|
39
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
40
|
+
self._user_agent = user_agent
|
|
41
|
+
self._grid_cache: dict[str, BasinGrid] = {}
|
|
42
|
+
|
|
43
|
+
async def __aenter__(self) -> ArusClient:
|
|
44
|
+
if self._session is None:
|
|
45
|
+
self._session = aiohttp.ClientSession(timeout=self._timeout)
|
|
46
|
+
self._owns_session = True
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
async def __aexit__(self, *_: object) -> None:
|
|
50
|
+
await self.close()
|
|
51
|
+
|
|
52
|
+
async def close(self) -> None:
|
|
53
|
+
"""Close the owned aiohttp session."""
|
|
54
|
+
if self._owns_session and self._session is not None and not self._session.closed:
|
|
55
|
+
await self._session.close()
|
|
56
|
+
self._session = None
|
|
57
|
+
|
|
58
|
+
async def _get_json(self, url: str, params: dict[str, Any] | None = None) -> Any:
|
|
59
|
+
if self._session is None:
|
|
60
|
+
self._session = aiohttp.ClientSession(timeout=self._timeout)
|
|
61
|
+
self._owns_session = True
|
|
62
|
+
headers = {"User-Agent": self._user_agent, "Accept": "application/json"}
|
|
63
|
+
try:
|
|
64
|
+
async with self._session.get(
|
|
65
|
+
url,
|
|
66
|
+
params=params,
|
|
67
|
+
headers=headers,
|
|
68
|
+
timeout=self._timeout,
|
|
69
|
+
) as resp:
|
|
70
|
+
if resp.status in (429, 503):
|
|
71
|
+
retry_raw = resp.headers.get("Retry-After")
|
|
72
|
+
retry_after = float(retry_raw) if retry_raw and retry_raw.isdigit() else None
|
|
73
|
+
raise ArusRateLimitError(
|
|
74
|
+
f"Rate limited by {url} (HTTP {resp.status})",
|
|
75
|
+
status=resp.status,
|
|
76
|
+
retry_after=retry_after,
|
|
77
|
+
)
|
|
78
|
+
if resp.status >= 400:
|
|
79
|
+
raise ArusApiError(
|
|
80
|
+
f"HTTP {resp.status} from {url}",
|
|
81
|
+
status=resp.status,
|
|
82
|
+
)
|
|
83
|
+
return await resp.json(content_type=None)
|
|
84
|
+
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
|
|
85
|
+
raise ArusConnectionError(f"Request failed for {url}: {err}") from err
|
|
86
|
+
|
|
87
|
+
# --- Official Malaysian Endpoints (zero load on ARUS) ---
|
|
88
|
+
|
|
89
|
+
async def get_shelters(
|
|
90
|
+
self,
|
|
91
|
+
lat: float | None = None,
|
|
92
|
+
lon: float | None = None,
|
|
93
|
+
) -> ShelterSummary:
|
|
94
|
+
"""Fetch live PPS relief centers directly from JKM InfoBencana."""
|
|
95
|
+
data = await self._get_json(DEFAULT_JKM_URL)
|
|
96
|
+
if not isinstance(data, dict):
|
|
97
|
+
raise ArusApiError("Unexpected JKM InfoBencana response format")
|
|
98
|
+
return ShelterSummary.from_jkm_payload(data, ref_lat=lat, ref_lon=lon)
|
|
99
|
+
|
|
100
|
+
async def get_weather_warnings(self) -> list[WeatherWarning]:
|
|
101
|
+
"""Fetch official METMalaysia weather warnings from api.data.gov.my."""
|
|
102
|
+
data = await self._get_json(DEFAULT_DATAGOV_WARNING_URL)
|
|
103
|
+
if not isinstance(data, list):
|
|
104
|
+
raise ArusApiError("Unexpected data.gov.my warning response format")
|
|
105
|
+
return [WeatherWarning.from_dict(item) for item in data]
|
|
106
|
+
|
|
107
|
+
# --- ARUS Endpoints (gentle polling + cycle_iso-gated grid cache) ---
|
|
108
|
+
|
|
109
|
+
async def get_basins(self) -> list[BasinMeta]:
|
|
110
|
+
"""List all precalculated river basins from ARUS."""
|
|
111
|
+
data = await self._get_json(f"{self._base_url}/api/v1/live/basins")
|
|
112
|
+
return [BasinMeta.from_dict(item) for item in (data.get("meta") or [])]
|
|
113
|
+
|
|
114
|
+
async def get_context(self, lat: float, lon: float) -> BasinContext:
|
|
115
|
+
"""Fetch ARUS basin context & NWP/tide outlook for a coordinate."""
|
|
116
|
+
data = await self._get_json(
|
|
117
|
+
f"{self._base_url}/api/v1/context",
|
|
118
|
+
params={"lat": lat, "lon": lon},
|
|
119
|
+
)
|
|
120
|
+
return BasinContext.from_dict(data)
|
|
121
|
+
|
|
122
|
+
async def get_weather_point(self, lat: float, lon: float) -> WeatherPoint:
|
|
123
|
+
"""Fetch ARUS multi-model NWP point forecast."""
|
|
124
|
+
data = await self._get_json(
|
|
125
|
+
f"{self._base_url}/api/v1/weather/point",
|
|
126
|
+
params={"lat": lat, "lon": lon},
|
|
127
|
+
)
|
|
128
|
+
return WeatherPoint.from_dict(data)
|
|
129
|
+
|
|
130
|
+
async def get_basin_grid(
|
|
131
|
+
self,
|
|
132
|
+
basin_id: str,
|
|
133
|
+
cycle_iso: str | None = None,
|
|
134
|
+
force: bool = False,
|
|
135
|
+
) -> BasinGrid:
|
|
136
|
+
"""Fetch 128x128 basin flood grid, skipping download if cycle_iso is unchanged."""
|
|
137
|
+
cached = self._grid_cache.get(basin_id)
|
|
138
|
+
if not force and cached is not None and cycle_iso and cached.cycle_iso == cycle_iso:
|
|
139
|
+
return cached
|
|
140
|
+
|
|
141
|
+
data = await self._get_json(f"{self._base_url}/api/v1/live/{basin_id}/grid")
|
|
142
|
+
grid = BasinGrid.from_dict(basin_id, data, cycle_iso=cycle_iso or "")
|
|
143
|
+
self._grid_cache[basin_id] = grid
|
|
144
|
+
return grid
|
arus/exceptions.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Exceptions for python-arus."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ArusError(Exception):
|
|
7
|
+
"""Base exception for python-arus."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ArusConnectionError(ArusError):
|
|
11
|
+
"""Raised when a network or timeout error occurs."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ArusApiError(ArusError):
|
|
15
|
+
"""Raised when an upstream API returns an unexpected HTTP status or payload."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message: str, status: int | None = None) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.status = status
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ArusRateLimitError(ArusApiError):
|
|
23
|
+
"""Raised when an upstream API returns HTTP 429 or 503 with Retry-After."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str,
|
|
28
|
+
status: int | None = None,
|
|
29
|
+
retry_after: float | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message, status=status)
|
|
32
|
+
self.retry_after = retry_after
|
arus/models.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""Data models and geospatial helpers for python-arus."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
import math
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
11
|
+
"""Return great-circle distance in kilometres between two WGS84 points."""
|
|
12
|
+
r = 6371.0
|
|
13
|
+
phi1, phi2 = math.radians(lat1), math.radians(lat2)
|
|
14
|
+
dphi = math.radians(lat2 - lat1)
|
|
15
|
+
dlambda = math.radians(lon2 - lon1)
|
|
16
|
+
a = (
|
|
17
|
+
math.sin(dphi / 2.0) ** 2
|
|
18
|
+
+ math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2
|
|
19
|
+
)
|
|
20
|
+
return 2.0 * r * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def classify_flood_risk(depth_m: float) -> str:
|
|
24
|
+
"""Classify flood risk tier from water depth in metres."""
|
|
25
|
+
if depth_m >= 1.2:
|
|
26
|
+
return "danger"
|
|
27
|
+
if depth_m >= 0.5:
|
|
28
|
+
return "high"
|
|
29
|
+
if depth_m >= 0.15:
|
|
30
|
+
return "moderate"
|
|
31
|
+
return "low"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True)
|
|
35
|
+
class Shelter:
|
|
36
|
+
"""Active JKM InfoBencana relief center (PPS)."""
|
|
37
|
+
|
|
38
|
+
id: int
|
|
39
|
+
name: str
|
|
40
|
+
latitude: float
|
|
41
|
+
longitude: float
|
|
42
|
+
state: str
|
|
43
|
+
district: str
|
|
44
|
+
mukim: str
|
|
45
|
+
disaster_type: str
|
|
46
|
+
victims: int
|
|
47
|
+
families: int
|
|
48
|
+
capacity_pct: float
|
|
49
|
+
distance_km: float | None = None
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_dict(
|
|
53
|
+
cls,
|
|
54
|
+
data: dict[str, Any],
|
|
55
|
+
ref_lat: float | None = None,
|
|
56
|
+
ref_lon: float | None = None,
|
|
57
|
+
) -> Shelter:
|
|
58
|
+
"""Parse a JKM InfoBencana or ARUS shelter dictionary."""
|
|
59
|
+
lat = float(data.get("latti") or data.get("latitude") or 0.0)
|
|
60
|
+
lon = float(data.get("longi") or data.get("longitude") or 0.0)
|
|
61
|
+
dist = (
|
|
62
|
+
round(haversine_km(ref_lat, ref_lon, lat, lon), 2)
|
|
63
|
+
if ref_lat is not None and ref_lon is not None and lat and lon
|
|
64
|
+
else None
|
|
65
|
+
)
|
|
66
|
+
return cls(
|
|
67
|
+
id=int(data.get("id", 0)),
|
|
68
|
+
name=str(data.get("name", "")).strip(),
|
|
69
|
+
latitude=lat,
|
|
70
|
+
longitude=lon,
|
|
71
|
+
state=str(data.get("negeri") or data.get("state") or "").strip(),
|
|
72
|
+
district=str(data.get("daerah") or data.get("district") or "").strip(),
|
|
73
|
+
mukim=str(data.get("mukim") or "").strip(),
|
|
74
|
+
disaster_type=str(data.get("bencana") or data.get("disaster_type") or "").strip(),
|
|
75
|
+
victims=int(data.get("mangsa") or data.get("victims") or 0),
|
|
76
|
+
families=int(data.get("keluarga") or data.get("families") or 0),
|
|
77
|
+
capacity_pct=round(float(data.get("kapasiti") or data.get("capacity_pct") or 0.0), 1),
|
|
78
|
+
distance_km=dist,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(slots=True)
|
|
83
|
+
class ShelterSummary:
|
|
84
|
+
"""Aggregated JKM InfoBencana relief center snapshot."""
|
|
85
|
+
|
|
86
|
+
total_points: int
|
|
87
|
+
active_flood_pps_count: int
|
|
88
|
+
total_flood_victims: int
|
|
89
|
+
affected_states: list[str]
|
|
90
|
+
shelters: list[Shelter] = field(default_factory=list)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_jkm_payload(
|
|
94
|
+
cls,
|
|
95
|
+
data: dict[str, Any],
|
|
96
|
+
ref_lat: float | None = None,
|
|
97
|
+
ref_lon: float | None = None,
|
|
98
|
+
) -> ShelterSummary:
|
|
99
|
+
"""Build summary directly from official JKM pusat-buka.php payload."""
|
|
100
|
+
raw_points = data.get("points") or []
|
|
101
|
+
shelters = [
|
|
102
|
+
Shelter.from_dict(item, ref_lat=ref_lat, ref_lon=ref_lon)
|
|
103
|
+
for item in raw_points
|
|
104
|
+
]
|
|
105
|
+
if ref_lat is not None and ref_lon is not None:
|
|
106
|
+
shelters.sort(key=lambda s: s.distance_km if s.distance_km is not None else float("inf"))
|
|
107
|
+
flood_shelters = [s for s in shelters if s.disaster_type.lower() == "banjir"]
|
|
108
|
+
states = sorted({s.state for s in flood_shelters if s.state})
|
|
109
|
+
return cls(
|
|
110
|
+
total_points=len(shelters),
|
|
111
|
+
active_flood_pps_count=len(flood_shelters),
|
|
112
|
+
total_flood_victims=sum(s.victims for s in flood_shelters),
|
|
113
|
+
affected_states=states,
|
|
114
|
+
shelters=shelters,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(slots=True)
|
|
119
|
+
class WeatherWarning:
|
|
120
|
+
"""Official METMalaysia weather warning from api.data.gov.my."""
|
|
121
|
+
|
|
122
|
+
issued: str
|
|
123
|
+
title_en: str
|
|
124
|
+
title_bm: str
|
|
125
|
+
heading_en: str
|
|
126
|
+
heading_bm: str
|
|
127
|
+
text_en: str
|
|
128
|
+
text_bm: str
|
|
129
|
+
valid_from: str
|
|
130
|
+
valid_to: str
|
|
131
|
+
|
|
132
|
+
@classmethod
|
|
133
|
+
def from_dict(cls, data: dict[str, Any]) -> WeatherWarning:
|
|
134
|
+
"""Parse a METMalaysia warning record."""
|
|
135
|
+
issue = data.get("warning_issue") or {}
|
|
136
|
+
return cls(
|
|
137
|
+
issued=str(issue.get("issued") or ""),
|
|
138
|
+
title_en=str(issue.get("title_en") or ""),
|
|
139
|
+
title_bm=str(issue.get("title_bm") or ""),
|
|
140
|
+
heading_en=str(data.get("heading_en") or ""),
|
|
141
|
+
heading_bm=str(data.get("heading_bm") or ""),
|
|
142
|
+
text_en=str(data.get("text_en") or ""),
|
|
143
|
+
text_bm=str(data.get("text_bm") or ""),
|
|
144
|
+
valid_from=str(data.get("valid_from") or ""),
|
|
145
|
+
valid_to=str(data.get("valid_to") or ""),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(slots=True)
|
|
150
|
+
class BasinMeta:
|
|
151
|
+
"""Metadata for a precalculated ARUS river basin."""
|
|
152
|
+
|
|
153
|
+
id: str
|
|
154
|
+
cols: int
|
|
155
|
+
rows: int
|
|
156
|
+
dx_m: float
|
|
157
|
+
tier: str
|
|
158
|
+
has_context: bool
|
|
159
|
+
wgs84_bounds: tuple[float, float, float, float]
|
|
160
|
+
|
|
161
|
+
@classmethod
|
|
162
|
+
def from_dict(cls, data: dict[str, Any]) -> BasinMeta:
|
|
163
|
+
"""Parse basin metadata from /api/v1/live/basins."""
|
|
164
|
+
bounds = data.get("wgs84_bounds") or [0.0, 0.0, 0.0, 0.0]
|
|
165
|
+
return cls(
|
|
166
|
+
id=str(data["id"]),
|
|
167
|
+
cols=int(data.get("cols", 0)),
|
|
168
|
+
rows=int(data.get("rows", 0)),
|
|
169
|
+
dx_m=float(data.get("dx_m", 0.0)),
|
|
170
|
+
tier=str(data.get("tier", "regional")),
|
|
171
|
+
has_context=bool(data.get("has_context", False)),
|
|
172
|
+
wgs84_bounds=(float(bounds[0]), float(bounds[1]), float(bounds[2]), float(bounds[3])),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(slots=True)
|
|
177
|
+
class BasinContext:
|
|
178
|
+
"""ARUS /api/v1/context response for a coordinate."""
|
|
179
|
+
|
|
180
|
+
basin_id: str
|
|
181
|
+
wgs84_bounds: tuple[float, float, float, float]
|
|
182
|
+
cycle_iso: str
|
|
183
|
+
valid_until_iso: str
|
|
184
|
+
antecedent_rain_mm: float
|
|
185
|
+
observed_gauges: list[dict[str, Any]]
|
|
186
|
+
active_incidents: list[dict[str, Any]]
|
|
187
|
+
warnings: list[dict[str, Any]]
|
|
188
|
+
hourly_tide_m: list[float]
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def from_dict(cls, data: dict[str, Any]) -> BasinContext:
|
|
192
|
+
"""Parse /api/v1/context payload."""
|
|
193
|
+
ctx = data.get("context", data)
|
|
194
|
+
bounds = ctx.get("wgs84_bounds") or [0.0, 0.0, 0.0, 0.0]
|
|
195
|
+
return cls(
|
|
196
|
+
basin_id=str(ctx.get("basin_id", "")),
|
|
197
|
+
wgs84_bounds=(float(bounds[0]), float(bounds[1]), float(bounds[2]), float(bounds[3])),
|
|
198
|
+
cycle_iso=str(ctx.get("cycle_iso", "")),
|
|
199
|
+
valid_until_iso=str(ctx.get("valid_until_iso", "")),
|
|
200
|
+
antecedent_rain_mm=float(ctx.get("antecedent_rain_mm", 0.0)),
|
|
201
|
+
observed_gauges=list(ctx.get("observed_gauges") or []),
|
|
202
|
+
active_incidents=list(ctx.get("active_incidents") or []),
|
|
203
|
+
warnings=list(ctx.get("warnings") or []),
|
|
204
|
+
hourly_tide_m=[float(x) for x in (ctx.get("hourly_tide_m") or [])],
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass(slots=True)
|
|
209
|
+
class WeatherPointStep:
|
|
210
|
+
"""Single hourly/step forecast from ARUS /api/v1/weather/point."""
|
|
211
|
+
|
|
212
|
+
step_h: int
|
|
213
|
+
rain_3h_mm: float
|
|
214
|
+
wind_speed_kmh: float
|
|
215
|
+
wind_dir_deg: float
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def from_dict(cls, data: dict[str, Any]) -> WeatherPointStep:
|
|
219
|
+
"""Parse a single weather step."""
|
|
220
|
+
return cls(
|
|
221
|
+
step_h=int(data.get("step_h", 0)),
|
|
222
|
+
rain_3h_mm=float(data.get("rain_3h_mm", 0.0)),
|
|
223
|
+
wind_speed_kmh=float(data.get("wind_speed_kmh", 0.0)),
|
|
224
|
+
wind_dir_deg=float(data.get("wind_dir_deg", 0.0)),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@dataclass(slots=True)
|
|
229
|
+
class WeatherPoint:
|
|
230
|
+
"""ARUS /api/v1/weather/point response."""
|
|
231
|
+
|
|
232
|
+
lat: float
|
|
233
|
+
lon: float
|
|
234
|
+
run_utc: str
|
|
235
|
+
sources: list[str]
|
|
236
|
+
steps: list[WeatherPointStep]
|
|
237
|
+
|
|
238
|
+
@classmethod
|
|
239
|
+
def from_dict(cls, data: dict[str, Any]) -> WeatherPoint:
|
|
240
|
+
"""Parse /api/v1/weather/point payload."""
|
|
241
|
+
return cls(
|
|
242
|
+
lat=float(data.get("lat", 0.0)),
|
|
243
|
+
lon=float(data.get("lon", 0.0)),
|
|
244
|
+
run_utc=str(data.get("run_utc", "")),
|
|
245
|
+
sources=list(data.get("sources") or []),
|
|
246
|
+
steps=[WeatherPointStep.from_dict(s) for s in (data.get("steps") or [])],
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@dataclass(slots=True)
|
|
251
|
+
class PointFloodSample:
|
|
252
|
+
"""Point-sampled flood metrics at a specific coordinate."""
|
|
253
|
+
|
|
254
|
+
basin_id: str
|
|
255
|
+
depth_m: float
|
|
256
|
+
speed_m_s: float
|
|
257
|
+
hazard_m2_s: float
|
|
258
|
+
onset_time_s: float | None
|
|
259
|
+
risk_level: str
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@dataclass(slots=True)
|
|
263
|
+
class BasinGridSummary:
|
|
264
|
+
"""Recorder-safe summary of a 128x128 basin grid."""
|
|
265
|
+
|
|
266
|
+
basin_id: str
|
|
267
|
+
run_id: str
|
|
268
|
+
cycle_iso: str
|
|
269
|
+
cols: int
|
|
270
|
+
rows: int
|
|
271
|
+
dx_m: float
|
|
272
|
+
wgs84_bounds: tuple[float, float, float, float]
|
|
273
|
+
peak_depth_m: float
|
|
274
|
+
avg_depth_m: float
|
|
275
|
+
flooded_cells: int
|
|
276
|
+
flooded_pct: float
|
|
277
|
+
flooded_area_km2: float
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@dataclass(slots=True)
|
|
281
|
+
class BasinGrid:
|
|
282
|
+
"""Full ARUS /api/v1/live/{basin}/grid payload (kept out of HA attributes)."""
|
|
283
|
+
|
|
284
|
+
basin_id: str
|
|
285
|
+
run_id: str
|
|
286
|
+
cycle_iso: str
|
|
287
|
+
cols: int
|
|
288
|
+
rows: int
|
|
289
|
+
dx_m: float
|
|
290
|
+
dy_m: float
|
|
291
|
+
wgs84_bounds: tuple[float, float, float, float]
|
|
292
|
+
threshold_m: float
|
|
293
|
+
max_depth_m: list[float]
|
|
294
|
+
max_speed_m_s: list[float]
|
|
295
|
+
max_hazard_m2_s: list[float]
|
|
296
|
+
onset_time_s: list[float | None]
|
|
297
|
+
|
|
298
|
+
@classmethod
|
|
299
|
+
def from_dict(
|
|
300
|
+
cls,
|
|
301
|
+
basin_id: str,
|
|
302
|
+
data: dict[str, Any],
|
|
303
|
+
cycle_iso: str = "",
|
|
304
|
+
) -> BasinGrid:
|
|
305
|
+
"""Parse /api/v1/live/{basin}/grid payload."""
|
|
306
|
+
meta = data.get("metadata") or {}
|
|
307
|
+
env = data.get("envelope") or {}
|
|
308
|
+
bounds = meta.get("wgs84_bounds") or [0.0, 0.0, 0.0, 0.0]
|
|
309
|
+
return cls(
|
|
310
|
+
basin_id=basin_id,
|
|
311
|
+
run_id=str(data.get("run_id", "")),
|
|
312
|
+
cycle_iso=cycle_iso,
|
|
313
|
+
cols=int(meta.get("cols", 0)),
|
|
314
|
+
rows=int(meta.get("rows", 0)),
|
|
315
|
+
dx_m=float(meta.get("dx_m", 0.0)),
|
|
316
|
+
dy_m=float(meta.get("dy_m", 0.0)),
|
|
317
|
+
wgs84_bounds=(float(bounds[0]), float(bounds[1]), float(bounds[2]), float(bounds[3])),
|
|
318
|
+
threshold_m=float(env.get("threshold_m", 0.15)),
|
|
319
|
+
max_depth_m=[float(v) for v in (env.get("max_depth_m") or [])],
|
|
320
|
+
max_speed_m_s=[float(v) for v in (env.get("max_speed_m_s") or [])],
|
|
321
|
+
max_hazard_m2_s=[float(v) for v in (env.get("max_hazard_m2_s") or [])],
|
|
322
|
+
onset_time_s=list(env.get("onset_time_s") or []),
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
def summarize(self) -> BasinGridSummary:
|
|
326
|
+
"""Compute lightweight scalar summary suitable for HA entities."""
|
|
327
|
+
total = max(self.cols * self.rows, 1)
|
|
328
|
+
flooded = [d for d in self.max_depth_m if d >= self.threshold_m]
|
|
329
|
+
peak = max(self.max_depth_m, default=0.0)
|
|
330
|
+
avg = sum(flooded) / len(flooded) if flooded else 0.0
|
|
331
|
+
cell_area_km2 = (self.dx_m * self.dy_m) / 1_000_000.0
|
|
332
|
+
return BasinGridSummary(
|
|
333
|
+
basin_id=self.basin_id,
|
|
334
|
+
run_id=self.run_id,
|
|
335
|
+
cycle_iso=self.cycle_iso,
|
|
336
|
+
cols=self.cols,
|
|
337
|
+
rows=self.rows,
|
|
338
|
+
dx_m=self.dx_m,
|
|
339
|
+
wgs84_bounds=self.wgs84_bounds,
|
|
340
|
+
peak_depth_m=round(peak, 3),
|
|
341
|
+
avg_depth_m=round(avg, 3),
|
|
342
|
+
flooded_cells=len(flooded),
|
|
343
|
+
flooded_pct=round((len(flooded) / total) * 100.0, 2),
|
|
344
|
+
flooded_area_km2=round(len(flooded) * cell_area_km2, 2),
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
def sample_point(self, lat: float, lon: float) -> PointFloodSample | None:
|
|
348
|
+
"""Sample the nearest grid cell for a WGS84 coordinate."""
|
|
349
|
+
min_lon, min_lat, max_lon, max_lat = self.wgs84_bounds
|
|
350
|
+
if self.cols <= 0 or self.rows <= 0:
|
|
351
|
+
return None
|
|
352
|
+
if not (min_lon <= lon <= max_lon and min_lat <= lat <= max_lat):
|
|
353
|
+
return None
|
|
354
|
+
col = min(max(int(((lon - min_lon) / (max_lon - min_lon)) * self.cols), 0), self.cols - 1)
|
|
355
|
+
row = min(max(int(((max_lat - lat) / (max_lat - min_lat)) * self.rows), 0), self.rows - 1)
|
|
356
|
+
idx = row * self.cols + col
|
|
357
|
+
if idx >= len(self.max_depth_m):
|
|
358
|
+
return None
|
|
359
|
+
depth = round(self.max_depth_m[idx], 3)
|
|
360
|
+
speed = round(self.max_speed_m_s[idx], 3) if idx < len(self.max_speed_m_s) else 0.0
|
|
361
|
+
hazard = round(self.max_hazard_m2_s[idx], 3) if idx < len(self.max_hazard_m2_s) else 0.0
|
|
362
|
+
onset = self.onset_time_s[idx] if idx < len(self.onset_time_s) else None
|
|
363
|
+
return PointFloodSample(
|
|
364
|
+
basin_id=self.basin_id,
|
|
365
|
+
depth_m=depth,
|
|
366
|
+
speed_m_s=speed,
|
|
367
|
+
hazard_m2_s=hazard,
|
|
368
|
+
onset_time_s=float(onset) if onset is not None else None,
|
|
369
|
+
risk_level=classify_flood_risk(depth),
|
|
370
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-arus
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client for ARUS flood forecasting, JKM InfoBencana PPS relief centers, and METMalaysia weather warnings
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-arus
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-arus
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-arus/issues
|
|
10
|
+
Keywords: arus,flood,banjir,malaysia,infobencana,jkm,metmalaysia,home-assistant
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Home Automation
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# python-arus
|
|
30
|
+
|
|
31
|
+
Asynchronous Python client for **ARUS** (`farhan-syah/arus` / `arus.mata.ngo`) flood forecasting, **JKM InfoBencana** active PPS relief centers, and **METMalaysia** weather warnings.
|
|
32
|
+
|
|
33
|
+
Designed for Home Assistant integrations with minimal upstream load:
|
|
34
|
+
- **Official feeds first:** Queries `infobencanajkmv2.jkm.gov.my` and `api.data.gov.my` directly for PPS shelters and weather warnings.
|
|
35
|
+
- **`cycle_iso`-gated grid caching:** Avoids re-downloading the ~568 KB 128×128 basin flood grid unless the NWP forecast cycle has changed.
|
|
36
|
+
- **Recorder-safe helpers:** Summarizes basin grids and samples point coordinates (`sample_point(lat, lon)`) so large arrays stay out of Home Assistant entity attributes.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install python-arus
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Quick Start
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import asyncio
|
|
48
|
+
from arus import ArusClient
|
|
49
|
+
|
|
50
|
+
async def main() -> None:
|
|
51
|
+
async with ArusClient() as client:
|
|
52
|
+
# Official JKM PPS relief centers (sorted nearest to Kajang)
|
|
53
|
+
shelters = await client.get_shelters(lat=3.009, lon=101.787)
|
|
54
|
+
print(f"Active flood PPS: {shelters.active_flood_pps_count}")
|
|
55
|
+
|
|
56
|
+
# Official METMalaysia warnings
|
|
57
|
+
warnings = await client.get_weather_warnings()
|
|
58
|
+
print(f"Active warnings: {len(warnings)}")
|
|
59
|
+
|
|
60
|
+
# ARUS basin context & cycle-cached flood grid
|
|
61
|
+
ctx = await client.get_context(lat=3.009, lon=101.787)
|
|
62
|
+
grid = await client.get_basin_grid(ctx.basin_id, cycle_iso=ctx.cycle_iso)
|
|
63
|
+
sample = grid.sample_point(lat=3.009, lon=101.787)
|
|
64
|
+
print(ctx.basin_id, grid.summarize(), sample)
|
|
65
|
+
|
|
66
|
+
asyncio.run(main())
|
|
67
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
arus/__init__.py,sha256=oU-GwdX9tSIIMO02gBzr8Dy08-FfoB_Zi98MxtdPQ7w,904
|
|
2
|
+
arus/client.py,sha256=ErjeRv1IRBzs5Pq0lvhvCQ4elOlU5yFKA9zvvy0d8Uk,5744
|
|
3
|
+
arus/exceptions.py,sha256=xqHWf2L_k_MvBOPvHiiFvxVujBeH9eCch2rUWK2wpls,850
|
|
4
|
+
arus/models.py,sha256=lzzeRSmO90so_QtmAd3Vw8-1BG8PHF5SA4x8-Ugkp6Q,12699
|
|
5
|
+
python_arus-0.1.0.dist-info/licenses/LICENSE,sha256=CV9UcjHZBMuVjUPCSgOJpqCp8L0ekkcK1UAomLpdW9Y,1068
|
|
6
|
+
python_arus-0.1.0.dist-info/METADATA,sha256=qUnj0DbWDKci2JpSAsbgCwdP0dkPdwbMjYIvl9Bypp4,2828
|
|
7
|
+
python_arus-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
python_arus-0.1.0.dist-info/top_level.txt,sha256=EE1oq7JSdPDpPMCrOkQRs9QrmZFGnPMzXtK3sbCYX0s,5
|
|
9
|
+
python_arus-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zubir Jamal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
arus
|