python-carimakanhalal 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,27 @@
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 associated documentation files (the "Software"),
13
+ including without limitation the rights to use, copy, modify, merge, publish,
14
+ distribute, sublicense, and/or sell copies of the Software, and to permit
15
+ persons to whom the Software is furnished to do so, subject to the following
16
+ conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-carimakanhalal
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for CariMakanHalal (carimakanhalal.com) JAKIM-certified halal food directory
5
+ Author: Zubir Jamal
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-carimakanhalal
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-carimakanhalal
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-carimakanhalal/issues
10
+ Keywords: carimakanhalal,halal,jakim,malaysia,home-assistant,food
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: License :: OSI Approved :: MIT License
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
+ Requires-Dist: tzdata; sys_platform == "win32"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8.0.0; extra == "test"
27
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # python-carimakanhalal
31
+
32
+ Asynchronous Python client for [CariMakanHalal](https://carimakanhalal.com/) — a directory of JAKIM-certified halal food premises across Malaysia.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install python-carimakanhalal
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ import asyncio
44
+ from carimakanhalal import CariMakanHalalClient
45
+
46
+
47
+ async def main() -> None:
48
+ async with CariMakanHalalClient() as client:
49
+ revision = await client.get_revision()
50
+ print("Dataset revision:", revision)
51
+
52
+ results = await client.search("coffee", lat=2.992, lng=101.79)
53
+ for item in results.results[:5]:
54
+ print(item.listing.name, item.distance_km, "km")
55
+
56
+ new_places = await client.get_new_places()
57
+ print("Recent outlets:", len(new_places.all_outlets))
58
+
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ ## License
64
+
65
+ MIT
@@ -0,0 +1,36 @@
1
+ # python-carimakanhalal
2
+
3
+ Asynchronous Python client for [CariMakanHalal](https://carimakanhalal.com/) — a directory of JAKIM-certified halal food premises across Malaysia.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install python-carimakanhalal
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ import asyncio
15
+ from carimakanhalal import CariMakanHalalClient
16
+
17
+
18
+ async def main() -> None:
19
+ async with CariMakanHalalClient() as client:
20
+ revision = await client.get_revision()
21
+ print("Dataset revision:", revision)
22
+
23
+ results = await client.search("coffee", lat=2.992, lng=101.79)
24
+ for item in results.results[:5]:
25
+ print(item.listing.name, item.distance_km, "km")
26
+
27
+ new_places = await client.get_new_places()
28
+ print("Recent outlets:", len(new_places.all_outlets))
29
+
30
+
31
+ asyncio.run(main())
32
+ ```
33
+
34
+ ## License
35
+
36
+ MIT
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "python-carimakanhalal"
7
+ version = "0.1.0"
8
+ description = "Asynchronous Python client for CariMakanHalal (carimakanhalal.com) JAKIM-certified halal food directory"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Zubir Jamal" }
14
+ ]
15
+ keywords = ["carimakanhalal", "halal", "jakim", "malaysia", "home-assistant", "food"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: OS Independent",
23
+ "Topic :: Home Automation",
24
+ "Topic :: Software Development :: Libraries :: Python Modules",
25
+ "Intended Audience :: Developers",
26
+ ]
27
+ dependencies = [
28
+ "aiohttp>=3.9.0",
29
+ "tzdata; sys_platform == 'win32'",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ test = [
34
+ "pytest>=8.0.0",
35
+ "pytest-asyncio>=0.23.0",
36
+ ]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/zubirjamal/python-carimakanhalal"
40
+ Repository = "https://github.com/zubirjamal/python-carimakanhalal"
41
+ Issues = "https://github.com/zubirjamal/python-carimakanhalal/issues"
42
+
43
+ [project.scripts]
44
+ carimakanhalal = "carimakanhalal.cli:main"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.pytest.ini_options]
50
+ asyncio_mode = "auto"
51
+ asyncio_default_fixture_loop_scope = "function"
52
+ pythonpath = ["src"]
53
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,46 @@
1
+ """Asynchronous Python client for CariMakanHalal (carimakanhalal.com)."""
2
+ from __future__ import annotations
3
+
4
+ from .client import CariMakanHalalClient
5
+ from .constants import NEGERI_NAMES
6
+ from .exceptions import (
7
+ CariMakanHalalConnectionError,
8
+ CariMakanHalalEmptyResponseError,
9
+ CariMakanHalalError,
10
+ CariMakanHalalHttpError,
11
+ CariMakanHalalRateLimitError,
12
+ )
13
+ from .geo import haversine_km, nearby_points
14
+ from .models import (
15
+ Listing,
16
+ MapSnapshot,
17
+ NewPlacesDay,
18
+ NewPlacesGroup,
19
+ NewPlacesResponse,
20
+ SearchResponse,
21
+ SearchResult,
22
+ SnapshotPoint,
23
+ )
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "__version__",
29
+ "CariMakanHalalClient",
30
+ "CariMakanHalalConnectionError",
31
+ "CariMakanHalalEmptyResponseError",
32
+ "CariMakanHalalError",
33
+ "CariMakanHalalHttpError",
34
+ "CariMakanHalalRateLimitError",
35
+ "Listing",
36
+ "MapSnapshot",
37
+ "NEGERI_NAMES",
38
+ "NewPlacesDay",
39
+ "NewPlacesGroup",
40
+ "NewPlacesResponse",
41
+ "SearchResponse",
42
+ "SearchResult",
43
+ "SnapshotPoint",
44
+ "haversine_km",
45
+ "nearby_points",
46
+ ]
@@ -0,0 +1,7 @@
1
+ """Module entrypoint for python -m carimakanhalal."""
2
+ from __future__ import annotations
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ main()
@@ -0,0 +1,62 @@
1
+ """CLI entrypoint for python-carimakanhalal."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ from dataclasses import asdict
8
+
9
+ from .client import CariMakanHalalClient
10
+
11
+
12
+ async def _run(args: argparse.Namespace) -> None:
13
+ async with CariMakanHalalClient() as client:
14
+ if args.command == "revision":
15
+ print(await client.get_revision())
16
+ elif args.command == "coverage":
17
+ print(json.dumps(await client.get_coverage(), indent=2))
18
+ elif args.command == "search":
19
+ resp = await client.search(args.query, lat=args.lat, lng=args.lng)
20
+ payload = {
21
+ "total_matches": resp.total_matches,
22
+ "results": [
23
+ {"distance_meters": r.distance_meters, "listing": asdict(r.listing)}
24
+ for r in resp.results[: args.limit]
25
+ ],
26
+ }
27
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
28
+ elif args.command == "new-places":
29
+ resp = await client.get_new_places()
30
+ outlets = resp.all_outlets[: args.limit]
31
+ print(
32
+ json.dumps(
33
+ {
34
+ "last_refresh": resp.last_refresh,
35
+ "count": len(resp.all_outlets),
36
+ "outlets": [asdict(o) for o in outlets],
37
+ },
38
+ indent=2,
39
+ ensure_ascii=False,
40
+ )
41
+ )
42
+
43
+
44
+ def main() -> None:
45
+ """Run the CariMakanHalal CLI."""
46
+ parser = argparse.ArgumentParser(description="CariMakanHalal CLI")
47
+ sub = parser.add_subparsers(dest="command", required=True)
48
+
49
+ sub.add_parser("revision", help="Show current dataset revision")
50
+ sub.add_parser("coverage", help="List covered Malaysian state codes")
51
+
52
+ p_search = sub.add_parser("search", help="Search certified halal premises")
53
+ p_search.add_argument("query", help="Search keyword")
54
+ p_search.add_argument("--lat", type=float, default=None, help="Latitude")
55
+ p_search.add_argument("--lng", type=float, default=None, help="Longitude")
56
+ p_search.add_argument("--limit", type=int, default=10, help="Max results to print")
57
+
58
+ p_new = sub.add_parser("new-places", help="Show newly added certified premises")
59
+ p_new.add_argument("--limit", type=int, default=10, help="Max outlets to print")
60
+
61
+ args = parser.parse_args()
62
+ asyncio.run(_run(args))
@@ -0,0 +1,160 @@
1
+ """Asynchronous client for CariMakanHalal API."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ from typing import Any
7
+
8
+ import aiohttp
9
+
10
+ from .constants import (
11
+ API_COVERAGE,
12
+ API_MAP_LOCATION,
13
+ API_MAP_REVISION,
14
+ API_MAP_SNAPSHOT,
15
+ API_NEW_PLACES,
16
+ API_SEARCH,
17
+ DEFAULT_TIMEOUT_SECONDS,
18
+ DEFAULT_USER_AGENT,
19
+ )
20
+ from .exceptions import (
21
+ CariMakanHalalConnectionError,
22
+ CariMakanHalalEmptyResponseError,
23
+ CariMakanHalalError,
24
+ CariMakanHalalHttpError,
25
+ CariMakanHalalRateLimitError,
26
+ )
27
+ from .geo import nearby_points
28
+ from .models import (
29
+ Listing,
30
+ MapSnapshot,
31
+ NewPlacesResponse,
32
+ SearchResponse,
33
+ SnapshotPoint,
34
+ )
35
+
36
+ _LOGGER = logging.getLogger(__name__)
37
+
38
+
39
+ class CariMakanHalalClient:
40
+ """Async client for CariMakanHalal (carimakanhalal.com)."""
41
+
42
+ def __init__(
43
+ self,
44
+ session: aiohttp.ClientSession | None = None,
45
+ user_agent: str | None = None,
46
+ timeout: int = DEFAULT_TIMEOUT_SECONDS,
47
+ ) -> None:
48
+ """Initialize the client."""
49
+ self._session = session
50
+ self._close_session = False
51
+ self._user_agent = user_agent or DEFAULT_USER_AGENT
52
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
53
+
54
+ async def _get_session(self) -> aiohttp.ClientSession:
55
+ if self._session is None:
56
+ self._session = aiohttp.ClientSession(timeout=self._timeout)
57
+ self._close_session = True
58
+ elif isinstance(self._session, aiohttp.ClientSession) and self._session.closed:
59
+ self._session = aiohttp.ClientSession(timeout=self._timeout)
60
+ self._close_session = True
61
+ return self._session
62
+
63
+ async def close(self) -> None:
64
+ """Close the underlying session if created by this client."""
65
+ if self._close_session and self._session and not getattr(self._session, "closed", True):
66
+ await self._session.close()
67
+
68
+ async def __aenter__(self) -> CariMakanHalalClient:
69
+ return self
70
+
71
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
72
+ await self.close()
73
+
74
+ async def _get_json(
75
+ self, url: str, params: dict[str, str] | None = None
76
+ ) -> dict[str, Any]:
77
+ """Perform a GET request and return parsed JSON object."""
78
+ session = await self._get_session()
79
+ headers = {"User-Agent": self._user_agent, "Accept": "application/json"}
80
+ try:
81
+ async with session.get(
82
+ url, params=params, headers=headers, timeout=self._timeout
83
+ ) as resp:
84
+ if resp.status == 429:
85
+ retry = int(resp.headers.get("Retry-After", "5") or 5)
86
+ raise CariMakanHalalRateLimitError(retry_after=retry)
87
+ if resp.status != 200:
88
+ text = await resp.text()
89
+ raise CariMakanHalalHttpError(resp.status, text[:200])
90
+
91
+ body = await resp.json(content_type=None)
92
+ except (aiohttp.ClientError, asyncio.TimeoutError) as err:
93
+ raise CariMakanHalalConnectionError(f"Connection failed: {err}") from err
94
+ except (CariMakanHalalError, CariMakanHalalHttpError):
95
+ raise
96
+ except Exception as err:
97
+ raise CariMakanHalalError(f"Unexpected error: {err}") from err
98
+
99
+ if not isinstance(body, dict):
100
+ raise CariMakanHalalEmptyResponseError("Invalid JSON structure received from API")
101
+ return body
102
+
103
+ async def get_revision(self) -> str:
104
+ """Fetch current dataset revision token."""
105
+ body = await self._get_json(API_MAP_REVISION)
106
+ rev = body.get("revision")
107
+ if not rev:
108
+ raise CariMakanHalalEmptyResponseError("Missing revision in API response")
109
+ return str(rev)
110
+
111
+ async def get_coverage(self) -> list[str]:
112
+ """Fetch covered ISO 3166-2:MY state/territory codes."""
113
+ body = await self._get_json(API_COVERAGE)
114
+ covered = body.get("covered")
115
+ if not isinstance(covered, list):
116
+ raise CariMakanHalalEmptyResponseError("Missing covered list in API response")
117
+ return [str(code) for code in covered]
118
+
119
+ async def get_snapshot(self, query: str = "") -> MapSnapshot:
120
+ """Fetch the full map snapshot (optionally filtered by query)."""
121
+ params = {"q": query} if query else None
122
+ body = await self._get_json(API_MAP_SNAPSHOT, params=params)
123
+ return MapSnapshot.from_api(body)
124
+
125
+ async def get_location_listings(self, lat: float, lng: float) -> list[Listing]:
126
+ """Fetch all listings at a specific snapshot coordinate."""
127
+ params = {"lat": str(lat), "lng": str(lng)}
128
+ body = await self._get_json(API_MAP_LOCATION, params=params)
129
+ raw = body.get("listings") or []
130
+ return [item for item in (Listing.from_api(row) for row in raw) if item is not None]
131
+
132
+ async def search(
133
+ self,
134
+ query: str,
135
+ lat: float | None = None,
136
+ lng: float | None = None,
137
+ ) -> SearchResponse:
138
+ """Search JAKIM-certified premises by keyword and optional coordinates."""
139
+ params: dict[str, str] = {"q": query}
140
+ if lat is not None and lng is not None:
141
+ params["lat"] = str(lat)
142
+ params["lng"] = str(lng)
143
+ body = await self._get_json(API_SEARCH, params=params)
144
+ return SearchResponse.from_api(body)
145
+
146
+ async def get_new_places(self) -> NewPlacesResponse:
147
+ """Fetch recently added/updated halal-certified outlets."""
148
+ body = await self._get_json(API_NEW_PLACES)
149
+ return NewPlacesResponse.from_api(body)
150
+
151
+ async def find_nearby_snapshot_points(
152
+ self,
153
+ lat: float,
154
+ lng: float,
155
+ radius_km: float = 5.0,
156
+ query: str = "",
157
+ ) -> list[tuple[SnapshotPoint, float]]:
158
+ """Fetch snapshot and return coordinate points within radius_km sorted closest-first."""
159
+ snapshot = await self.get_snapshot(query=query)
160
+ return nearby_points(snapshot.locations, lat=lat, lng=lng, radius_km=radius_km)
@@ -0,0 +1,37 @@
1
+ """Constants for CariMakanHalal client."""
2
+ from __future__ import annotations
3
+
4
+ from zoneinfo import ZoneInfo
5
+
6
+ BASE_URL = "https://carimakanhalal.com"
7
+
8
+ API_COVERAGE = f"{BASE_URL}/api/coverage"
9
+ API_MAP_REVISION = f"{BASE_URL}/api/map/revision"
10
+ API_MAP_SNAPSHOT = f"{BASE_URL}/api/map/snapshot"
11
+ API_MAP_LOCATION = f"{BASE_URL}/api/map/location"
12
+ API_SEARCH = f"{BASE_URL}/api/search"
13
+ API_NEW_PLACES = f"{BASE_URL}/api/new-places"
14
+
15
+ DEFAULT_TIMEOUT_SECONDS = 15
16
+ DEFAULT_USER_AGENT = "python-carimakanhalal/0.1.0 (+https://github.com/zubirjamal/python-carimakanhalal)"
17
+
18
+ MYT = ZoneInfo("Asia/Kuala_Lumpur")
19
+
20
+ NEGERI_NAMES: dict[int, str] = {
21
+ 1: "Johor",
22
+ 2: "Kedah",
23
+ 3: "Kelantan",
24
+ 4: "Melaka",
25
+ 5: "Negeri Sembilan",
26
+ 6: "Pahang",
27
+ 7: "Pulau Pinang",
28
+ 8: "Perak",
29
+ 9: "Perlis",
30
+ 10: "Selangor",
31
+ 11: "Terengganu",
32
+ 12: "Sabah",
33
+ 13: "Sarawak",
34
+ 14: "Kuala Lumpur",
35
+ 15: "Labuan",
36
+ 16: "Putrajaya",
37
+ }
@@ -0,0 +1,31 @@
1
+ """Exceptions for CariMakanHalal client."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class CariMakanHalalError(Exception):
6
+ """Base exception for CariMakanHalal client."""
7
+
8
+
9
+ class CariMakanHalalConnectionError(CariMakanHalalError):
10
+ """Network or timeout error talking to CariMakanHalal."""
11
+
12
+
13
+ class CariMakanHalalHttpError(CariMakanHalalError):
14
+ """Non-200 HTTP response from CariMakanHalal."""
15
+
16
+ def __init__(self, status: int, body: str = "") -> None:
17
+ self.status = status
18
+ self.body = body
19
+ super().__init__(f"HTTP {status}: {body}" if body else f"HTTP {status}")
20
+
21
+
22
+ class CariMakanHalalRateLimitError(CariMakanHalalHttpError):
23
+ """HTTP 429 Too Many Requests."""
24
+
25
+ def __init__(self, retry_after: int = 5, body: str = "") -> None:
26
+ self.retry_after = retry_after
27
+ super().__init__(429, body or f"Rate limited; retry after {retry_after}s")
28
+
29
+
30
+ class CariMakanHalalEmptyResponseError(CariMakanHalalError):
31
+ """Invalid or empty JSON payload returned by CariMakanHalal."""
@@ -0,0 +1,40 @@
1
+ """Geospatial helpers for CariMakanHalal."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from .models import SnapshotPoint
9
+
10
+ _EARTH_RADIUS_KM = 6371.0088
11
+
12
+
13
+ def haversine_km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
14
+ """Compute great-circle distance in kilometers between two WGS84 coordinates."""
15
+ phi1 = math.radians(lat1)
16
+ phi2 = math.radians(lat2)
17
+ dphi = math.radians(lat2 - lat1)
18
+ dlambda = math.radians(lng2 - lng1)
19
+
20
+ a = (
21
+ math.sin(dphi / 2) ** 2
22
+ + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
23
+ )
24
+ return 2 * _EARTH_RADIUS_KM * math.atan2(math.sqrt(a), math.sqrt(1 - a))
25
+
26
+
27
+ def nearby_points(
28
+ points: list[SnapshotPoint],
29
+ lat: float,
30
+ lng: float,
31
+ radius_km: float = 5.0,
32
+ ) -> list[tuple[SnapshotPoint, float]]:
33
+ """Return snapshot points within radius_km of (lat, lng), sorted closest-first."""
34
+ matches: list[tuple[SnapshotPoint, float]] = []
35
+ for pt in points:
36
+ dist = haversine_km(lat, lng, pt.lat, pt.lng)
37
+ if dist <= radius_km:
38
+ matches.append((pt, dist))
39
+ matches.sort(key=lambda item: item[1])
40
+ return matches
@@ -0,0 +1,263 @@
1
+ """Data models for CariMakanHalal API."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from datetime import date, datetime
6
+ from typing import Any
7
+
8
+ from .constants import MYT
9
+
10
+
11
+ def _parse_expiry_date(raw: str | None) -> date | None:
12
+ if not raw or not isinstance(raw, str):
13
+ return None
14
+ for fmt in ("%d/%m/%Y", "%Y-%m-%d"):
15
+ try:
16
+ return datetime.strptime(raw.strip(), fmt).date()
17
+ except ValueError:
18
+ continue
19
+ return None
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Listing:
24
+ """A JAKIM-certified halal food premise."""
25
+
26
+ comp_code: str
27
+ name: str
28
+ brand: str | None
29
+ address: str
30
+ state: str
31
+ negeri: int | None
32
+ expiry: str | None
33
+ lat: float | None
34
+ lng: float | None
35
+ geocode_status: str | None = None
36
+ last_seen_at: str | None = None
37
+ menu_tags: tuple[str, ...] = ()
38
+ pin_kind: str | None = None
39
+ menu_items: int | None = None
40
+
41
+ @classmethod
42
+ def from_api(cls, data: dict[str, Any]) -> Listing | None:
43
+ """Parse a listing dict from the CariMakanHalal API."""
44
+ if not isinstance(data, dict):
45
+ return None
46
+ comp_code = str(data.get("comp_code") or "").strip()
47
+ name = str(data.get("name") or "").strip()
48
+ if not comp_code and not name:
49
+ return None
50
+
51
+ raw_tags = data.get("menu_tags") or []
52
+ tags = tuple(str(t) for t in raw_tags if t is not None)
53
+
54
+ lat_val = data.get("lat")
55
+ lng_val = data.get("lng")
56
+ negeri_val = data.get("negeri")
57
+ menu_items_val = data.get("menu_items")
58
+
59
+ return cls(
60
+ comp_code=comp_code,
61
+ name=name,
62
+ brand=data.get("brand"),
63
+ address=str(data.get("address") or "").strip(),
64
+ state=str(data.get("state") or "").strip(),
65
+ negeri=int(negeri_val) if negeri_val is not None else None,
66
+ expiry=data.get("expiry"),
67
+ lat=float(lat_val) if lat_val is not None else None,
68
+ lng=float(lng_val) if lng_val is not None else None,
69
+ geocode_status=data.get("geocode_status"),
70
+ last_seen_at=data.get("last_seen_at"),
71
+ menu_tags=tags,
72
+ pin_kind=data.get("pin_kind"),
73
+ menu_items=int(menu_items_val) if menu_items_val is not None else None,
74
+ )
75
+
76
+ @property
77
+ def expiry_date(self) -> date | None:
78
+ """Parsed halal certificate expiry date."""
79
+ return _parse_expiry_date(self.expiry)
80
+
81
+ @property
82
+ def is_expired(self) -> bool | None:
83
+ """Return whether the certificate is expired in Malaysia time, or None if unknown."""
84
+ exp = self.expiry_date
85
+ if exp is None:
86
+ return None
87
+ return exp < datetime.now(MYT).date()
88
+
89
+ @property
90
+ def days_until_expiry(self) -> int | None:
91
+ """Days until certificate expiry (negative if expired), or None if unknown."""
92
+ exp = self.expiry_date
93
+ if exp is None:
94
+ return None
95
+ return (exp - datetime.now(MYT).date()).days
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class SearchResult:
100
+ """Single search match with optional distance in meters."""
101
+
102
+ listing: Listing
103
+ distance_meters: float | None = None
104
+
105
+ @property
106
+ def distance_km(self) -> float | None:
107
+ """Distance in kilometers if available."""
108
+ if self.distance_meters is None:
109
+ return None
110
+ return round(self.distance_meters / 1000.0, 3)
111
+
112
+
113
+ @dataclass(frozen=True, slots=True)
114
+ class SearchResponse:
115
+ """Response from /api/search."""
116
+
117
+ results: list[SearchResult] = field(default_factory=list)
118
+ total_matches: int = 0
119
+ menu: Any = None
120
+
121
+ @classmethod
122
+ def from_api(cls, data: dict[str, Any]) -> SearchResponse:
123
+ """Parse /api/search JSON response."""
124
+ results: list[SearchResult] = []
125
+ for item in data.get("results") or []:
126
+ if not isinstance(item, dict):
127
+ continue
128
+ listing = Listing.from_api(item.get("listing") or {})
129
+ if listing is None:
130
+ continue
131
+ dist = item.get("distanceMeters")
132
+ results.append(
133
+ SearchResult(
134
+ listing=listing,
135
+ distance_meters=float(dist) if dist is not None else None,
136
+ )
137
+ )
138
+ return cls(
139
+ results=results,
140
+ total_matches=int(data.get("totalMatches") or len(results)),
141
+ menu=data.get("menu"),
142
+ )
143
+
144
+
145
+ @dataclass(frozen=True, slots=True)
146
+ class SnapshotPoint:
147
+ """A coordinate cluster point in /api/map/snapshot."""
148
+
149
+ lat: float
150
+ lng: float
151
+ count: int
152
+ tags: tuple[str, ...] = ()
153
+
154
+ @classmethod
155
+ def from_api(cls, row: list[Any]) -> SnapshotPoint | None:
156
+ """Parse a compact [lat, lng, count, ...tags] array."""
157
+ if not isinstance(row, (list, tuple)) or len(row) < 3:
158
+ return None
159
+ return cls(
160
+ lat=float(row[0]),
161
+ lng=float(row[1]),
162
+ count=int(row[2]),
163
+ tags=tuple(str(t) for t in row[3:] if t is not None),
164
+ )
165
+
166
+
167
+ @dataclass(frozen=True, slots=True)
168
+ class MapSnapshot:
169
+ """Full map snapshot from /api/map/snapshot."""
170
+
171
+ revision: str
172
+ query: str
173
+ total_listings: int
174
+ peninsular_count: int
175
+ east_count: int
176
+ bounds: dict[str, Any] = field(default_factory=dict)
177
+ locations: list[SnapshotPoint] = field(default_factory=list)
178
+
179
+ @classmethod
180
+ def from_api(cls, data: dict[str, Any]) -> MapSnapshot:
181
+ """Parse /api/map/snapshot JSON response."""
182
+ sides = data.get("sides") or {}
183
+ peninsular = sides.get("peninsular") or {}
184
+ east = sides.get("east") or {}
185
+ points = [
186
+ p
187
+ for p in (SnapshotPoint.from_api(row) for row in (data.get("locations") or []))
188
+ if p is not None
189
+ ]
190
+ return cls(
191
+ revision=str(data.get("revision") or ""),
192
+ query=str(data.get("query") or ""),
193
+ total_listings=int(data.get("totalListings") or 0),
194
+ peninsular_count=int(peninsular.get("count") or 0),
195
+ east_count=int(east.get("count") or 0),
196
+ bounds=dict(data.get("bounds") or {}),
197
+ locations=points,
198
+ )
199
+
200
+
201
+ @dataclass(frozen=True, slots=True)
202
+ class NewPlacesGroup:
203
+ """Brand/company group in /api/new-places."""
204
+
205
+ comp_code: str
206
+ label: str
207
+ outlets: list[Listing] = field(default_factory=list)
208
+ certificate_outlets: int | None = None
209
+
210
+ @classmethod
211
+ def from_api(cls, data: dict[str, Any]) -> NewPlacesGroup:
212
+ outlets = [
213
+ o
214
+ for o in (Listing.from_api(row) for row in (data.get("outlets") or []))
215
+ if o is not None
216
+ ]
217
+ cert_outlets = data.get("certificateOutlets")
218
+ return cls(
219
+ comp_code=str(data.get("compCode") or ""),
220
+ label=str(data.get("label") or ""),
221
+ outlets=outlets,
222
+ certificate_outlets=int(cert_outlets) if cert_outlets is not None else None,
223
+ )
224
+
225
+
226
+ @dataclass(frozen=True, slots=True)
227
+ class NewPlacesDay:
228
+ """Daily batch of newly certified outlets."""
229
+
230
+ day: str
231
+ groups: list[NewPlacesGroup] = field(default_factory=list)
232
+
233
+ @property
234
+ def outlets(self) -> list[Listing]:
235
+ """All outlets added on this day across all groups."""
236
+ return [o for g in self.groups for o in g.outlets]
237
+
238
+
239
+ @dataclass(frozen=True, slots=True)
240
+ class NewPlacesResponse:
241
+ """Response from /api/new-places."""
242
+
243
+ days: list[NewPlacesDay] = field(default_factory=list)
244
+ last_refresh: str | None = None
245
+
246
+ @classmethod
247
+ def from_api(cls, data: dict[str, Any]) -> NewPlacesResponse:
248
+ days: list[NewPlacesDay] = []
249
+ for day_row in data.get("days") or []:
250
+ if not isinstance(day_row, dict):
251
+ continue
252
+ groups = [
253
+ NewPlacesGroup.from_api(g)
254
+ for g in (day_row.get("groups") or [])
255
+ if isinstance(g, dict)
256
+ ]
257
+ days.append(NewPlacesDay(day=str(day_row.get("day") or ""), groups=groups))
258
+ return cls(days=days, last_refresh=data.get("lastRefresh"))
259
+
260
+ @property
261
+ def all_outlets(self) -> list[Listing]:
262
+ """Flattened list of all newly added outlets."""
263
+ return [o for d in self.days for o in d.outlets]
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-carimakanhalal
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for CariMakanHalal (carimakanhalal.com) JAKIM-certified halal food directory
5
+ Author: Zubir Jamal
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-carimakanhalal
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-carimakanhalal
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-carimakanhalal/issues
10
+ Keywords: carimakanhalal,halal,jakim,malaysia,home-assistant,food
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: License :: OSI Approved :: MIT License
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
+ Requires-Dist: tzdata; sys_platform == "win32"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8.0.0; extra == "test"
27
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # python-carimakanhalal
31
+
32
+ Asynchronous Python client for [CariMakanHalal](https://carimakanhalal.com/) — a directory of JAKIM-certified halal food premises across Malaysia.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install python-carimakanhalal
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ import asyncio
44
+ from carimakanhalal import CariMakanHalalClient
45
+
46
+
47
+ async def main() -> None:
48
+ async with CariMakanHalalClient() as client:
49
+ revision = await client.get_revision()
50
+ print("Dataset revision:", revision)
51
+
52
+ results = await client.search("coffee", lat=2.992, lng=101.79)
53
+ for item in results.results[:5]:
54
+ print(item.listing.name, item.distance_km, "km")
55
+
56
+ new_places = await client.get_new_places()
57
+ print("Recent outlets:", len(new_places.all_outlets))
58
+
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ ## License
64
+
65
+ MIT
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/carimakanhalal/__init__.py
5
+ src/carimakanhalal/__main__.py
6
+ src/carimakanhalal/cli.py
7
+ src/carimakanhalal/client.py
8
+ src/carimakanhalal/constants.py
9
+ src/carimakanhalal/exceptions.py
10
+ src/carimakanhalal/geo.py
11
+ src/carimakanhalal/models.py
12
+ src/python_carimakanhalal.egg-info/PKG-INFO
13
+ src/python_carimakanhalal.egg-info/SOURCES.txt
14
+ src/python_carimakanhalal.egg-info/dependency_links.txt
15
+ src/python_carimakanhalal.egg-info/entry_points.txt
16
+ src/python_carimakanhalal.egg-info/requires.txt
17
+ src/python_carimakanhalal.egg-info/top_level.txt
18
+ tests/test_client.py
19
+ tests/test_geo.py
20
+ tests/test_models.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ carimakanhalal = carimakanhalal.cli:main
@@ -0,0 +1,8 @@
1
+ aiohttp>=3.9.0
2
+
3
+ [:sys_platform == "win32"]
4
+ tzdata
5
+
6
+ [test]
7
+ pytest>=8.0.0
8
+ pytest-asyncio>=0.23.0
@@ -0,0 +1,97 @@
1
+ """Tests for CariMakanHalalClient."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+ from unittest.mock import AsyncMock, MagicMock
6
+
7
+ import pytest
8
+
9
+ from carimakanhalal import (
10
+ CariMakanHalalClient,
11
+ CariMakanHalalEmptyResponseError,
12
+ CariMakanHalalHttpError,
13
+ CariMakanHalalRateLimitError,
14
+ )
15
+
16
+
17
+ class _MockResponse:
18
+ def __init__(self, status: int, payload: Any, headers: dict[str, str] | None = None) -> None:
19
+ self.status = status
20
+ self._payload = payload
21
+ self.headers = headers or {}
22
+
23
+ async def json(self, content_type: str | None = None) -> Any:
24
+ return self._payload
25
+
26
+ async def text(self) -> str:
27
+ return str(self._payload)
28
+
29
+ async def __aenter__(self) -> _MockResponse:
30
+ return self
31
+
32
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
33
+ return None
34
+
35
+
36
+ def _make_session(response: _MockResponse) -> MagicMock:
37
+ session = MagicMock()
38
+ session.closed = False
39
+ session.get = MagicMock(return_value=response)
40
+ session.close = AsyncMock()
41
+ return session
42
+
43
+
44
+ async def test_get_revision_and_coverage() -> None:
45
+ session = _make_session(_MockResponse(200, {"revision": "14339-test"}))
46
+ client = CariMakanHalalClient(session=session)
47
+ assert await client.get_revision() == "14339-test"
48
+
49
+ session.get.return_value = _MockResponse(200, {"covered": ["MY-10", "MY-14"]})
50
+ assert await client.get_coverage() == ["MY-10", "MY-14"]
51
+
52
+
53
+ async def test_search_and_location_listings() -> None:
54
+ payload = {
55
+ "totalMatches": 1,
56
+ "results": [
57
+ {
58
+ "listing": {
59
+ "comp_code": "COMP-1",
60
+ "name": "ZUS COFFEE",
61
+ "address": "Kajang",
62
+ "state": "Selangor",
63
+ },
64
+ "distanceMeters": 500,
65
+ }
66
+ ],
67
+ }
68
+ session = _make_session(_MockResponse(200, payload))
69
+ client = CariMakanHalalClient(session=session)
70
+ resp = await client.search("coffee", lat=2.992, lng=101.79)
71
+ assert resp.total_matches == 1
72
+ assert resp.results[0].listing.name == "ZUS COFFEE"
73
+
74
+ session.get.return_value = _MockResponse(
75
+ 200,
76
+ {"datasetVersion": "14339", "listings": [{"comp_code": "COMP-1", "name": "ZUS COFFEE"}]},
77
+ )
78
+ listings = await client.get_location_listings(2.992, 101.79)
79
+ assert len(listings) == 1
80
+ assert listings[0].comp_code == "COMP-1"
81
+
82
+
83
+ async def test_rate_limit_and_http_errors() -> None:
84
+ session = _make_session(_MockResponse(429, "Too Many Requests", headers={"Retry-After": "10"}))
85
+ client = CariMakanHalalClient(session=session)
86
+ with pytest.raises(CariMakanHalalRateLimitError) as exc_info:
87
+ await client.get_revision()
88
+ assert exc_info.value.retry_after == 10
89
+
90
+ session.get.return_value = _MockResponse(500, "Server Error")
91
+ with pytest.raises(CariMakanHalalHttpError) as http_err:
92
+ await client.get_coverage()
93
+ assert http_err.value.status == 500
94
+
95
+ session.get.return_value = _MockResponse(200, [])
96
+ with pytest.raises(CariMakanHalalEmptyResponseError):
97
+ await client.get_new_places()
@@ -0,0 +1,24 @@
1
+ """Tests for geospatial helpers."""
2
+ from __future__ import annotations
3
+
4
+ from carimakanhalal.geo import haversine_km, nearby_points
5
+ from carimakanhalal.models import SnapshotPoint
6
+
7
+
8
+ def test_haversine_km_zero_and_known_distance() -> None:
9
+ assert haversine_km(2.992, 101.79, 2.992, 101.79) == 0.0
10
+ # Kajang to KLCC is ~20 km
11
+ dist = haversine_km(2.992, 101.79, 3.1579, 101.7116)
12
+ assert 18.0 < dist < 23.0
13
+
14
+
15
+ def test_nearby_points_filters_and_sorts() -> None:
16
+ points = [
17
+ SnapshotPoint(lat=3.1579, lng=101.7116, count=1), # ~20 km away
18
+ SnapshotPoint(lat=2.9950, lng=101.7920, count=2), # ~0.4 km away
19
+ SnapshotPoint(lat=3.0100, lng=101.7800, count=1), # ~2.3 km away
20
+ ]
21
+ matches = nearby_points(points, lat=2.992, lng=101.79, radius_km=5.0)
22
+ assert len(matches) == 2
23
+ assert matches[0][0].count == 2
24
+ assert matches[0][1] < matches[1][1]
@@ -0,0 +1,114 @@
1
+ """Tests for CariMakanHalal data models."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import date
5
+
6
+ from carimakanhalal.models import (
7
+ Listing,
8
+ MapSnapshot,
9
+ NewPlacesResponse,
10
+ SearchResponse,
11
+ SnapshotPoint,
12
+ )
13
+
14
+
15
+ def test_listing_from_api_and_expiry() -> None:
16
+ raw = {
17
+ "comp_code": "COMP-20210622-202530",
18
+ "name": "ZUS COFFEE TAMAN SUTERA",
19
+ "brand": "ZUS COFFEE",
20
+ "address": "NO. A2-19, TAMAN SUTERA KAJANG, 43000, Selangor",
21
+ "state": "Selangor",
22
+ "negeri": 10,
23
+ "expiry": "15/11/2099",
24
+ "lat": 3.0098918,
25
+ "lng": 101.7674326,
26
+ "geocode_status": "published",
27
+ "last_seen_at": "2026-11-28 06:02:15",
28
+ "menu_tags": ["kopi"],
29
+ "pin_kind": "place",
30
+ "menu_items": 1358,
31
+ }
32
+ listing = Listing.from_api(raw)
33
+ assert listing is not None
34
+ assert listing.comp_code == "COMP-20210622-202530"
35
+ assert listing.brand == "ZUS COFFEE"
36
+ assert listing.negeri == 10
37
+ assert listing.menu_tags == ("kopi",)
38
+ assert listing.expiry_date == date(2099, 11, 15)
39
+ assert listing.is_expired is False
40
+ assert listing.days_until_expiry is not None and listing.days_until_expiry > 0
41
+
42
+
43
+ def test_listing_invalid_or_empty() -> None:
44
+ assert Listing.from_api({}) is None
45
+ assert Listing.from_api({"comp_code": "", "name": ""}) is None
46
+
47
+
48
+ def test_search_response_from_api() -> None:
49
+ raw = {
50
+ "totalMatches": 1,
51
+ "results": [
52
+ {
53
+ "listing": {
54
+ "comp_code": "COMP-1",
55
+ "name": "KOPI SATU",
56
+ "address": "Kajang",
57
+ "state": "Selangor",
58
+ },
59
+ "distanceMeters": 1250.5,
60
+ }
61
+ ],
62
+ }
63
+ resp = SearchResponse.from_api(raw)
64
+ assert resp.total_matches == 1
65
+ assert len(resp.results) == 1
66
+ assert resp.results[0].distance_km == 1.25
67
+
68
+
69
+ def test_snapshot_from_api() -> None:
70
+ raw = {
71
+ "revision": "14339-abc",
72
+ "query": "",
73
+ "totalListings": 3,
74
+ "bounds": {"north": 6.8, "south": 1.0, "east": 119.0, "west": 99.6},
75
+ "sides": {
76
+ "peninsular": {"count": 2},
77
+ "east": {"count": 1},
78
+ },
79
+ "locations": [
80
+ [2.99, 101.79, 1, "kopi"],
81
+ [3.01, 101.76, 2],
82
+ ],
83
+ }
84
+ snap = MapSnapshot.from_api(raw)
85
+ assert snap.revision == "14339-abc"
86
+ assert snap.peninsular_count == 2
87
+ assert snap.east_count == 1
88
+ assert len(snap.locations) == 2
89
+ assert snap.locations[0] == SnapshotPoint(lat=2.99, lng=101.79, count=1, tags=("kopi",))
90
+
91
+
92
+ def test_new_places_from_api() -> None:
93
+ raw = {
94
+ "lastRefresh": "2026-11-28T06:00:00Z",
95
+ "days": [
96
+ {
97
+ "day": "2026-11-28",
98
+ "groups": [
99
+ {
100
+ "compCode": "COMP-1",
101
+ "label": "SUBWAY",
102
+ "certificateOutlets": 2,
103
+ "outlets": [
104
+ {"comp_code": "COMP-1", "name": "SUBWAY A", "address": "KL", "state": "Kuala Lumpur"}
105
+ ],
106
+ }
107
+ ],
108
+ }
109
+ ],
110
+ }
111
+ resp = NewPlacesResponse.from_api(raw)
112
+ assert resp.last_refresh == "2026-11-28T06:00:00Z"
113
+ assert len(resp.all_outlets) == 1
114
+ assert resp.all_outlets[0].name == "SUBWAY A"