atm-milano 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.
- atm_milano-0.1.0/.gitignore +27 -0
- atm_milano-0.1.0/PKG-INFO +76 -0
- atm_milano-0.1.0/README.md +61 -0
- atm_milano-0.1.0/pyproject.toml +29 -0
- atm_milano-0.1.0/src/atm_milano/__init__.py +65 -0
- atm_milano-0.1.0/src/atm_milano/_version.py +24 -0
- atm_milano-0.1.0/src/atm_milano/client.py +327 -0
- atm_milano-0.1.0/src/atm_milano/errors.py +38 -0
- atm_milano-0.1.0/src/atm_milano/models.py +340 -0
- atm_milano-0.1.0/src/atm_milano/py.typed +0 -0
- atm_milano-0.1.0/tests/fixtures/geocode.json +31 -0
- atm_milano-0.1.0/tests/fixtures/journey_pattern.json +3224 -0
- atm_milano-0.1.0/tests/fixtures/line_summary.json +50 -0
- atm_milano-0.1.0/tests/fixtures/metro.json +59 -0
- atm_milano-0.1.0/tests/fixtures/search.json +385 -0
- atm_milano-0.1.0/tests/fixtures/timetable.json +418 -0
- atm_milano-0.1.0/tests/fixtures/trips.json +785 -0
- atm_milano-0.1.0/tests/test_client.py +85 -0
- atm_milano-0.1.0/tests/test_models.py +70 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.venv/
|
|
6
|
+
build/
|
|
7
|
+
dist/
|
|
8
|
+
|
|
9
|
+
# Tooling caches
|
|
10
|
+
.pytest_cache/
|
|
11
|
+
.ruff_cache/
|
|
12
|
+
.pyright/
|
|
13
|
+
.mypy_cache/
|
|
14
|
+
.coverage
|
|
15
|
+
htmlcov/
|
|
16
|
+
|
|
17
|
+
# Generated by hatch-vcs
|
|
18
|
+
_version.py
|
|
19
|
+
|
|
20
|
+
# Editors / OS
|
|
21
|
+
.idea/
|
|
22
|
+
.vscode/
|
|
23
|
+
*.swp
|
|
24
|
+
.DS_Store
|
|
25
|
+
|
|
26
|
+
# Local env
|
|
27
|
+
.env
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: atm-milano
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python client for ATM Milano (GiroMilano) journey planner, line, stop and metro data
|
|
5
|
+
Project-URL: Repository, https://github.com/matteoredaelli/atm-milano
|
|
6
|
+
Author-email: Matteo Redaelli <matteo.redaelli@gmail.com>
|
|
7
|
+
License-Expression: GPL-3.0-or-later
|
|
8
|
+
Keywords: atm,gtfs,milano,public-transport,transit
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.14
|
|
12
|
+
Requires-Dist: curl-cffi>=0.13
|
|
13
|
+
Requires-Dist: pydantic>=2.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# atm-milano
|
|
17
|
+
|
|
18
|
+
Async client for ATM Milano (GiroMilano) with pydantic models. Unofficial; endpoints may change.
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
pip install atm-milano
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## API (`AtmClient`)
|
|
25
|
+
|
|
26
|
+
| Method | Returns | Description |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| `search_places(term, kinds=, limit=)` | `SearchResults` | Addresses, localities, POIs (stations, stops) |
|
|
29
|
+
| `geocode(place)` | `Place` | Add coordinates to an address result |
|
|
30
|
+
| `resolve_place(ref)` | `Place` | Text, `Place` or `(lat, lng)` → place with coordinates |
|
|
31
|
+
| `plan_trip(origin, destination, when=, modes=)` | `TripPlan` | Public-transport trips (default: now, Europe/Rome) |
|
|
32
|
+
| `get_line_route(line, direction=0)` | `LineRoute` | Ordered stops of a line (`M1`..`M5`, `90`, `15`...) |
|
|
33
|
+
| `get_stop_lines(stop_code)` | `StopLines` | Lines at a stop with live wait times |
|
|
34
|
+
| `get_stop_timetable(stop_code, line, direction=0)` | `Timetable` | Scheduled times by day type and hour |
|
|
35
|
+
| `list_metro_stations(line=None)` | `list[MetroStation]` | Metro stations (Comune di Milano GIS) |
|
|
36
|
+
|
|
37
|
+
Errors: `AtmError` → `AtmBlockedError`, `AtmNotFoundError`, `AtmApiError`.
|
|
38
|
+
|
|
39
|
+
## Examples
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import asyncio
|
|
43
|
+
from datetime import datetime
|
|
44
|
+
from atm_milano import AtmClient, TransportMode
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def main():
|
|
48
|
+
async with AtmClient(lang="en") as c:
|
|
49
|
+
places = await c.search_places("Cadorna")
|
|
50
|
+
print(places.places[0].name, places.places[0].code)
|
|
51
|
+
|
|
52
|
+
plan = await c.plan_trip(
|
|
53
|
+
"Cadorna",
|
|
54
|
+
"Stazione Centrale",
|
|
55
|
+
when=datetime(2026, 11, 20, 9, 30),
|
|
56
|
+
modes=[TransportMode.METRO],
|
|
57
|
+
)
|
|
58
|
+
trip = plan.trips[0]
|
|
59
|
+
print(trip.duration_minutes, "min", [s.description for s in trip.steps])
|
|
60
|
+
|
|
61
|
+
route = await c.get_line_route("M1", direction=0)
|
|
62
|
+
print(route.description, len(route.stops), "stops")
|
|
63
|
+
|
|
64
|
+
stop = await c.get_stop_lines("-51") # Cadorna M1
|
|
65
|
+
print([(a.line_code, a.wait) for a in stop.arrivals])
|
|
66
|
+
|
|
67
|
+
tt = await c.get_stop_timetable("12254", "1") # tram 1 at Greco Rovereto
|
|
68
|
+
print(tt.schedules[0].day_type)
|
|
69
|
+
|
|
70
|
+
print(len(await c.list_metro_stations("M2")), "M2 stations")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
asyncio.run(main())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Origins/destinations accept free text, a `Place`, or a `(lat, lng)` tuple.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# atm-milano
|
|
2
|
+
|
|
3
|
+
Async client for ATM Milano (GiroMilano) with pydantic models. Unofficial; endpoints may change.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
pip install atm-milano
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## API (`AtmClient`)
|
|
10
|
+
|
|
11
|
+
| Method | Returns | Description |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `search_places(term, kinds=, limit=)` | `SearchResults` | Addresses, localities, POIs (stations, stops) |
|
|
14
|
+
| `geocode(place)` | `Place` | Add coordinates to an address result |
|
|
15
|
+
| `resolve_place(ref)` | `Place` | Text, `Place` or `(lat, lng)` → place with coordinates |
|
|
16
|
+
| `plan_trip(origin, destination, when=, modes=)` | `TripPlan` | Public-transport trips (default: now, Europe/Rome) |
|
|
17
|
+
| `get_line_route(line, direction=0)` | `LineRoute` | Ordered stops of a line (`M1`..`M5`, `90`, `15`...) |
|
|
18
|
+
| `get_stop_lines(stop_code)` | `StopLines` | Lines at a stop with live wait times |
|
|
19
|
+
| `get_stop_timetable(stop_code, line, direction=0)` | `Timetable` | Scheduled times by day type and hour |
|
|
20
|
+
| `list_metro_stations(line=None)` | `list[MetroStation]` | Metro stations (Comune di Milano GIS) |
|
|
21
|
+
|
|
22
|
+
Errors: `AtmError` → `AtmBlockedError`, `AtmNotFoundError`, `AtmApiError`.
|
|
23
|
+
|
|
24
|
+
## Examples
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import asyncio
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from atm_milano import AtmClient, TransportMode
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def main():
|
|
33
|
+
async with AtmClient(lang="en") as c:
|
|
34
|
+
places = await c.search_places("Cadorna")
|
|
35
|
+
print(places.places[0].name, places.places[0].code)
|
|
36
|
+
|
|
37
|
+
plan = await c.plan_trip(
|
|
38
|
+
"Cadorna",
|
|
39
|
+
"Stazione Centrale",
|
|
40
|
+
when=datetime(2026, 11, 20, 9, 30),
|
|
41
|
+
modes=[TransportMode.METRO],
|
|
42
|
+
)
|
|
43
|
+
trip = plan.trips[0]
|
|
44
|
+
print(trip.duration_minutes, "min", [s.description for s in trip.steps])
|
|
45
|
+
|
|
46
|
+
route = await c.get_line_route("M1", direction=0)
|
|
47
|
+
print(route.description, len(route.stops), "stops")
|
|
48
|
+
|
|
49
|
+
stop = await c.get_stop_lines("-51") # Cadorna M1
|
|
50
|
+
print([(a.line_code, a.wait) for a in stop.arrivals])
|
|
51
|
+
|
|
52
|
+
tt = await c.get_stop_timetable("12254", "1") # tram 1 at Greco Rovereto
|
|
53
|
+
print(tt.schedules[0].day_type)
|
|
54
|
+
|
|
55
|
+
print(len(await c.list_metro_stations("M2")), "M2 stations")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
asyncio.run(main())
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Origins/destinations accept free text, a `Place`, or a `(lat, lng)` tuple.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27", "hatch-vcs"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "atm-milano"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Async Python client for ATM Milano (GiroMilano) journey planner, line, stop and metro data"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "GPL-3.0-or-later"
|
|
11
|
+
authors = [{ name = "Matteo Redaelli", email = "matteo.redaelli@gmail.com" }]
|
|
12
|
+
requires-python = ">=3.14"
|
|
13
|
+
keywords = ["atm", "milano", "transit", "public-transport", "gtfs"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3.14", "Typing :: Typed"]
|
|
15
|
+
dependencies = ["curl-cffi>=0.13", "pydantic>=2.10"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Repository = "https://github.com/matteoredaelli/atm-milano"
|
|
19
|
+
|
|
20
|
+
# Version comes from the git tag (v0.1.0 -> 0.1.0); repo root is two levels up.
|
|
21
|
+
[tool.hatch.version]
|
|
22
|
+
source = "vcs"
|
|
23
|
+
raw-options = { root = "../..", local_scheme = "no-local-version" }
|
|
24
|
+
|
|
25
|
+
[tool.hatch.build.hooks.vcs]
|
|
26
|
+
version-file = "src/atm_milano/_version.py"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/atm_milano"]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Copyright (C) 2026 Matteo Redaelli
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
#
|
|
16
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
17
|
+
|
|
18
|
+
"""Async client for ATM Milano (GiroMilano) public data."""
|
|
19
|
+
|
|
20
|
+
from .client import AtmClient
|
|
21
|
+
from .errors import AtmApiError, AtmBlockedError, AtmError, AtmNotFoundError
|
|
22
|
+
from .models import (
|
|
23
|
+
Fare,
|
|
24
|
+
LineRoute,
|
|
25
|
+
LineStop,
|
|
26
|
+
MetroStation,
|
|
27
|
+
Place,
|
|
28
|
+
PlaceKind,
|
|
29
|
+
Ride,
|
|
30
|
+
SearchResults,
|
|
31
|
+
StepType,
|
|
32
|
+
StopArrival,
|
|
33
|
+
StopLines,
|
|
34
|
+
Timetable,
|
|
35
|
+
TransportMode,
|
|
36
|
+
Trip,
|
|
37
|
+
TripPlan,
|
|
38
|
+
TripStep,
|
|
39
|
+
Waypoint,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"AtmApiError",
|
|
44
|
+
"AtmBlockedError",
|
|
45
|
+
"AtmClient",
|
|
46
|
+
"AtmError",
|
|
47
|
+
"AtmNotFoundError",
|
|
48
|
+
"Fare",
|
|
49
|
+
"LineRoute",
|
|
50
|
+
"LineStop",
|
|
51
|
+
"MetroStation",
|
|
52
|
+
"Place",
|
|
53
|
+
"PlaceKind",
|
|
54
|
+
"Ride",
|
|
55
|
+
"SearchResults",
|
|
56
|
+
"StepType",
|
|
57
|
+
"StopArrival",
|
|
58
|
+
"StopLines",
|
|
59
|
+
"Timetable",
|
|
60
|
+
"TransportMode",
|
|
61
|
+
"Trip",
|
|
62
|
+
"TripPlan",
|
|
63
|
+
"TripStep",
|
|
64
|
+
"Waypoint",
|
|
65
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
# Copyright (C) 2026 Matteo Redaelli
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
#
|
|
16
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
17
|
+
|
|
18
|
+
"""Async HTTP client for ATM Milano (GiroMilano) and the Comune di Milano GIS."""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
from collections.abc import Iterable
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from types import TracebackType
|
|
26
|
+
from typing import Any, Literal, Protocol, Self
|
|
27
|
+
from zoneinfo import ZoneInfo
|
|
28
|
+
|
|
29
|
+
from curl_cffi import requests as cffi
|
|
30
|
+
|
|
31
|
+
from .errors import AtmApiError, AtmBlockedError, AtmNotFoundError
|
|
32
|
+
from .models import (
|
|
33
|
+
LineRoute,
|
|
34
|
+
MetroStation,
|
|
35
|
+
Place,
|
|
36
|
+
PlaceKind,
|
|
37
|
+
SearchResults,
|
|
38
|
+
StopLines,
|
|
39
|
+
Timetable,
|
|
40
|
+
TransportMode,
|
|
41
|
+
Trip,
|
|
42
|
+
TripPlan,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
BASE = "https://giromilano.atm.it"
|
|
46
|
+
SEARCH_API = f"{BASE}/proxy.search/api/atmSearch"
|
|
47
|
+
TP_API = f"{BASE}/proxy.tpportal/api/tpportal"
|
|
48
|
+
GIS_METRO = (
|
|
49
|
+
"https://gisportal.comune.milano.it/server/rest/services/D_Mobilita/ATM_Metro/MapServer/0/query"
|
|
50
|
+
)
|
|
51
|
+
ROME = ZoneInfo("Europe/Rome")
|
|
52
|
+
|
|
53
|
+
Lang = Literal["en", "it"]
|
|
54
|
+
PlaceRef = str | Place | tuple[float, float]
|
|
55
|
+
"""A free-text query, a resolved Place, or a (lat, lng) tuple."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class HttpSession(Protocol):
|
|
59
|
+
"""The subset of curl_cffi's AsyncSession used here (lets tests inject a fake)."""
|
|
60
|
+
|
|
61
|
+
async def request(self, method: str, url: str, **kwargs: Any) -> Any: ...
|
|
62
|
+
async def close(self) -> Any: ...
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class AtmClient:
|
|
66
|
+
"""Client for the unofficial GiroMilano endpoints.
|
|
67
|
+
|
|
68
|
+
Uses Chrome TLS impersonation (curl_cffi) because the site sits behind Akamai bot protection.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
lang: Lang = "en",
|
|
75
|
+
timeout: float = 20.0,
|
|
76
|
+
retries: int = 2,
|
|
77
|
+
session: HttpSession | None = None,
|
|
78
|
+
) -> None:
|
|
79
|
+
self.lang: Lang = lang
|
|
80
|
+
self.timeout = timeout
|
|
81
|
+
self.retries = retries
|
|
82
|
+
self._owns_session = session is None
|
|
83
|
+
self._session: HttpSession = session or cffi.AsyncSession( # pyright: ignore[reportAttributeAccessIssue]
|
|
84
|
+
impersonate="chrome",
|
|
85
|
+
headers={"Referer": f"{BASE}/", "Accept": "application/json, text/plain, */*"},
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
async def __aenter__(self) -> Self:
|
|
89
|
+
return self
|
|
90
|
+
|
|
91
|
+
async def __aexit__(
|
|
92
|
+
self,
|
|
93
|
+
exc_type: type[BaseException] | None,
|
|
94
|
+
exc: BaseException | None,
|
|
95
|
+
tb: TracebackType | None,
|
|
96
|
+
) -> None:
|
|
97
|
+
await self.aclose()
|
|
98
|
+
|
|
99
|
+
async def aclose(self) -> None:
|
|
100
|
+
if self._owns_session:
|
|
101
|
+
await self._session.close()
|
|
102
|
+
|
|
103
|
+
# -- transport ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
async def _request(self, method: str, url: str, params: dict[str, Any] | None = None) -> Any:
|
|
106
|
+
last: Exception | None = None
|
|
107
|
+
for attempt in range(self.retries + 1):
|
|
108
|
+
try:
|
|
109
|
+
r = await self._session.request(method, url, params=params, timeout=self.timeout)
|
|
110
|
+
except Exception as e: # network-level failure
|
|
111
|
+
last = AtmApiError(f"{method} {url} failed: {e}")
|
|
112
|
+
else:
|
|
113
|
+
if r.status_code == 403:
|
|
114
|
+
raise AtmBlockedError(f"Blocked by edge protection: {url}")
|
|
115
|
+
if r.status_code == 404:
|
|
116
|
+
raise AtmNotFoundError(f"Not found: {url}")
|
|
117
|
+
if r.status_code < 400:
|
|
118
|
+
try:
|
|
119
|
+
return r.json()
|
|
120
|
+
except ValueError as e:
|
|
121
|
+
raise AtmApiError(f"Invalid JSON from {url}", r.status_code) from e
|
|
122
|
+
last = AtmApiError(f"HTTP {r.status_code} from {url}", r.status_code)
|
|
123
|
+
if r.status_code < 500:
|
|
124
|
+
raise last
|
|
125
|
+
if attempt < self.retries:
|
|
126
|
+
await asyncio.sleep(0.5 * 2**attempt)
|
|
127
|
+
assert last is not None
|
|
128
|
+
raise last
|
|
129
|
+
|
|
130
|
+
# -- places ------------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
async def search_places(
|
|
133
|
+
self,
|
|
134
|
+
term: str,
|
|
135
|
+
*,
|
|
136
|
+
kinds: Iterable[PlaceKind] = (PlaceKind.ADDRESS, PlaceKind.LOCALITY, PlaceKind.POI),
|
|
137
|
+
limit: int = 15,
|
|
138
|
+
lang: Lang | None = None,
|
|
139
|
+
) -> SearchResults:
|
|
140
|
+
"""Search addresses, localities and POIs (stations, stops, bike-sharing...)."""
|
|
141
|
+
data = await self._request(
|
|
142
|
+
"GET",
|
|
143
|
+
f"{SEARCH_API}/search",
|
|
144
|
+
{
|
|
145
|
+
"Lang": lang or self.lang,
|
|
146
|
+
"RighePerCategoria": 3,
|
|
147
|
+
"Tipi": ",".join(k.value for k in kinds),
|
|
148
|
+
"page": 1,
|
|
149
|
+
"rows": limit,
|
|
150
|
+
"soloGeocodificati": "true",
|
|
151
|
+
"searchTerm": term,
|
|
152
|
+
},
|
|
153
|
+
)
|
|
154
|
+
return SearchResults(
|
|
155
|
+
places=[Place.model_validate(r) for r in data.get("rows", [])],
|
|
156
|
+
total_pages=int(data.get("total", 1) or 1),
|
|
157
|
+
total_records=int(data.get("records", 0) or 0),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
async def geocode(self, place: Place) -> Place:
|
|
161
|
+
"""Fill in coordinates for an address result that lacks them."""
|
|
162
|
+
if place.has_coordinates:
|
|
163
|
+
return place
|
|
164
|
+
data = await self._request(
|
|
165
|
+
"POST",
|
|
166
|
+
f"{SEARCH_API}/Geocode",
|
|
167
|
+
{
|
|
168
|
+
"comune": place.municipality,
|
|
169
|
+
"indirizzo": place.name,
|
|
170
|
+
"civico": place.house_number or "",
|
|
171
|
+
},
|
|
172
|
+
)
|
|
173
|
+
item = data.get("geocodeditem")
|
|
174
|
+
if not item:
|
|
175
|
+
raise AtmNotFoundError(f"Could not geocode {place.description!r}")
|
|
176
|
+
lat = item["lat"] if item.get("lat", -1) != -1 else item.get("p_lat")
|
|
177
|
+
lng = item["lon"] if item.get("lon", -1) != -1 else item.get("p_lon")
|
|
178
|
+
if lat is None or lng is None:
|
|
179
|
+
raise AtmNotFoundError(f"Could not geocode {place.description!r}")
|
|
180
|
+
return place.model_copy(update={"lat": lat, "lng": lng})
|
|
181
|
+
|
|
182
|
+
async def resolve_place(self, ref: PlaceRef) -> Place:
|
|
183
|
+
"""Turn a text query / Place / (lat, lng) into a Place with coordinates."""
|
|
184
|
+
if isinstance(ref, tuple):
|
|
185
|
+
lat, lng = ref
|
|
186
|
+
return Place.model_validate(
|
|
187
|
+
{
|
|
188
|
+
"id": 0,
|
|
189
|
+
"kind": PlaceKind.ADDRESS,
|
|
190
|
+
"name": f"{lat:.5f},{lng:.5f}",
|
|
191
|
+
"lat": lat,
|
|
192
|
+
"lng": lng,
|
|
193
|
+
}
|
|
194
|
+
)
|
|
195
|
+
if isinstance(ref, Place):
|
|
196
|
+
return await self.geocode(ref)
|
|
197
|
+
results = await self.search_places(ref, limit=5)
|
|
198
|
+
if not results.places:
|
|
199
|
+
raise AtmNotFoundError(f"No place found for {ref!r}")
|
|
200
|
+
# Prefer a POI (stations etc.) or Milan address that already has coordinates.
|
|
201
|
+
ranked = sorted(
|
|
202
|
+
results.places,
|
|
203
|
+
key=lambda p: (p.municipality.lower() != "milano", not p.has_coordinates),
|
|
204
|
+
)
|
|
205
|
+
return await self.geocode(ranked[0])
|
|
206
|
+
|
|
207
|
+
# -- trips -------------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
async def plan_trip(
|
|
210
|
+
self,
|
|
211
|
+
origin: PlaceRef,
|
|
212
|
+
destination: PlaceRef,
|
|
213
|
+
*,
|
|
214
|
+
when: datetime | None = None,
|
|
215
|
+
modes: Iterable[TransportMode] = (
|
|
216
|
+
TransportMode.METRO,
|
|
217
|
+
TransportMode.BUS,
|
|
218
|
+
TransportMode.TRAM,
|
|
219
|
+
TransportMode.RAIL,
|
|
220
|
+
),
|
|
221
|
+
lang: Lang | None = None,
|
|
222
|
+
) -> TripPlan:
|
|
223
|
+
"""Plan public-transport trips departing at `when` (default: now, Europe/Rome)."""
|
|
224
|
+
src, dst = await asyncio.gather(self.resolve_place(origin), self.resolve_place(destination))
|
|
225
|
+
if when is None:
|
|
226
|
+
when = datetime.now(ROME)
|
|
227
|
+
elif when.tzinfo is None:
|
|
228
|
+
when = when.replace(tzinfo=ROME)
|
|
229
|
+
else:
|
|
230
|
+
when = when.astimezone(ROME)
|
|
231
|
+
data = await self._request(
|
|
232
|
+
"GET",
|
|
233
|
+
f"{TP_API}/tpl/trips",
|
|
234
|
+
{
|
|
235
|
+
"FromPoint.X": src.lng,
|
|
236
|
+
"FromPoint.Y": src.lat,
|
|
237
|
+
"ToPoint.X": dst.lng,
|
|
238
|
+
"ToPoint.Y": dst.lat,
|
|
239
|
+
"Date": when.strftime("%Y-%m-%d"),
|
|
240
|
+
"FromSeconds": when.hour * 3600 + when.minute * 60,
|
|
241
|
+
"TransportModes": ",".join(m.value for m in modes),
|
|
242
|
+
"Lang": lang or self.lang,
|
|
243
|
+
"FromDescription": src.description,
|
|
244
|
+
"ToDescription": dst.description,
|
|
245
|
+
},
|
|
246
|
+
)
|
|
247
|
+
return TripPlan(
|
|
248
|
+
origin=src,
|
|
249
|
+
destination=dst,
|
|
250
|
+
trips=[Trip.model_validate(t) for t in data.get("Trips") or []],
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
# -- lines & stops -----------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
async def get_line_route(self, line_code: str, direction: int = 0) -> LineRoute:
|
|
256
|
+
"""Ordered stops of a line. Metro codes are -1..-5 (M1..M5); bus/tram use their number."""
|
|
257
|
+
line_code = _normalize_line(line_code)
|
|
258
|
+
data = await self._request(
|
|
259
|
+
"GET",
|
|
260
|
+
f"{TP_API}/tpl/journeyPatterns/{line_code}|{direction}",
|
|
261
|
+
{"alternativeRoutesMode": "false"},
|
|
262
|
+
)
|
|
263
|
+
return LineRoute.model_validate(data)
|
|
264
|
+
|
|
265
|
+
async def get_stop_lines(self, stop_code: str) -> StopLines:
|
|
266
|
+
"""Lines serving a stop, with live wait messages."""
|
|
267
|
+
data = await self._request("GET", f"{TP_API}/tpl/stops/{stop_code}/linesummary")
|
|
268
|
+
return StopLines.model_validate(data)
|
|
269
|
+
|
|
270
|
+
async def get_stop_timetable(
|
|
271
|
+
self, stop_code: str, line_code: str, direction: int = 0
|
|
272
|
+
) -> Timetable:
|
|
273
|
+
"""Scheduled timetable of a line at a stop."""
|
|
274
|
+
line_code = _normalize_line(line_code)
|
|
275
|
+
data = await self._request(
|
|
276
|
+
"GET", f"{TP_API}/tpl/stops/{stop_code}/timetable/line/{line_code}/dir/{direction}"
|
|
277
|
+
)
|
|
278
|
+
return Timetable.model_validate(data)
|
|
279
|
+
|
|
280
|
+
# -- metro (Comune di Milano GIS) --------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
async def list_metro_stations(self, line: str | None = None) -> list[MetroStation]:
|
|
283
|
+
"""All metro station entries (one per line served) from the Comune di Milano GIS."""
|
|
284
|
+
out: list[MetroStation] = []
|
|
285
|
+
offset = 0
|
|
286
|
+
while True:
|
|
287
|
+
data = await self._request(
|
|
288
|
+
"GET",
|
|
289
|
+
GIS_METRO,
|
|
290
|
+
{
|
|
291
|
+
"where": "1=1",
|
|
292
|
+
"outFields": "linee,nome",
|
|
293
|
+
"returnGeometry": "true",
|
|
294
|
+
"outSR": 4326,
|
|
295
|
+
"f": "json",
|
|
296
|
+
"resultOffset": offset,
|
|
297
|
+
"resultRecordCount": 1000,
|
|
298
|
+
},
|
|
299
|
+
)
|
|
300
|
+
feats = data.get("features", [])
|
|
301
|
+
for f in feats:
|
|
302
|
+
g, a = f.get("geometry"), f["attributes"]
|
|
303
|
+
if not g:
|
|
304
|
+
continue
|
|
305
|
+
out.append(
|
|
306
|
+
MetroStation(
|
|
307
|
+
name=a["nome"],
|
|
308
|
+
lines=[x.strip() for x in str(a["linee"]).split(",") if x.strip()],
|
|
309
|
+
lat=g["y"],
|
|
310
|
+
lng=g["x"],
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
if not data.get("exceededTransferLimit") or not feats:
|
|
314
|
+
break
|
|
315
|
+
offset += len(feats)
|
|
316
|
+
if line:
|
|
317
|
+
want = line.upper().removeprefix("M")
|
|
318
|
+
out = [s for s in out if want in s.lines]
|
|
319
|
+
return out
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
_METRO_CODES = {"M1": "-1", "M2": "-2", "M3": "-3", "M4": "-4", "M5": "-5"}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _normalize_line(code: str) -> str:
|
|
326
|
+
"""Accept 'M1'..'M5' as aliases of the internal negative codes."""
|
|
327
|
+
return _METRO_CODES.get(code.strip().upper(), code.strip())
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Copyright (C) 2026 Matteo Redaelli
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU General Public License as published by
|
|
5
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
6
|
+
# (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
#
|
|
16
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
17
|
+
|
|
18
|
+
"""Exception hierarchy."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AtmError(Exception):
|
|
22
|
+
"""Base class for all errors raised by this library."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AtmBlockedError(AtmError):
|
|
26
|
+
"""The edge/bot protection (Akamai) rejected the request (HTTP 403)."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AtmNotFoundError(AtmError):
|
|
30
|
+
"""The requested resource (line, stop, place) does not exist."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AtmApiError(AtmError):
|
|
34
|
+
"""The upstream service returned an unexpected status or payload."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
self.status_code = status_code
|