python-carimakanhalal 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.
- carimakanhalal/__init__.py +46 -0
- carimakanhalal/__main__.py +7 -0
- carimakanhalal/cli.py +62 -0
- carimakanhalal/client.py +160 -0
- carimakanhalal/constants.py +37 -0
- carimakanhalal/exceptions.py +31 -0
- carimakanhalal/geo.py +40 -0
- carimakanhalal/models.py +263 -0
- python_carimakanhalal-0.1.0.dist-info/METADATA +65 -0
- python_carimakanhalal-0.1.0.dist-info/RECORD +14 -0
- python_carimakanhalal-0.1.0.dist-info/WHEEL +5 -0
- python_carimakanhalal-0.1.0.dist-info/entry_points.txt +2 -0
- python_carimakanhalal-0.1.0.dist-info/licenses/LICENSE +27 -0
- python_carimakanhalal-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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
|
+
]
|
carimakanhalal/cli.py
ADDED
|
@@ -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))
|
carimakanhalal/client.py
ADDED
|
@@ -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."""
|
carimakanhalal/geo.py
ADDED
|
@@ -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
|
carimakanhalal/models.py
ADDED
|
@@ -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,14 @@
|
|
|
1
|
+
carimakanhalal/__init__.py,sha256=5ZK0htj9fDrB-UOrblLKlyF3FXWpOCJncYq_-9k6jpI,1074
|
|
2
|
+
carimakanhalal/__main__.py,sha256=v9Q3r0jaiYD__YTkyzoQ9M4ocRQTnZ_2yA0KW_7ip6c,151
|
|
3
|
+
carimakanhalal/cli.py,sha256=SksYDMZN-YTcOqgCQZrU34wiZ29X6oFSU_uH3-aM9pU,2440
|
|
4
|
+
carimakanhalal/client.py,sha256=Plhgg0BPqtugFwOwsPla0_a3iQj62PSBFgRfBaiDD60,6037
|
|
5
|
+
carimakanhalal/constants.py,sha256=Dir_8LZKDaz30-cEUuDXq5BbP1SyAv8jbWU0xF1w7JY,944
|
|
6
|
+
carimakanhalal/exceptions.py,sha256=eK_QXSqkg3cOKrwX32LwIKvjHFIf-N3uatPS6-Jh3P4,1022
|
|
7
|
+
carimakanhalal/geo.py,sha256=4gcty27xA6F5eq9v8QQ77o4m6CvBRJmBCDQf68TGHLc,1213
|
|
8
|
+
carimakanhalal/models.py,sha256=rlFerp0qMSUYQ68x-skq8xEk9-6SZ19hQlzPaH_x8EA,8379
|
|
9
|
+
python_carimakanhalal-0.1.0.dist-info/licenses/LICENSE,sha256=kYpMu8Ouu9TIMBOK8qlhB-aKM2nvmVbTudXtMESI4wU,1390
|
|
10
|
+
python_carimakanhalal-0.1.0.dist-info/METADATA,sha256=j0XlvtoFa_a97iU_2zBYVzhKOzNEUoMHcsJOUyyiQeQ,2098
|
|
11
|
+
python_carimakanhalal-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
python_carimakanhalal-0.1.0.dist-info/entry_points.txt,sha256=K4dCseqsA00CmwE2hmCAjy25KwjR1waQWqkAxPj5JEg,59
|
|
13
|
+
python_carimakanhalal-0.1.0.dist-info/top_level.txt,sha256=D7BHj9OVeMj4RHAptNabZVYYftfxkM7H5EBlWiNPS_8,15
|
|
14
|
+
python_carimakanhalal-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
carimakanhalal
|