septa-api 0.1.0__tar.gz → 0.2.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.
- {septa_api-0.1.0/septa_api.egg-info → septa_api-0.2.0}/PKG-INFO +34 -7
- {septa_api-0.1.0 → septa_api-0.2.0}/README.md +33 -6
- {septa_api-0.1.0 → septa_api-0.2.0}/pyproject.toml +1 -1
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/__init__.py +2 -1
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/client.py +86 -6
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/models.py +21 -1
- {septa_api-0.1.0 → septa_api-0.2.0/septa_api.egg-info}/PKG-INFO +34 -7
- {septa_api-0.1.0 → septa_api-0.2.0}/tests/test_client.py +106 -5
- {septa_api-0.1.0 → septa_api-0.2.0}/LICENSE +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/catalog.json +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/catalog.py +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/exceptions.py +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api/py.typed +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api.egg-info/SOURCES.txt +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api.egg-info/dependency_links.txt +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api.egg-info/requires.txt +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/septa_api.egg-info/top_level.txt +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/setup.cfg +0 -0
- {septa_api-0.1.0 → septa_api-0.2.0}/tests/test_catalog.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: septa-api
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python API client for SEPTA real-time data, alerts, and schedules
|
|
5
5
|
Author: zackwag
|
|
6
6
|
License: MIT
|
|
@@ -44,11 +44,20 @@ async def main():
|
|
|
44
44
|
async with aiohttp.ClientSession() as session:
|
|
45
45
|
client = SeptaClient(session)
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
alerts = await client.async_get_alerts()
|
|
48
|
+
cancelled = {t for a in alerts if a.effect == "NO_SERVICE" for t in a.trip_ids}
|
|
49
|
+
|
|
50
|
+
departures = await client.async_get_stop_departures(
|
|
51
|
+
stop_id, route.id, results=3, cancelled_trip_ids=cancelled
|
|
52
|
+
)
|
|
53
|
+
for departure in departures:
|
|
54
|
+
if departure.cancelled:
|
|
55
|
+
label = "cancelled"
|
|
56
|
+
else:
|
|
57
|
+
label = "live" if departure.realtime else "scheduled"
|
|
49
58
|
print(f"{catalog.stops[stop_id]}: {departure.expected:%H:%M} ({label})")
|
|
50
59
|
|
|
51
|
-
for alert in
|
|
60
|
+
for alert in alerts:
|
|
52
61
|
if route.id in alert.route_ids:
|
|
53
62
|
print(f"{alert.severity}: {alert.header}")
|
|
54
63
|
|
|
@@ -88,24 +97,42 @@ Takes an `aiohttp.ClientSession`, which the caller owns.
|
|
|
88
97
|
|
|
89
98
|
Every active and upcoming `Alert` across all modes. Route-level alerts list `route_ids` and apply to both directions. Trip cancellations list only `trip_ids`, which match `StopDeparture.trip_id`. Use `alert.is_active(now)` to filter by the alert's active periods.
|
|
90
99
|
|
|
91
|
-
### `await client.async_get_stop_departures(stop_id, route_id, results=20)`
|
|
100
|
+
### `await client.async_get_stop_departures(stop_id, route_id, results=20, cancelled_trip_ids=())`
|
|
92
101
|
|
|
93
102
|
Upcoming `StopDeparture`s of one route from a bus, trolley, or subway stop, from the timetable. When a live vehicle is running the trip, `delay_minutes` and `vehicle_id` are filled in and `realtime` is `True`; `expected` is the scheduled time plus the delay. SEPTA caps `results` at 20.
|
|
94
103
|
|
|
104
|
+
The timetable still lists trips SEPTA has cancelled. Pass the `trip_ids` of `NO_SERVICE` alerts as `cancelled_trip_ids` and those departures come back with `cancelled` set to `True`, so they don't pass for a bus that's coming. Taking the IDs from the caller avoids fetching the alert feeds again for every stop.
|
|
105
|
+
|
|
95
106
|
### `await client.async_get_vehicles(route_id)`
|
|
96
107
|
|
|
97
108
|
Live `Vehicle` positions on a bus or trolley route. `direction` matches the catalog's direction names case-insensitively. Empty for subway lines.
|
|
98
109
|
|
|
99
|
-
### `await client.async_get_station_departures(station, results=5)`
|
|
110
|
+
### `await client.async_get_station_departures(station, results=5, cancelled_trains=None)`
|
|
100
111
|
|
|
101
112
|
A Regional Rail station's live departure board, as `TrainDeparture`s, `results` per direction. `direction` is `N` or `S` (SEPTA's through-Center-City convention), not inbound/outbound.
|
|
102
113
|
|
|
103
|
-
### `await client.async_get_next_to_arrive(origin, destination, results=5)`
|
|
114
|
+
### `await client.async_get_next_to_arrive(origin, destination, results=5, cancelled_trains=None)`
|
|
104
115
|
|
|
105
116
|
The next Regional Rail `Trip`s between two stations, each with one or two `TripLeg`s and the `connection_station` if there's a transfer.
|
|
106
117
|
|
|
107
118
|
Station arguments are catalog stop names; the client translates them to the legacy names SEPTA's JSON API expects. Station names in the results (`origin`, `connection_station`, ...) are SEPTA's legacy names.
|
|
108
119
|
|
|
120
|
+
### `cancelled_trains(alerts)`
|
|
121
|
+
|
|
122
|
+
SEPTA lists cancelled Regional Rail trains as on time. This maps the train numbers that alerts say are cancelled to `None` (the whole train) or the alert's text (part of its run). Pass it as `cancelled_trains` to either rail method: wholly cancelled `TrainDeparture`s and `TripLeg`s come back with `cancelled` set to `True`, partly cancelled ones with `cancelled` left `False` and the alert text in `cancellation_note`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
now = datetime.now(TIMEZONE)
|
|
126
|
+
alerts = [a for a in await client.async_get_alerts() if a.is_active(now)]
|
|
127
|
+
trips = await client.async_get_next_to_arrive(
|
|
128
|
+
"Doylestown", "Suburban Station", cancelled_trains=cancelled_trains(alerts)
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Filter by `is_active()` first: train numbers repeat daily, so an expired alert would otherwise flag the same train on a later day.
|
|
133
|
+
|
|
134
|
+
Rail cancellations come either as structured trip alerts or only as alert text ("Inbound train #5319 ... is canceled ..."), and the text match follows SEPTA's current wording. Partial cancellations aren't flagged because the same train really does run on the rest of its route: on 2026-11-30, train 5319 "canceled to Suburban Station" skipped Doylestown to Suburban but ran on to Wawa, so flagging it would have been wrong at Media and Wawa. Show `cancellation_note` so riders at the affected stations still see the warning.
|
|
135
|
+
|
|
109
136
|
### Exceptions
|
|
110
137
|
|
|
111
138
|
- `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
|
|
@@ -29,11 +29,20 @@ async def main():
|
|
|
29
29
|
async with aiohttp.ClientSession() as session:
|
|
30
30
|
client = SeptaClient(session)
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
alerts = await client.async_get_alerts()
|
|
33
|
+
cancelled = {t for a in alerts if a.effect == "NO_SERVICE" for t in a.trip_ids}
|
|
34
|
+
|
|
35
|
+
departures = await client.async_get_stop_departures(
|
|
36
|
+
stop_id, route.id, results=3, cancelled_trip_ids=cancelled
|
|
37
|
+
)
|
|
38
|
+
for departure in departures:
|
|
39
|
+
if departure.cancelled:
|
|
40
|
+
label = "cancelled"
|
|
41
|
+
else:
|
|
42
|
+
label = "live" if departure.realtime else "scheduled"
|
|
34
43
|
print(f"{catalog.stops[stop_id]}: {departure.expected:%H:%M} ({label})")
|
|
35
44
|
|
|
36
|
-
for alert in
|
|
45
|
+
for alert in alerts:
|
|
37
46
|
if route.id in alert.route_ids:
|
|
38
47
|
print(f"{alert.severity}: {alert.header}")
|
|
39
48
|
|
|
@@ -73,24 +82,42 @@ Takes an `aiohttp.ClientSession`, which the caller owns.
|
|
|
73
82
|
|
|
74
83
|
Every active and upcoming `Alert` across all modes. Route-level alerts list `route_ids` and apply to both directions. Trip cancellations list only `trip_ids`, which match `StopDeparture.trip_id`. Use `alert.is_active(now)` to filter by the alert's active periods.
|
|
75
84
|
|
|
76
|
-
### `await client.async_get_stop_departures(stop_id, route_id, results=20)`
|
|
85
|
+
### `await client.async_get_stop_departures(stop_id, route_id, results=20, cancelled_trip_ids=())`
|
|
77
86
|
|
|
78
87
|
Upcoming `StopDeparture`s of one route from a bus, trolley, or subway stop, from the timetable. When a live vehicle is running the trip, `delay_minutes` and `vehicle_id` are filled in and `realtime` is `True`; `expected` is the scheduled time plus the delay. SEPTA caps `results` at 20.
|
|
79
88
|
|
|
89
|
+
The timetable still lists trips SEPTA has cancelled. Pass the `trip_ids` of `NO_SERVICE` alerts as `cancelled_trip_ids` and those departures come back with `cancelled` set to `True`, so they don't pass for a bus that's coming. Taking the IDs from the caller avoids fetching the alert feeds again for every stop.
|
|
90
|
+
|
|
80
91
|
### `await client.async_get_vehicles(route_id)`
|
|
81
92
|
|
|
82
93
|
Live `Vehicle` positions on a bus or trolley route. `direction` matches the catalog's direction names case-insensitively. Empty for subway lines.
|
|
83
94
|
|
|
84
|
-
### `await client.async_get_station_departures(station, results=5)`
|
|
95
|
+
### `await client.async_get_station_departures(station, results=5, cancelled_trains=None)`
|
|
85
96
|
|
|
86
97
|
A Regional Rail station's live departure board, as `TrainDeparture`s, `results` per direction. `direction` is `N` or `S` (SEPTA's through-Center-City convention), not inbound/outbound.
|
|
87
98
|
|
|
88
|
-
### `await client.async_get_next_to_arrive(origin, destination, results=5)`
|
|
99
|
+
### `await client.async_get_next_to_arrive(origin, destination, results=5, cancelled_trains=None)`
|
|
89
100
|
|
|
90
101
|
The next Regional Rail `Trip`s between two stations, each with one or two `TripLeg`s and the `connection_station` if there's a transfer.
|
|
91
102
|
|
|
92
103
|
Station arguments are catalog stop names; the client translates them to the legacy names SEPTA's JSON API expects. Station names in the results (`origin`, `connection_station`, ...) are SEPTA's legacy names.
|
|
93
104
|
|
|
105
|
+
### `cancelled_trains(alerts)`
|
|
106
|
+
|
|
107
|
+
SEPTA lists cancelled Regional Rail trains as on time. This maps the train numbers that alerts say are cancelled to `None` (the whole train) or the alert's text (part of its run). Pass it as `cancelled_trains` to either rail method: wholly cancelled `TrainDeparture`s and `TripLeg`s come back with `cancelled` set to `True`, partly cancelled ones with `cancelled` left `False` and the alert text in `cancellation_note`.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
now = datetime.now(TIMEZONE)
|
|
111
|
+
alerts = [a for a in await client.async_get_alerts() if a.is_active(now)]
|
|
112
|
+
trips = await client.async_get_next_to_arrive(
|
|
113
|
+
"Doylestown", "Suburban Station", cancelled_trains=cancelled_trains(alerts)
|
|
114
|
+
)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Filter by `is_active()` first: train numbers repeat daily, so an expired alert would otherwise flag the same train on a later day.
|
|
118
|
+
|
|
119
|
+
Rail cancellations come either as structured trip alerts or only as alert text ("Inbound train #5319 ... is canceled ..."), and the text match follows SEPTA's current wording. Partial cancellations aren't flagged because the same train really does run on the rest of its route: on 2026-11-30, train 5319 "canceled to Suburban Station" skipped Doylestown to Suburban but ran on to Wawa, so flagging it would have been wrong at Media and Wawa. Show `cancellation_note` so riders at the affected stations still see the warning.
|
|
120
|
+
|
|
94
121
|
### Exceptions
|
|
95
122
|
|
|
96
123
|
- `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Python API client for SEPTA (Southeastern Pennsylvania Transportation Authority)."""
|
|
2
2
|
|
|
3
3
|
from .catalog import Catalog, Route, RouteDirection, load_catalog
|
|
4
|
-
from .client import TIMEZONE, SeptaClient
|
|
4
|
+
from .client import TIMEZONE, SeptaClient, cancelled_trains
|
|
5
5
|
from .exceptions import SeptaConnectionError, SeptaError, SeptaRequestError
|
|
6
6
|
from .models import Alert, StopDeparture, TrainDeparture, Trip, TripLeg, Vehicle
|
|
7
7
|
|
|
@@ -20,5 +20,6 @@ __all__ = [
|
|
|
20
20
|
"Trip",
|
|
21
21
|
"TripLeg",
|
|
22
22
|
"Vehicle",
|
|
23
|
+
"cancelled_trains",
|
|
23
24
|
"load_catalog",
|
|
24
25
|
]
|
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import asyncio
|
|
6
6
|
import json
|
|
7
7
|
import re
|
|
8
|
+
from collections.abc import Collection, Iterable, Mapping
|
|
8
9
|
from datetime import datetime, timedelta
|
|
9
10
|
from typing import Any
|
|
10
11
|
from zoneinfo import ZoneInfo
|
|
@@ -60,6 +61,16 @@ _STATION_NAMES = {
|
|
|
60
61
|
# Arrivals takes "Wayne" but not "Wayne Station"; NextToArrive is the reverse.
|
|
61
62
|
_NEXT_TO_ARRIVE_NAMES = {**_STATION_NAMES, "Wayne": "Wayne Station"}
|
|
62
63
|
|
|
64
|
+
# Rail GTFS trip IDs embed the train number after the route: LAN3508_20261019_...
|
|
65
|
+
_RAIL_TRIP_RE = re.compile(r"^[A-Z]+(\d+)_")
|
|
66
|
+
# Only train numbers before "is/are canceled" count, so "Train #1234 replaces
|
|
67
|
+
# canceled train #5678" doesn't flag 1234 and delay notices never match.
|
|
68
|
+
# "canceled to/from/between ..." cancels only part of the run.
|
|
69
|
+
_CANCELLED_RE = re.compile(
|
|
70
|
+
r"\b(?:is|are)\s+cancell?ed\b(?P<partial>\s+(?:to|from|between)\b)?", re.IGNORECASE
|
|
71
|
+
)
|
|
72
|
+
_TRAIN_NUMBER_RE = re.compile(r"#\s*(\d+)")
|
|
73
|
+
|
|
63
74
|
# SEPTA reports "delay unknown" as 998 or 999 minutes.
|
|
64
75
|
_UNKNOWN_DELAYS = {998, 999}
|
|
65
76
|
_DELAY_RE = re.compile(r"(-?\d+)\s*min", re.IGNORECASE)
|
|
@@ -77,12 +88,20 @@ class SeptaClient:
|
|
|
77
88
|
return [alert for feed in feeds for alert in _parse_alerts(feed)]
|
|
78
89
|
|
|
79
90
|
async def async_get_stop_departures(
|
|
80
|
-
self,
|
|
91
|
+
self,
|
|
92
|
+
stop_id: str,
|
|
93
|
+
route_id: str,
|
|
94
|
+
results: int = 20,
|
|
95
|
+
cancelled_trip_ids: Collection[str] = (),
|
|
81
96
|
) -> list[StopDeparture]:
|
|
82
97
|
"""Fetch upcoming departures of one route from a bus, trolley, or subway stop.
|
|
83
98
|
|
|
84
99
|
Times come from the timetable; trips with a live vehicle get its delay.
|
|
85
100
|
SEPTA caps `results` at 20.
|
|
101
|
+
|
|
102
|
+
The timetable includes trips SEPTA has cancelled. Pass the trip IDs of
|
|
103
|
+
`NO_SERVICE` alerts from `async_get_alerts()` as `cancelled_trip_ids` to
|
|
104
|
+
flag them as `cancelled`.
|
|
86
105
|
"""
|
|
87
106
|
schedule, vehicles = await asyncio.gather(
|
|
88
107
|
self._get_json(
|
|
@@ -107,6 +126,7 @@ class SeptaClient:
|
|
|
107
126
|
),
|
|
108
127
|
delay_minutes=vehicle.delay_minutes if vehicle else None,
|
|
109
128
|
vehicle_id=vehicle.vehicle_id if vehicle else None,
|
|
129
|
+
cancelled=row["trip_id"] in cancelled_trip_ids,
|
|
110
130
|
)
|
|
111
131
|
)
|
|
112
132
|
return departures
|
|
@@ -138,12 +158,17 @@ class SeptaClient:
|
|
|
138
158
|
]
|
|
139
159
|
|
|
140
160
|
async def async_get_station_departures(
|
|
141
|
-
self,
|
|
161
|
+
self,
|
|
162
|
+
station: str,
|
|
163
|
+
results: int = 5,
|
|
164
|
+
cancelled_trains: Mapping[str, str | None] | None = None,
|
|
142
165
|
) -> list[TrainDeparture]:
|
|
143
166
|
"""Fetch a Regional Rail station's live departure board, `results` per direction.
|
|
144
167
|
|
|
145
168
|
`station` is a catalog (GTFS) stop name. Station names in the result
|
|
146
169
|
(`origin`, `destination`, `next_station`) are SEPTA's legacy names.
|
|
170
|
+
Pass `cancelled_trains(alerts)` as `cancelled_trains` to flag cancelled
|
|
171
|
+
trains.
|
|
147
172
|
"""
|
|
148
173
|
data = await self._get_json(
|
|
149
174
|
"Arrivals/index.php",
|
|
@@ -175,17 +200,23 @@ class SeptaClient:
|
|
|
175
200
|
track_change=row.get("track_change") or None,
|
|
176
201
|
platform=row.get("platform") or None,
|
|
177
202
|
platform_change=row.get("platform_change") or None,
|
|
203
|
+
**_cancellation(row["train_id"], cancelled_trains or {}),
|
|
178
204
|
)
|
|
179
205
|
for row in rows
|
|
180
206
|
]
|
|
181
207
|
|
|
182
208
|
async def async_get_next_to_arrive(
|
|
183
|
-
self,
|
|
209
|
+
self,
|
|
210
|
+
origin: str,
|
|
211
|
+
destination: str,
|
|
212
|
+
results: int = 5,
|
|
213
|
+
cancelled_trains: Mapping[str, str | None] | None = None,
|
|
184
214
|
) -> list[Trip]:
|
|
185
215
|
"""Fetch the next Regional Rail trips from `origin` to `destination`.
|
|
186
216
|
|
|
187
217
|
Both are catalog (GTFS) stop names; `connection_station` in the result
|
|
188
|
-
is a legacy name.
|
|
218
|
+
is a legacy name. SEPTA lists cancelled trains as on time; pass
|
|
219
|
+
`cancelled_trains(alerts)` as `cancelled_trains` to flag them.
|
|
189
220
|
"""
|
|
190
221
|
data = await self._get_json(
|
|
191
222
|
"NextToArrive/index.php",
|
|
@@ -195,7 +226,8 @@ class SeptaClient:
|
|
|
195
226
|
"req3": results,
|
|
196
227
|
},
|
|
197
228
|
)
|
|
198
|
-
|
|
229
|
+
now = datetime.now(TIMEZONE)
|
|
230
|
+
return [_parse_trip(row, now, cancelled_trains or {}) for row in data]
|
|
199
231
|
|
|
200
232
|
async def _get_json(self, path: str, params: dict[str, Any]) -> Any:
|
|
201
233
|
body = await self._get(f"{API_URL}/{path}", params)
|
|
@@ -258,7 +290,9 @@ def _time_near(value: str, ref: datetime) -> datetime:
|
|
|
258
290
|
return min(candidates, key=lambda c: abs(c - ref))
|
|
259
291
|
|
|
260
292
|
|
|
261
|
-
def _parse_trip(
|
|
293
|
+
def _parse_trip(
|
|
294
|
+
row: dict[str, Any], now: datetime, cancelled_trains: Mapping[str, str | None]
|
|
295
|
+
) -> Trip:
|
|
262
296
|
departs = _time_near(row["orig_departure_time"], now)
|
|
263
297
|
legs = [
|
|
264
298
|
TripLeg(
|
|
@@ -267,6 +301,7 @@ def _parse_trip(row: dict[str, Any], now: datetime) -> Trip:
|
|
|
267
301
|
departs=departs,
|
|
268
302
|
arrives=_time_near(row["orig_arrival_time"], departs),
|
|
269
303
|
delay_minutes=_delay(row.get("orig_delay")),
|
|
304
|
+
**_cancellation(row["orig_train"], cancelled_trains),
|
|
270
305
|
)
|
|
271
306
|
]
|
|
272
307
|
if row.get("term_train"):
|
|
@@ -278,11 +313,56 @@ def _parse_trip(row: dict[str, Any], now: datetime) -> Trip:
|
|
|
278
313
|
departs=term_departs,
|
|
279
314
|
arrives=_time_near(row["term_arrival_time"], term_departs),
|
|
280
315
|
delay_minutes=_delay(row.get("term_delay")),
|
|
316
|
+
**_cancellation(row["term_train"], cancelled_trains),
|
|
281
317
|
)
|
|
282
318
|
)
|
|
283
319
|
return Trip(legs=tuple(legs), connection_station=row.get("Connection") or None)
|
|
284
320
|
|
|
285
321
|
|
|
322
|
+
def _cancellation(train_id: str, cancelled_trains: Mapping[str, str | None]) -> dict[str, Any]:
|
|
323
|
+
if train_id not in cancelled_trains:
|
|
324
|
+
return {"cancelled": False, "cancellation_note": None}
|
|
325
|
+
note = cancelled_trains[train_id]
|
|
326
|
+
return {"cancelled": note is None, "cancellation_note": note}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def cancelled_trains(alerts: Iterable[Alert]) -> dict[str, str | None]:
|
|
330
|
+
"""Regional Rail trains that alerts say are cancelled, by train number (as in `train_id`).
|
|
331
|
+
|
|
332
|
+
The value is None when the whole train is cancelled. When only part of its
|
|
333
|
+
run is ("... is canceled to Suburban Station"), the value is the alert's
|
|
334
|
+
text instead: which stations that covers can't be matched reliably, so the
|
|
335
|
+
rail methods note it rather than flag the train `cancelled` everywhere.
|
|
336
|
+
|
|
337
|
+
SEPTA reports rail cancellations two ways: `NO_SERVICE` alerts naming a GTFS
|
|
338
|
+
trip ID like `LAN3508_20261019_SID189798` (train 3508), and text-only alerts
|
|
339
|
+
like "Inbound train #5319, scheduled to depart ... is canceled ...". Filter
|
|
340
|
+
`alerts` by `is_active()` first so an expired text alert doesn't flag the
|
|
341
|
+
same train number on a later day.
|
|
342
|
+
"""
|
|
343
|
+
trains: dict[str, str | None] = {}
|
|
344
|
+
|
|
345
|
+
def add(train: str, note: str | None) -> None:
|
|
346
|
+
# A whole-train cancellation outranks a partial one for the same train.
|
|
347
|
+
if note is None:
|
|
348
|
+
trains[train] = None
|
|
349
|
+
else:
|
|
350
|
+
trains.setdefault(train, note)
|
|
351
|
+
|
|
352
|
+
for alert in alerts:
|
|
353
|
+
if alert.effect == "NO_SERVICE":
|
|
354
|
+
for trip_id in alert.trip_ids:
|
|
355
|
+
if trip := _RAIL_TRIP_RE.match(trip_id):
|
|
356
|
+
add(trip.group(1), None)
|
|
357
|
+
# shortcut: matches SEPTA's current wording; a rewording silently stops
|
|
358
|
+
# flagging these until _CANCELLED_RE is updated.
|
|
359
|
+
if cancelled := _CANCELLED_RE.search(alert.header):
|
|
360
|
+
note = alert.header if cancelled.group("partial") else None
|
|
361
|
+
for train in _TRAIN_NUMBER_RE.findall(alert.header[: cancelled.start()]):
|
|
362
|
+
add(train, note)
|
|
363
|
+
return trains
|
|
364
|
+
|
|
365
|
+
|
|
286
366
|
def _parse_alerts(body: bytes) -> list[Alert]:
|
|
287
367
|
feed = gtfs_realtime_pb2.FeedMessage()
|
|
288
368
|
try:
|
|
@@ -44,6 +44,10 @@ class StopDeparture:
|
|
|
44
44
|
`delay_minutes` is None when no live vehicle is tracking the trip, which is
|
|
45
45
|
always the case for the Broad Street and Market-Frankford Lines: the time
|
|
46
46
|
is then the timetable, not a prediction.
|
|
47
|
+
|
|
48
|
+
`cancelled` is True when the trip ID was among the `cancelled_trip_ids`
|
|
49
|
+
passed to `async_get_stop_departures()`. The timetable still lists
|
|
50
|
+
cancelled trips, so without that they look like any other scheduled trip.
|
|
47
51
|
"""
|
|
48
52
|
|
|
49
53
|
route_id: str
|
|
@@ -53,6 +57,7 @@ class StopDeparture:
|
|
|
53
57
|
scheduled: datetime
|
|
54
58
|
delay_minutes: int | None
|
|
55
59
|
vehicle_id: str | None
|
|
60
|
+
cancelled: bool = False
|
|
56
61
|
|
|
57
62
|
@property
|
|
58
63
|
def realtime(self) -> bool:
|
|
@@ -94,6 +99,11 @@ class TrainDeparture:
|
|
|
94
99
|
|
|
95
100
|
`direction` is `N` or `S` (SEPTA's through-Center-City convention, not
|
|
96
101
|
inbound/outbound). `status` is SEPTA's raw text, e.g. `On Time`, `5 min`.
|
|
102
|
+
|
|
103
|
+
`cancelled` and `cancellation_note` come from the `cancelled_trains` passed
|
|
104
|
+
to `async_get_station_departures()`; SEPTA's board doesn't say. A train
|
|
105
|
+
cancelled for only part of its run isn't `cancelled`; `cancellation_note`
|
|
106
|
+
carries the alert text instead.
|
|
97
107
|
"""
|
|
98
108
|
|
|
99
109
|
train_id: str
|
|
@@ -111,17 +121,27 @@ class TrainDeparture:
|
|
|
111
121
|
track_change: str | None
|
|
112
122
|
platform: str | None
|
|
113
123
|
platform_change: str | None
|
|
124
|
+
cancelled: bool = False
|
|
125
|
+
cancellation_note: str | None = None
|
|
114
126
|
|
|
115
127
|
|
|
116
128
|
@dataclass(frozen=True)
|
|
117
129
|
class TripLeg:
|
|
118
|
-
"""One train in a NextToArrive trip.
|
|
130
|
+
"""One train in a NextToArrive trip.
|
|
131
|
+
|
|
132
|
+
`cancelled` and `cancellation_note` come from the `cancelled_trains` passed
|
|
133
|
+
to `async_get_next_to_arrive()`; SEPTA lists cancelled trains as on time.
|
|
134
|
+
A train cancelled for only part of its run isn't `cancelled`;
|
|
135
|
+
`cancellation_note` carries the alert text instead.
|
|
136
|
+
"""
|
|
119
137
|
|
|
120
138
|
train_id: str
|
|
121
139
|
line: str
|
|
122
140
|
departs: datetime
|
|
123
141
|
arrives: datetime
|
|
124
142
|
delay_minutes: int | None
|
|
143
|
+
cancelled: bool = False
|
|
144
|
+
cancellation_note: str | None = None
|
|
125
145
|
|
|
126
146
|
|
|
127
147
|
@dataclass(frozen=True)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: septa-api
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python API client for SEPTA real-time data, alerts, and schedules
|
|
5
5
|
Author: zackwag
|
|
6
6
|
License: MIT
|
|
@@ -44,11 +44,20 @@ async def main():
|
|
|
44
44
|
async with aiohttp.ClientSession() as session:
|
|
45
45
|
client = SeptaClient(session)
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
alerts = await client.async_get_alerts()
|
|
48
|
+
cancelled = {t for a in alerts if a.effect == "NO_SERVICE" for t in a.trip_ids}
|
|
49
|
+
|
|
50
|
+
departures = await client.async_get_stop_departures(
|
|
51
|
+
stop_id, route.id, results=3, cancelled_trip_ids=cancelled
|
|
52
|
+
)
|
|
53
|
+
for departure in departures:
|
|
54
|
+
if departure.cancelled:
|
|
55
|
+
label = "cancelled"
|
|
56
|
+
else:
|
|
57
|
+
label = "live" if departure.realtime else "scheduled"
|
|
49
58
|
print(f"{catalog.stops[stop_id]}: {departure.expected:%H:%M} ({label})")
|
|
50
59
|
|
|
51
|
-
for alert in
|
|
60
|
+
for alert in alerts:
|
|
52
61
|
if route.id in alert.route_ids:
|
|
53
62
|
print(f"{alert.severity}: {alert.header}")
|
|
54
63
|
|
|
@@ -88,24 +97,42 @@ Takes an `aiohttp.ClientSession`, which the caller owns.
|
|
|
88
97
|
|
|
89
98
|
Every active and upcoming `Alert` across all modes. Route-level alerts list `route_ids` and apply to both directions. Trip cancellations list only `trip_ids`, which match `StopDeparture.trip_id`. Use `alert.is_active(now)` to filter by the alert's active periods.
|
|
90
99
|
|
|
91
|
-
### `await client.async_get_stop_departures(stop_id, route_id, results=20)`
|
|
100
|
+
### `await client.async_get_stop_departures(stop_id, route_id, results=20, cancelled_trip_ids=())`
|
|
92
101
|
|
|
93
102
|
Upcoming `StopDeparture`s of one route from a bus, trolley, or subway stop, from the timetable. When a live vehicle is running the trip, `delay_minutes` and `vehicle_id` are filled in and `realtime` is `True`; `expected` is the scheduled time plus the delay. SEPTA caps `results` at 20.
|
|
94
103
|
|
|
104
|
+
The timetable still lists trips SEPTA has cancelled. Pass the `trip_ids` of `NO_SERVICE` alerts as `cancelled_trip_ids` and those departures come back with `cancelled` set to `True`, so they don't pass for a bus that's coming. Taking the IDs from the caller avoids fetching the alert feeds again for every stop.
|
|
105
|
+
|
|
95
106
|
### `await client.async_get_vehicles(route_id)`
|
|
96
107
|
|
|
97
108
|
Live `Vehicle` positions on a bus or trolley route. `direction` matches the catalog's direction names case-insensitively. Empty for subway lines.
|
|
98
109
|
|
|
99
|
-
### `await client.async_get_station_departures(station, results=5)`
|
|
110
|
+
### `await client.async_get_station_departures(station, results=5, cancelled_trains=None)`
|
|
100
111
|
|
|
101
112
|
A Regional Rail station's live departure board, as `TrainDeparture`s, `results` per direction. `direction` is `N` or `S` (SEPTA's through-Center-City convention), not inbound/outbound.
|
|
102
113
|
|
|
103
|
-
### `await client.async_get_next_to_arrive(origin, destination, results=5)`
|
|
114
|
+
### `await client.async_get_next_to_arrive(origin, destination, results=5, cancelled_trains=None)`
|
|
104
115
|
|
|
105
116
|
The next Regional Rail `Trip`s between two stations, each with one or two `TripLeg`s and the `connection_station` if there's a transfer.
|
|
106
117
|
|
|
107
118
|
Station arguments are catalog stop names; the client translates them to the legacy names SEPTA's JSON API expects. Station names in the results (`origin`, `connection_station`, ...) are SEPTA's legacy names.
|
|
108
119
|
|
|
120
|
+
### `cancelled_trains(alerts)`
|
|
121
|
+
|
|
122
|
+
SEPTA lists cancelled Regional Rail trains as on time. This maps the train numbers that alerts say are cancelled to `None` (the whole train) or the alert's text (part of its run). Pass it as `cancelled_trains` to either rail method: wholly cancelled `TrainDeparture`s and `TripLeg`s come back with `cancelled` set to `True`, partly cancelled ones with `cancelled` left `False` and the alert text in `cancellation_note`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
now = datetime.now(TIMEZONE)
|
|
126
|
+
alerts = [a for a in await client.async_get_alerts() if a.is_active(now)]
|
|
127
|
+
trips = await client.async_get_next_to_arrive(
|
|
128
|
+
"Doylestown", "Suburban Station", cancelled_trains=cancelled_trains(alerts)
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Filter by `is_active()` first: train numbers repeat daily, so an expired alert would otherwise flag the same train on a later day.
|
|
133
|
+
|
|
134
|
+
Rail cancellations come either as structured trip alerts or only as alert text ("Inbound train #5319 ... is canceled ..."), and the text match follows SEPTA's current wording. Partial cancellations aren't flagged because the same train really does run on the rest of its route: on 2026-11-30, train 5319 "canceled to Suburban Station" skipped Doylestown to Suburban but ran on to Wawa, so flagging it would have been wrong at Media and Wawa. Show `cancellation_note` so riders at the affected stations still see the warning.
|
|
135
|
+
|
|
109
136
|
### Exceptions
|
|
110
137
|
|
|
111
138
|
- `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
|
|
@@ -10,10 +10,12 @@ from google.transit import gtfs_realtime_pb2
|
|
|
10
10
|
|
|
11
11
|
from septa_api import (
|
|
12
12
|
TIMEZONE,
|
|
13
|
+
Alert,
|
|
13
14
|
SeptaClient,
|
|
14
15
|
SeptaConnectionError,
|
|
15
16
|
SeptaError,
|
|
16
17
|
SeptaRequestError,
|
|
18
|
+
cancelled_trains,
|
|
17
19
|
)
|
|
18
20
|
from septa_api.client import ALERT_FEED_URLS, _parse_trip, _time_near
|
|
19
21
|
|
|
@@ -111,6 +113,19 @@ class TestStationDepartures:
|
|
|
111
113
|
"results": 3,
|
|
112
114
|
}
|
|
113
115
|
|
|
116
|
+
async def test_flags_cancelled_trains(self, session):
|
|
117
|
+
session.add(
|
|
118
|
+
"Arrivals/index.php",
|
|
119
|
+
{"Doylestown Departures: ...": [{"Southbound": [_train(train_id="5319"), _train()]}]},
|
|
120
|
+
)
|
|
121
|
+
departures = await SeptaClient(session).async_get_station_departures(
|
|
122
|
+
"Doylestown", cancelled_trains={"5319": None, "5780": "Canceled to Suburban Station"}
|
|
123
|
+
)
|
|
124
|
+
assert [(d.train_id, d.cancelled, d.cancellation_note) for d in departures] == [
|
|
125
|
+
("5319", True, None),
|
|
126
|
+
("5780", False, "Canceled to Suburban Station"),
|
|
127
|
+
]
|
|
128
|
+
|
|
114
129
|
async def test_empty_board(self, session):
|
|
115
130
|
session.add("Arrivals/index.php", {"Wayne Departures: ...": [{"Northbound": []}, {}]})
|
|
116
131
|
assert await SeptaClient(session).async_get_station_departures("Wayne") == []
|
|
@@ -137,7 +152,9 @@ class TestNextToArrive:
|
|
|
137
152
|
}
|
|
138
153
|
],
|
|
139
154
|
)
|
|
140
|
-
trips = await SeptaClient(session).async_get_next_to_arrive(
|
|
155
|
+
trips = await SeptaClient(session).async_get_next_to_arrive(
|
|
156
|
+
"Doylestown", "Wayne", cancelled_trains={"9719": None}
|
|
157
|
+
)
|
|
141
158
|
|
|
142
159
|
assert session.params_for("NextToArrive/index.php") == {
|
|
143
160
|
"req1": "Doylestown",
|
|
@@ -146,9 +163,9 @@ class TestNextToArrive:
|
|
|
146
163
|
}
|
|
147
164
|
(trip,) = trips
|
|
148
165
|
assert trip.connection_station == "Suburban Station"
|
|
149
|
-
assert [(leg.train_id, leg.delay_minutes) for leg in trip.legs] == [
|
|
150
|
-
("6583", 0),
|
|
151
|
-
("9719", 3),
|
|
166
|
+
assert [(leg.train_id, leg.delay_minutes, leg.cancelled) for leg in trip.legs] == [
|
|
167
|
+
("6583", 0, False),
|
|
168
|
+
("9719", 3, True),
|
|
152
169
|
]
|
|
153
170
|
assert trip.legs[1].departs.time().isoformat() == "08:40:00"
|
|
154
171
|
|
|
@@ -161,7 +178,7 @@ class TestNextToArrive:
|
|
|
161
178
|
"orig_delay": "999 mins",
|
|
162
179
|
"isdirect": "true",
|
|
163
180
|
}
|
|
164
|
-
(leg,) = _parse_trip(row, _at(2026, 11, 30, 23, 40)).legs
|
|
181
|
+
(leg,) = _parse_trip(row, _at(2026, 11, 30, 23, 40), {}).legs
|
|
165
182
|
assert leg.departs == _at(2026, 11, 30, 23, 50)
|
|
166
183
|
assert leg.arrives == _at(2026, 12, 1, 0, 20)
|
|
167
184
|
assert leg.delay_minutes is None
|
|
@@ -179,6 +196,66 @@ class TestNextToArrive:
|
|
|
179
196
|
assert _time_near(text, ref) == expected
|
|
180
197
|
|
|
181
198
|
|
|
199
|
+
def _rail_alert(header: str, effect: str = "UNKNOWN_EFFECT", trip_ids=()) -> Alert:
|
|
200
|
+
return Alert(
|
|
201
|
+
id="1",
|
|
202
|
+
route_ids=frozenset() if trip_ids else frozenset({"LAN"}),
|
|
203
|
+
trip_ids=frozenset(trip_ids),
|
|
204
|
+
cause="OTHER_CAUSE",
|
|
205
|
+
effect=effect,
|
|
206
|
+
severity="SEVERE",
|
|
207
|
+
header=header,
|
|
208
|
+
description=header,
|
|
209
|
+
url=None,
|
|
210
|
+
active_periods=(),
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class TestCancelledTrainIds:
|
|
215
|
+
def test_real_alert_wording(self):
|
|
216
|
+
alerts = [
|
|
217
|
+
# Structured cancellation from the rail GTFS-RT feed.
|
|
218
|
+
_rail_alert(
|
|
219
|
+
"Trip cancellation for trip LAN3508_20261019_SID189798.",
|
|
220
|
+
effect="NO_SERVICE",
|
|
221
|
+
trip_ids={"LAN3508_20261019_SID189798"},
|
|
222
|
+
),
|
|
223
|
+
# Text-only cancellation; the "a.m." must not cut the sentence short.
|
|
224
|
+
_rail_alert(
|
|
225
|
+
"Inbound train #5319, scheduled to depart Doylestown Station at 9:17 a.m., "
|
|
226
|
+
"is canceled to Suburban Station due to earlier mechanical issues."
|
|
227
|
+
),
|
|
228
|
+
# Mentions a train but isn't a cancellation.
|
|
229
|
+
_rail_alert(
|
|
230
|
+
"Outbound train #2512 is experiencing delays of up to 20 minutes due to "
|
|
231
|
+
"earlier mechanical issues."
|
|
232
|
+
),
|
|
233
|
+
_rail_alert("Outbound Platform Boarding, Train #207, Norristown Transit Center"),
|
|
234
|
+
# Bus trip cancellations use numeric trip IDs and aren't trains.
|
|
235
|
+
_rail_alert("Trip cancellation for trip 870680.", "NO_SERVICE", {"870680"}),
|
|
236
|
+
]
|
|
237
|
+
assert cancelled_trains(alerts) == {
|
|
238
|
+
"3508": None,
|
|
239
|
+
# Only cancelled up to Suburban Station; it runs on to Wawa.
|
|
240
|
+
"5319": "Inbound train #5319, scheduled to depart Doylestown Station at 9:17 a.m., is canceled to Suburban Station due to earlier mechanical issues.",
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
def test_only_trains_before_cancelled_count(self):
|
|
244
|
+
alerts = [
|
|
245
|
+
_rail_alert("Trains #1234 and #5678 are cancelled due to a crew shortage."),
|
|
246
|
+
_rail_alert("Train #4321 is canceled and will be replaced by train #8765."),
|
|
247
|
+
]
|
|
248
|
+
assert cancelled_trains(alerts) == {"1234": None, "5678": None, "4321": None}
|
|
249
|
+
|
|
250
|
+
@pytest.mark.parametrize("order", [1, -1])
|
|
251
|
+
def test_whole_train_outranks_partial(self, order):
|
|
252
|
+
alerts = [
|
|
253
|
+
_rail_alert("Train #5319 is canceled between Lansdale and Suburban Station."),
|
|
254
|
+
_rail_alert("Train #5319 is canceled due to a crew shortage."),
|
|
255
|
+
][::order]
|
|
256
|
+
assert cancelled_trains(alerts) == {"5319": None}
|
|
257
|
+
|
|
258
|
+
|
|
182
259
|
class TestStopDepartures:
|
|
183
260
|
async def test_overlays_live_delay_by_trip(self, session):
|
|
184
261
|
session.add(
|
|
@@ -204,6 +281,30 @@ class TestStopDepartures:
|
|
|
204
281
|
assert departures[1].expected == _at(2026, 11, 30, 8, 10)
|
|
205
282
|
assert departures[0].direction_id == 1
|
|
206
283
|
|
|
284
|
+
async def test_flags_cancelled_trips(self, session):
|
|
285
|
+
session.add(
|
|
286
|
+
"BusSchedules/index.php",
|
|
287
|
+
{
|
|
288
|
+
"17": [
|
|
289
|
+
_scheduled("870680", "11/30/26 07:58 am"),
|
|
290
|
+
_scheduled("993241", "11/30/26 08:10 am"),
|
|
291
|
+
]
|
|
292
|
+
},
|
|
293
|
+
)
|
|
294
|
+
session.add("TransitView/index.php", [])
|
|
295
|
+
client = SeptaClient(session)
|
|
296
|
+
|
|
297
|
+
flagged = await client.async_get_stop_departures(
|
|
298
|
+
"17842", "17", cancelled_trip_ids={"870680", "unrelated"}
|
|
299
|
+
)
|
|
300
|
+
unflagged = await client.async_get_stop_departures("17842", "17")
|
|
301
|
+
|
|
302
|
+
assert [(d.trip_id, d.cancelled, d.realtime) for d in flagged] == [
|
|
303
|
+
("870680", True, False),
|
|
304
|
+
("993241", False, False),
|
|
305
|
+
]
|
|
306
|
+
assert not any(d.cancelled for d in unflagged)
|
|
307
|
+
|
|
207
308
|
async def test_subway_is_timetable_only(self, session):
|
|
208
309
|
session.add(
|
|
209
310
|
"BusSchedules/index.php", {"L1": [_scheduled("979962", "11/30/26 07:59 am", "L1")]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|