python-arus 0.1.0__tar.gz

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.
@@ -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,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,39 @@
1
+ # python-arus
2
+
3
+ Asynchronous Python client for **ARUS** (`farhan-syah/arus` / `arus.mata.ngo`) flood forecasting, **JKM InfoBencana** active PPS relief centers, and **METMalaysia** weather warnings.
4
+
5
+ Designed for Home Assistant integrations with minimal upstream load:
6
+ - **Official feeds first:** Queries `infobencanajkmv2.jkm.gov.my` and `api.data.gov.my` directly for PPS shelters and weather warnings.
7
+ - **`cycle_iso`-gated grid caching:** Avoids re-downloading the ~568 KB 128×128 basin flood grid unless the NWP forecast cycle has changed.
8
+ - **Recorder-safe helpers:** Summarizes basin grids and samples point coordinates (`sample_point(lat, lon)`) so large arrays stay out of Home Assistant entity attributes.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install python-arus
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ```python
19
+ import asyncio
20
+ from arus import ArusClient
21
+
22
+ async def main() -> None:
23
+ async with ArusClient() as client:
24
+ # Official JKM PPS relief centers (sorted nearest to Kajang)
25
+ shelters = await client.get_shelters(lat=3.009, lon=101.787)
26
+ print(f"Active flood PPS: {shelters.active_flood_pps_count}")
27
+
28
+ # Official METMalaysia warnings
29
+ warnings = await client.get_weather_warnings()
30
+ print(f"Active warnings: {len(warnings)}")
31
+
32
+ # ARUS basin context & cycle-cached flood grid
33
+ ctx = await client.get_context(lat=3.009, lon=101.787)
34
+ grid = await client.get_basin_grid(ctx.basin_id, cycle_iso=ctx.cycle_iso)
35
+ sample = grid.sample_point(lat=3.009, lon=101.787)
36
+ print(ctx.basin_id, grid.summarize(), sample)
37
+
38
+ asyncio.run(main())
39
+ ```
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "python-arus"
7
+ version = "0.1.0"
8
+ description = "Asynchronous Python client for ARUS flood forecasting, JKM InfoBencana PPS relief centers, and METMalaysia weather warnings"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [
13
+ { name = "Zubir Jamal" }
14
+ ]
15
+ keywords = [
16
+ "arus",
17
+ "flood",
18
+ "banjir",
19
+ "malaysia",
20
+ "infobencana",
21
+ "jkm",
22
+ "metmalaysia",
23
+ "home-assistant",
24
+ ]
25
+ classifiers = [
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ "Programming Language :: Python :: 3.14",
31
+ "Operating System :: OS Independent",
32
+ "Topic :: Home Automation",
33
+ "Topic :: Software Development :: Libraries :: Python Modules",
34
+ "Intended Audience :: Developers",
35
+ ]
36
+ dependencies = [
37
+ "aiohttp>=3.9.0",
38
+ ]
39
+
40
+ [project.optional-dependencies]
41
+ test = [
42
+ "pytest>=8.0.0",
43
+ "pytest-asyncio>=0.23.0",
44
+ ]
45
+
46
+ [project.urls]
47
+ Homepage = "https://github.com/zubirjamal/python-arus"
48
+ Repository = "https://github.com/zubirjamal/python-arus"
49
+ Issues = "https://github.com/zubirjamal/python-arus/issues"
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["src"]
53
+
54
+ [tool.pytest.ini_options]
55
+ asyncio_mode = "auto"
56
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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
@@ -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
@@ -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,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/arus/__init__.py
5
+ src/arus/client.py
6
+ src/arus/exceptions.py
7
+ src/arus/models.py
8
+ src/python_arus.egg-info/PKG-INFO
9
+ src/python_arus.egg-info/SOURCES.txt
10
+ src/python_arus.egg-info/dependency_links.txt
11
+ src/python_arus.egg-info/requires.txt
12
+ src/python_arus.egg-info/top_level.txt
13
+ tests/test_arus.py
@@ -0,0 +1,5 @@
1
+ aiohttp>=3.9.0
2
+
3
+ [test]
4
+ pytest>=8.0.0
5
+ pytest-asyncio>=0.23.0
@@ -0,0 +1,203 @@
1
+ """Unit tests for python-arus."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from unittest.mock import AsyncMock
6
+
7
+ import pytest
8
+
9
+ from arus import (
10
+ ArusApiError,
11
+ ArusClient,
12
+ ArusRateLimitError,
13
+ BasinContext,
14
+ BasinGrid,
15
+ ShelterSummary,
16
+ WeatherPoint,
17
+ WeatherWarning,
18
+ classify_flood_risk,
19
+ )
20
+
21
+
22
+ def test_shelter_summary_parsing_and_distance_sort() -> None:
23
+ payload = {
24
+ "points": [
25
+ {
26
+ "id": 1,
27
+ "name": "PPS FAR",
28
+ "latti": 4.02,
29
+ "longi": 101.02,
30
+ "negeri": "Perak",
31
+ "daerah": "Hilir Perak",
32
+ "mukim": "Teluk Intan",
33
+ "bencana": "Banjir",
34
+ "mangsa": 40,
35
+ "keluarga": 11,
36
+ "kapasiti": 16.0,
37
+ },
38
+ {
39
+ "id": 2,
40
+ "name": "PPS FIRE",
41
+ "latti": 3.01,
42
+ "longi": 101.79,
43
+ "negeri": "Selangor",
44
+ "daerah": "Hulu Langat",
45
+ "mukim": "Kajang",
46
+ "bencana": "Kebakaran",
47
+ "mangsa": 7,
48
+ "keluarga": 1,
49
+ "kapasiti": 5.0,
50
+ },
51
+ {
52
+ "id": 3,
53
+ "name": "PPS NEAR",
54
+ "latti": 3.02,
55
+ "longi": 101.78,
56
+ "negeri": "Selangor",
57
+ "daerah": "Hulu Langat",
58
+ "mukim": "Kajang",
59
+ "bencana": "Banjir",
60
+ "mangsa": 100,
61
+ "keluarga": 25,
62
+ "kapasiti": 50.0,
63
+ },
64
+ ]
65
+ }
66
+ summary = ShelterSummary.from_jkm_payload(payload, ref_lat=3.009, ref_lon=101.787)
67
+ assert summary.total_points == 3
68
+ assert summary.active_flood_pps_count == 2
69
+ assert summary.total_flood_victims == 140
70
+ assert summary.affected_states == ["Perak", "Selangor"]
71
+ # Nearest point (id=2) is sorted first even though it's Kebakaran
72
+ assert summary.shelters[0].id == 2
73
+ assert summary.shelters[1].id == 3
74
+ assert summary.shelters[1].distance_km is not None
75
+ assert summary.shelters[1].distance_km < summary.shelters[2].distance_km
76
+
77
+
78
+ def test_weather_warning_parsing() -> None:
79
+ raw = {
80
+ "warning_issue": {
81
+ "issued": "2026-12-02T16:55:00",
82
+ "title_bm": "Amaran Angin Kencang",
83
+ "title_en": "Strong Winds Warning",
84
+ },
85
+ "valid_from": "2026-12-02T00:00:00",
86
+ "valid_to": "2026-12-03T23:59:59",
87
+ "heading_en": "FIRST CATEGORY",
88
+ "text_en": "Thunderstorms expected.",
89
+ }
90
+ warning = WeatherWarning.from_dict(raw)
91
+ assert warning.title_en == "Strong Winds Warning"
92
+ assert warning.heading_en == "FIRST CATEGORY"
93
+
94
+
95
+ def test_basin_grid_summarize_and_sample_point() -> None:
96
+ # 2x2 grid covering lon 101.0..102.0, lat 2.0..3.0
97
+ payload = {
98
+ "run_id": "run-1",
99
+ "metadata": {
100
+ "cols": 2,
101
+ "rows": 2,
102
+ "dx_m": 500.0,
103
+ "dy_m": 500.0,
104
+ "wgs84_bounds": [101.0, 2.0, 102.0, 3.0],
105
+ },
106
+ "envelope": {
107
+ "threshold_m": 0.15,
108
+ "max_depth_m": [0.0, 0.6, 0.1, 1.5],
109
+ "max_speed_m_s": [0.0, 0.4, 0.1, 1.2],
110
+ "max_hazard_m2_s": [0.0, 0.54, 0.06, 2.04],
111
+ "onset_time_s": [None, 3600.0, None, 1800.0],
112
+ },
113
+ }
114
+ grid = BasinGrid.from_dict("sungai-langat", payload, cycle_iso="2026-12-02T11:00:00Z")
115
+ summary = grid.summarize()
116
+ assert summary.peak_depth_m == 1.5
117
+ assert summary.flooded_cells == 2
118
+ assert summary.flooded_pct == 50.0
119
+ assert summary.flooded_area_km2 == 0.5
120
+
121
+ # Top-right cell (row=0, col=1) -> lat=2.8, lon=101.8 -> depth 0.6
122
+ sample = grid.sample_point(2.8, 101.8)
123
+ assert sample is not None
124
+ assert sample.depth_m == 0.6
125
+ assert sample.risk_level == "high"
126
+ assert sample.onset_time_s == 3600.0
127
+
128
+ # Out of bounds
129
+ assert grid.sample_point(5.0, 101.8) is None
130
+
131
+
132
+ def test_classify_flood_risk() -> None:
133
+ assert classify_flood_risk(0.05) == "low"
134
+ assert classify_flood_risk(0.20) == "moderate"
135
+ assert classify_flood_risk(0.60) == "high"
136
+ assert classify_flood_risk(1.30) == "danger"
137
+
138
+
139
+ async def test_cycle_iso_gated_grid_cache() -> None:
140
+ grid_payload = {
141
+ "run_id": "run-1",
142
+ "metadata": {
143
+ "cols": 2,
144
+ "rows": 2,
145
+ "dx_m": 500.0,
146
+ "dy_m": 500.0,
147
+ "wgs84_bounds": [101.0, 2.0, 102.0, 3.0],
148
+ },
149
+ "envelope": {
150
+ "threshold_m": 0.15,
151
+ "max_depth_m": [0.0, 0.2, 0.0, 0.0],
152
+ "max_speed_m_s": [0.0, 0.1, 0.0, 0.0],
153
+ "max_hazard_m2_s": [0.0, 0.12, 0.0, 0.0],
154
+ "onset_time_s": [None, 7200.0, None, None],
155
+ },
156
+ }
157
+ client = ArusClient()
158
+ mock_get = AsyncMock(return_value=grid_payload)
159
+ client._get_json = mock_get # type: ignore[method-assign]
160
+
161
+ g1 = await client.get_basin_grid("sungai-langat", cycle_iso="cycle-1")
162
+ g2 = await client.get_basin_grid("sungai-langat", cycle_iso="cycle-1")
163
+ assert g1 is g2
164
+ assert mock_get.await_count == 1
165
+
166
+ # New cycle triggers a fresh fetch
167
+ await client.get_basin_grid("sungai-langat", cycle_iso="cycle-2")
168
+ assert mock_get.await_count == 2
169
+ await client.close()
170
+
171
+
172
+ async def test_context_and_weather_point_parsing() -> None:
173
+ client = ArusClient()
174
+ client._get_json = AsyncMock( # type: ignore[method-assign]
175
+ side_effect=[
176
+ {
177
+ "context": {
178
+ "basin_id": "sungai-langat",
179
+ "wgs84_bounds": [101.3, 2.6, 101.9, 3.2],
180
+ "cycle_iso": "2026-12-02T11:00:00Z",
181
+ "valid_until_iso": "2026-12-07T10:00:00Z",
182
+ "antecedent_rain_mm": 326.4,
183
+ "hourly_tide_m": [0.5, 0.6],
184
+ }
185
+ },
186
+ {
187
+ "lat": 3.009,
188
+ "lon": 101.787,
189
+ "run_utc": "2026-12-02T00:00:00Z",
190
+ "sources": ["ifs-0p25"],
191
+ "steps": [{"step_h": 0, "rain_3h_mm": 1.2, "wind_speed_kmh": 5.0, "wind_dir_deg": 90.0}],
192
+ },
193
+ ]
194
+ )
195
+ ctx = await client.get_context(3.009, 101.787)
196
+ assert isinstance(ctx, BasinContext)
197
+ assert ctx.basin_id == "sungai-langat"
198
+ assert ctx.antecedent_rain_mm == 326.4
199
+
200
+ wp = await client.get_weather_point(3.009, 101.787)
201
+ assert isinstance(wp, WeatherPoint)
202
+ assert wp.steps[0].rain_3h_mm == 1.2
203
+ await client.close()