septa-api 0.1.0__tar.gz → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: septa-api
3
- Version: 0.1.0
3
+ Version: 0.3.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
- for departure in await client.async_get_stop_departures(stop_id, route.id, results=3):
48
- label = "live" if departure.realtime else "scheduled"
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 await client.async_get_alerts():
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,44 @@ 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
+
136
+ The text match is tested against SEPTA's published wording from 2020 through 2026. An alert that names a train and mentions a cancellation in wording it doesn't recognize is logged as a warning (once per alert) rather than silently ignored; `unmatched_cancellations(alerts)` returns those alerts directly.
137
+
109
138
  ### Exceptions
110
139
 
111
140
  - `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
- for departure in await client.async_get_stop_departures(stop_id, route.id, results=3):
33
- label = "live" if departure.realtime else "scheduled"
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 await client.async_get_alerts():
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,44 @@ 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
+
121
+ The text match is tested against SEPTA's published wording from 2020 through 2026. An alert that names a train and mentions a cancellation in wording it doesn't recognize is logged as a warning (once per alert) rather than silently ignored; `unmatched_cancellations(alerts)` returns those alerts directly.
122
+
94
123
  ### Exceptions
95
124
 
96
125
  - `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "septa-api"
7
- version = "0.1.0"
7
+ version = "0.3.0"
8
8
  description = "Python API client for SEPTA real-time data, alerts, and schedules"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -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, unmatched_cancellations
5
5
  from .exceptions import SeptaConnectionError, SeptaError, SeptaRequestError
6
6
  from .models import Alert, StopDeparture, TrainDeparture, Trip, TripLeg, Vehicle
7
7
 
@@ -20,5 +20,7 @@ __all__ = [
20
20
  "Trip",
21
21
  "TripLeg",
22
22
  "Vehicle",
23
+ "cancelled_trains",
23
24
  "load_catalog",
25
+ "unmatched_cancellations",
24
26
  ]
@@ -4,7 +4,9 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import json
7
+ import logging
7
8
  import re
9
+ from collections.abc import Collection, Iterable, Mapping
8
10
  from datetime import datetime, timedelta
9
11
  from typing import Any
10
12
  from zoneinfo import ZoneInfo
@@ -16,6 +18,8 @@ from google.transit import gtfs_realtime_pb2
16
18
  from .exceptions import SeptaConnectionError, SeptaError, SeptaRequestError
17
19
  from .models import Alert, StopDeparture, TrainDeparture, Trip, TripLeg, Vehicle
18
20
 
21
+ _LOGGER = logging.getLogger(__name__)
22
+
19
23
  API_URL = "https://www3.septa.org/api"
20
24
  ALERT_FEED_URLS = (
21
25
  "https://www3.septa.org/gtfsrt/septa-pa-us/Service/rtServiceAlerts.pb",
@@ -60,6 +64,20 @@ _STATION_NAMES = {
60
64
  # Arrivals takes "Wayne" but not "Wayne Station"; NextToArrive is the reverse.
61
65
  _NEXT_TO_ARRIVE_NAMES = {**_STATION_NAMES, "Wayne": "Wayne Station"}
62
66
 
67
+ # Rail GTFS trip IDs embed the train number after the route: LAN3508_20261019_...
68
+ _RAIL_TRIP_RE = re.compile(r"^[A-Z]+(\d+)_")
69
+ # Only train numbers before "is/are canceled" count, so "Train #1234 replaces
70
+ # canceled train #5678" doesn't flag 1234 and delay notices never match.
71
+ # "canceled to/from/between ..." cancels only part of the run.
72
+ _CANCELLED_RE = re.compile(
73
+ r"\b(?:is|are)\s+cancell?ed\b(?P<partial>\s+(?:to|from|between)\b)?", re.IGNORECASE
74
+ )
75
+ # Train numbers are 3-4 digits; "on track #5" must not read as a train.
76
+ _TRAIN_NUMBER_RE = re.compile(r"#\s*(\d{3,4})\b")
77
+ _MENTIONS_CANCEL_RE = re.compile(r"cancel", re.IGNORECASE)
78
+ # Alert IDs already warned about, so a poll loop logs each one once.
79
+ _WARNED_ALERT_IDS: set[str] = set()
80
+
63
81
  # SEPTA reports "delay unknown" as 998 or 999 minutes.
64
82
  _UNKNOWN_DELAYS = {998, 999}
65
83
  _DELAY_RE = re.compile(r"(-?\d+)\s*min", re.IGNORECASE)
@@ -77,12 +95,20 @@ class SeptaClient:
77
95
  return [alert for feed in feeds for alert in _parse_alerts(feed)]
78
96
 
79
97
  async def async_get_stop_departures(
80
- self, stop_id: str, route_id: str, results: int = 20
98
+ self,
99
+ stop_id: str,
100
+ route_id: str,
101
+ results: int = 20,
102
+ cancelled_trip_ids: Collection[str] = (),
81
103
  ) -> list[StopDeparture]:
82
104
  """Fetch upcoming departures of one route from a bus, trolley, or subway stop.
83
105
 
84
106
  Times come from the timetable; trips with a live vehicle get its delay.
85
107
  SEPTA caps `results` at 20.
108
+
109
+ The timetable includes trips SEPTA has cancelled. Pass the trip IDs of
110
+ `NO_SERVICE` alerts from `async_get_alerts()` as `cancelled_trip_ids` to
111
+ flag them as `cancelled`.
86
112
  """
87
113
  schedule, vehicles = await asyncio.gather(
88
114
  self._get_json(
@@ -107,6 +133,7 @@ class SeptaClient:
107
133
  ),
108
134
  delay_minutes=vehicle.delay_minutes if vehicle else None,
109
135
  vehicle_id=vehicle.vehicle_id if vehicle else None,
136
+ cancelled=row["trip_id"] in cancelled_trip_ids,
110
137
  )
111
138
  )
112
139
  return departures
@@ -138,12 +165,17 @@ class SeptaClient:
138
165
  ]
139
166
 
140
167
  async def async_get_station_departures(
141
- self, station: str, results: int = 5
168
+ self,
169
+ station: str,
170
+ results: int = 5,
171
+ cancelled_trains: Mapping[str, str | None] | None = None,
142
172
  ) -> list[TrainDeparture]:
143
173
  """Fetch a Regional Rail station's live departure board, `results` per direction.
144
174
 
145
175
  `station` is a catalog (GTFS) stop name. Station names in the result
146
176
  (`origin`, `destination`, `next_station`) are SEPTA's legacy names.
177
+ Pass `cancelled_trains(alerts)` as `cancelled_trains` to flag cancelled
178
+ trains.
147
179
  """
148
180
  data = await self._get_json(
149
181
  "Arrivals/index.php",
@@ -175,17 +207,23 @@ class SeptaClient:
175
207
  track_change=row.get("track_change") or None,
176
208
  platform=row.get("platform") or None,
177
209
  platform_change=row.get("platform_change") or None,
210
+ **_cancellation(row["train_id"], cancelled_trains or {}),
178
211
  )
179
212
  for row in rows
180
213
  ]
181
214
 
182
215
  async def async_get_next_to_arrive(
183
- self, origin: str, destination: str, results: int = 5
216
+ self,
217
+ origin: str,
218
+ destination: str,
219
+ results: int = 5,
220
+ cancelled_trains: Mapping[str, str | None] | None = None,
184
221
  ) -> list[Trip]:
185
222
  """Fetch the next Regional Rail trips from `origin` to `destination`.
186
223
 
187
224
  Both are catalog (GTFS) stop names; `connection_station` in the result
188
- is a legacy name.
225
+ is a legacy name. SEPTA lists cancelled trains as on time; pass
226
+ `cancelled_trains(alerts)` as `cancelled_trains` to flag them.
189
227
  """
190
228
  data = await self._get_json(
191
229
  "NextToArrive/index.php",
@@ -195,7 +233,8 @@ class SeptaClient:
195
233
  "req3": results,
196
234
  },
197
235
  )
198
- return [_parse_trip(row, datetime.now(TIMEZONE)) for row in data]
236
+ now = datetime.now(TIMEZONE)
237
+ return [_parse_trip(row, now, cancelled_trains or {}) for row in data]
199
238
 
200
239
  async def _get_json(self, path: str, params: dict[str, Any]) -> Any:
201
240
  body = await self._get(f"{API_URL}/{path}", params)
@@ -258,7 +297,9 @@ def _time_near(value: str, ref: datetime) -> datetime:
258
297
  return min(candidates, key=lambda c: abs(c - ref))
259
298
 
260
299
 
261
- def _parse_trip(row: dict[str, Any], now: datetime) -> Trip:
300
+ def _parse_trip(
301
+ row: dict[str, Any], now: datetime, cancelled_trains: Mapping[str, str | None]
302
+ ) -> Trip:
262
303
  departs = _time_near(row["orig_departure_time"], now)
263
304
  legs = [
264
305
  TripLeg(
@@ -267,6 +308,7 @@ def _parse_trip(row: dict[str, Any], now: datetime) -> Trip:
267
308
  departs=departs,
268
309
  arrives=_time_near(row["orig_arrival_time"], departs),
269
310
  delay_minutes=_delay(row.get("orig_delay")),
311
+ **_cancellation(row["orig_train"], cancelled_trains),
270
312
  )
271
313
  ]
272
314
  if row.get("term_train"):
@@ -278,11 +320,88 @@ def _parse_trip(row: dict[str, Any], now: datetime) -> Trip:
278
320
  departs=term_departs,
279
321
  arrives=_time_near(row["term_arrival_time"], term_departs),
280
322
  delay_minutes=_delay(row.get("term_delay")),
323
+ **_cancellation(row["term_train"], cancelled_trains),
281
324
  )
282
325
  )
283
326
  return Trip(legs=tuple(legs), connection_station=row.get("Connection") or None)
284
327
 
285
328
 
329
+ def _cancellation(train_id: str, cancelled_trains: Mapping[str, str | None]) -> dict[str, Any]:
330
+ if train_id not in cancelled_trains:
331
+ return {"cancelled": False, "cancellation_note": None}
332
+ note = cancelled_trains[train_id]
333
+ return {"cancelled": note is None, "cancellation_note": note}
334
+
335
+
336
+ def cancelled_trains(alerts: Iterable[Alert]) -> dict[str, str | None]:
337
+ """Regional Rail trains that alerts say are cancelled, by train number (as in `train_id`).
338
+
339
+ The value is None when the whole train is cancelled. When only part of its
340
+ run is ("... is canceled to Suburban Station"), the value is the alert's
341
+ text instead: which stations that covers can't be matched reliably, so the
342
+ rail methods note it rather than flag the train `cancelled` everywhere.
343
+
344
+ SEPTA reports rail cancellations two ways: `NO_SERVICE` alerts naming a GTFS
345
+ trip ID like `LAN3508_20261019_SID189798` (train 3508), and text-only alerts
346
+ like "Inbound train #5319, scheduled to depart ... is canceled ...". Filter
347
+ `alerts` by `is_active()` first so an expired text alert doesn't flag the
348
+ same train number on a later day.
349
+
350
+ The text match follows SEPTA's known wording. An alert that names a train
351
+ and mentions a cancellation but doesn't match is logged as a warning (once
352
+ per alert) instead of being silently ignored; see unmatched_cancellations().
353
+ """
354
+ alerts = list(alerts) # read twice below; a generator would be empty the second time
355
+ trains: dict[str, str | None] = {}
356
+
357
+ def add(train: str, note: str | None) -> None:
358
+ # A whole-train cancellation outranks a partial one for the same train.
359
+ if note is None:
360
+ trains[train] = None
361
+ else:
362
+ trains.setdefault(train, note)
363
+
364
+ for alert in alerts:
365
+ if alert.effect == "NO_SERVICE":
366
+ for trip_id in alert.trip_ids:
367
+ if trip := _RAIL_TRIP_RE.match(trip_id):
368
+ add(trip.group(1), None)
369
+ if cancelled := _CANCELLED_RE.search(alert.header):
370
+ note = alert.header if cancelled.group("partial") else None
371
+ for train in _TRAIN_NUMBER_RE.findall(alert.header[: cancelled.start()]):
372
+ add(train, note)
373
+ for alert in unmatched_cancellations(alerts):
374
+ if alert.id not in _WARNED_ALERT_IDS:
375
+ _WARNED_ALERT_IDS.add(alert.id)
376
+ _LOGGER.warning(
377
+ "Rail alert %s looks like a train cancellation in wording septa-api "
378
+ "doesn't recognize, so it isn't flagged: %s",
379
+ alert.id,
380
+ alert.header,
381
+ )
382
+ return trains
383
+
384
+
385
+ def unmatched_cancellations(alerts: Iterable[Alert]) -> list[Alert]:
386
+ """Alerts that name a train and mention a cancellation, but in unrecognized wording.
387
+
388
+ These are what `cancelled_trains()` can't read: a sign SEPTA changed how it
389
+ words cancellations. Not every one is a missed cancellation ("Train #1234
390
+ replaces canceled train #5678" correctly flags nothing), but each deserves a
391
+ look and a test case.
392
+ """
393
+ return [
394
+ alert
395
+ for alert in alerts
396
+ if _MENTIONS_CANCEL_RE.search(alert.header)
397
+ and _TRAIN_NUMBER_RE.search(alert.header)
398
+ and not (
399
+ (cancelled := _CANCELLED_RE.search(alert.header))
400
+ and _TRAIN_NUMBER_RE.search(alert.header[: cancelled.start()])
401
+ )
402
+ ]
403
+
404
+
286
405
  def _parse_alerts(body: bytes) -> list[Alert]:
287
406
  feed = gtfs_realtime_pb2.FeedMessage()
288
407
  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.1.0
3
+ Version: 0.3.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
- for departure in await client.async_get_stop_departures(stop_id, route.id, results=3):
48
- label = "live" if departure.realtime else "scheduled"
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 await client.async_get_alerts():
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,44 @@ 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
+
136
+ The text match is tested against SEPTA's published wording from 2020 through 2026. An alert that names a train and mentions a cancellation in wording it doesn't recognize is logged as a warning (once per alert) rather than silently ignored; `unmatched_cancellations(alerts)` returns those alerts directly.
137
+
109
138
  ### Exceptions
110
139
 
111
140
  - `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
@@ -10,11 +10,15 @@ 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,
19
+ unmatched_cancellations,
17
20
  )
21
+ from septa_api import client as client_module
18
22
  from septa_api.client import ALERT_FEED_URLS, _parse_trip, _time_near
19
23
 
20
24
 
@@ -111,6 +115,19 @@ class TestStationDepartures:
111
115
  "results": 3,
112
116
  }
113
117
 
118
+ async def test_flags_cancelled_trains(self, session):
119
+ session.add(
120
+ "Arrivals/index.php",
121
+ {"Doylestown Departures: ...": [{"Southbound": [_train(train_id="5319"), _train()]}]},
122
+ )
123
+ departures = await SeptaClient(session).async_get_station_departures(
124
+ "Doylestown", cancelled_trains={"5319": None, "5780": "Canceled to Suburban Station"}
125
+ )
126
+ assert [(d.train_id, d.cancelled, d.cancellation_note) for d in departures] == [
127
+ ("5319", True, None),
128
+ ("5780", False, "Canceled to Suburban Station"),
129
+ ]
130
+
114
131
  async def test_empty_board(self, session):
115
132
  session.add("Arrivals/index.php", {"Wayne Departures: ...": [{"Northbound": []}, {}]})
116
133
  assert await SeptaClient(session).async_get_station_departures("Wayne") == []
@@ -137,7 +154,9 @@ class TestNextToArrive:
137
154
  }
138
155
  ],
139
156
  )
140
- trips = await SeptaClient(session).async_get_next_to_arrive("Doylestown", "Wayne")
157
+ trips = await SeptaClient(session).async_get_next_to_arrive(
158
+ "Doylestown", "Wayne", cancelled_trains={"9719": None}
159
+ )
141
160
 
142
161
  assert session.params_for("NextToArrive/index.php") == {
143
162
  "req1": "Doylestown",
@@ -146,9 +165,9 @@ class TestNextToArrive:
146
165
  }
147
166
  (trip,) = trips
148
167
  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),
168
+ assert [(leg.train_id, leg.delay_minutes, leg.cancelled) for leg in trip.legs] == [
169
+ ("6583", 0, False),
170
+ ("9719", 3, True),
152
171
  ]
153
172
  assert trip.legs[1].departs.time().isoformat() == "08:40:00"
154
173
 
@@ -161,7 +180,7 @@ class TestNextToArrive:
161
180
  "orig_delay": "999 mins",
162
181
  "isdirect": "true",
163
182
  }
164
- (leg,) = _parse_trip(row, _at(2026, 11, 30, 23, 40)).legs
183
+ (leg,) = _parse_trip(row, _at(2026, 11, 30, 23, 40), {}).legs
165
184
  assert leg.departs == _at(2026, 11, 30, 23, 50)
166
185
  assert leg.arrives == _at(2026, 12, 1, 0, 20)
167
186
  assert leg.delay_minutes is None
@@ -179,6 +198,122 @@ class TestNextToArrive:
179
198
  assert _time_near(text, ref) == expected
180
199
 
181
200
 
201
+ def _rail_alert(
202
+ header: str, effect: str = "UNKNOWN_EFFECT", trip_ids=(), alert_id: str = "1"
203
+ ) -> Alert:
204
+ return Alert(
205
+ id=alert_id,
206
+ route_ids=frozenset() if trip_ids else frozenset({"LAN"}),
207
+ trip_ids=frozenset(trip_ids),
208
+ cause="OTHER_CAUSE",
209
+ effect=effect,
210
+ severity="SEVERE",
211
+ header=header,
212
+ description=header,
213
+ url=None,
214
+ active_periods=(),
215
+ )
216
+
217
+
218
+ _PARTIAL = "partial" # expected value: the alert's own header
219
+
220
+ # Real SEPTA Regional Rail wording, with where and when it was published.
221
+ # Add every new wording the alert-wording check turns up here.
222
+ _RAIL_WORDING = [
223
+ # Rail GTFS-RT feed, 2026-11-30. The "a.m." must not cut the match short.
224
+ (
225
+ (
226
+ "Inbound train #5319, scheduled to depart Doylestown Station at 9:17 a.m., "
227
+ "is canceled to Suburban Station due to earlier mechanical issues."
228
+ ),
229
+ {"5319": _PARTIAL},
230
+ ),
231
+ (
232
+ (
233
+ "Outbound train #2512 is experiencing delays of up to 20 minutes due to "
234
+ "earlier mechanical issues."
235
+ ),
236
+ {},
237
+ ),
238
+ ("Outbound Platform Boarding, Train #207, Norristown Transit Center", {}),
239
+ # SEPTA on X, quoted by NBC Philadelphia, 2025-11-13.
240
+ (
241
+ (
242
+ "Airport: Inbound train #402, scheduled to depart the Airport at 5:07 a.m., "
243
+ "is canceled due to earlier signal issues."
244
+ ),
245
+ {"402": None},
246
+ ),
247
+ # SEPTA's cancellations as listed by Fox29, 2020-03-16.
248
+ ("Inbound train #344, scheduled to depart Elwyn at 8:31 a.m., is canceled.", {"344": None}),
249
+ ("Train #2301 scheduled to leave Elm Street at 6:49 AM, is canceled.", {"2301": None}),
250
+ (
251
+ (
252
+ "Train #516 scheduled to leave Suburban Station at 6:30 AM, train #511 scheduled "
253
+ "to leave Doylestown at 6:30 AM, train #515 scheduled to leave Lansdale at 7:44 AM, "
254
+ "are canceled."
255
+ ),
256
+ {"516": None, "511": None, "515": None},
257
+ ),
258
+ # Not a cancellation, and "#5" is a track, not a train.
259
+ ("Outbound train #515 will originate from Suburban Station on track #5.", {}),
260
+ ]
261
+
262
+
263
+ class TestCancelledTrains:
264
+ @pytest.mark.parametrize(("header", "expected"), _RAIL_WORDING)
265
+ def test_real_wording(self, header, expected):
266
+ alerts = [_rail_alert(header)]
267
+ assert cancelled_trains(alerts) == {
268
+ train: header if note == _PARTIAL else note for train, note in expected.items()
269
+ }
270
+ assert unmatched_cancellations(alerts) == []
271
+
272
+ def test_structured_trip_alerts(self):
273
+ alerts = [
274
+ _rail_alert(
275
+ "Trip cancellation for trip LAN3508_20261019_SID189798.",
276
+ effect="NO_SERVICE",
277
+ trip_ids={"LAN3508_20261019_SID189798"},
278
+ ),
279
+ # Bus trip cancellations use numeric trip IDs and aren't trains.
280
+ _rail_alert("Trip cancellation for trip 870680.", "NO_SERVICE", {"870680"}),
281
+ ]
282
+ assert cancelled_trains(alerts) == {"3508": None}
283
+
284
+ def test_only_trains_before_cancelled_count(self):
285
+ alerts = [
286
+ _rail_alert("Trains #1234 and #5678 are cancelled due to a crew shortage."),
287
+ _rail_alert("Train #4321 on track #5 is canceled and will be replaced by train #8765."),
288
+ ]
289
+ assert cancelled_trains(iter(alerts)) == {"1234": None, "5678": None, "4321": None}
290
+
291
+ @pytest.mark.parametrize("order", [1, -1])
292
+ def test_whole_train_outranks_partial(self, order):
293
+ alerts = [
294
+ _rail_alert("Train #5319 is canceled between Lansdale and Suburban Station."),
295
+ _rail_alert("Train #5319 is canceled due to a crew shortage."),
296
+ ][::order]
297
+ assert cancelled_trains(alerts) == {"5319": None}
298
+
299
+ def test_unrecognized_wording_is_warned_once(self, monkeypatch, caplog):
300
+ monkeypatch.setattr(client_module, "_WARNED_ALERT_IDS", set())
301
+ reworded = _rail_alert("Train #1234 has been canceled.", alert_id="139500")
302
+ unrelated = _rail_alert("Train #1234 is operating 10 minutes late.", alert_id="139501")
303
+
304
+ assert unmatched_cancellations([reworded, unrelated]) == [reworded]
305
+ assert cancelled_trains([reworded, unrelated]) == {}
306
+ cancelled_trains([reworded, unrelated])
307
+
308
+ warnings = [r for r in caplog.records if r.levelname == "WARNING"]
309
+ assert [r.getMessage() for r in warnings] == [
310
+ (
311
+ "Rail alert 139500 looks like a train cancellation in wording septa-api "
312
+ "doesn't recognize, so it isn't flagged: Train #1234 has been canceled."
313
+ )
314
+ ]
315
+
316
+
182
317
  class TestStopDepartures:
183
318
  async def test_overlays_live_delay_by_trip(self, session):
184
319
  session.add(
@@ -204,6 +339,30 @@ class TestStopDepartures:
204
339
  assert departures[1].expected == _at(2026, 11, 30, 8, 10)
205
340
  assert departures[0].direction_id == 1
206
341
 
342
+ async def test_flags_cancelled_trips(self, session):
343
+ session.add(
344
+ "BusSchedules/index.php",
345
+ {
346
+ "17": [
347
+ _scheduled("870680", "11/30/26 07:58 am"),
348
+ _scheduled("993241", "11/30/26 08:10 am"),
349
+ ]
350
+ },
351
+ )
352
+ session.add("TransitView/index.php", [])
353
+ client = SeptaClient(session)
354
+
355
+ flagged = await client.async_get_stop_departures(
356
+ "17842", "17", cancelled_trip_ids={"870680", "unrelated"}
357
+ )
358
+ unflagged = await client.async_get_stop_departures("17842", "17")
359
+
360
+ assert [(d.trip_id, d.cancelled, d.realtime) for d in flagged] == [
361
+ ("870680", True, False),
362
+ ("993241", False, False),
363
+ ]
364
+ assert not any(d.cancelled for d in unflagged)
365
+
207
366
  async def test_subway_is_timetable_only(self, session):
208
367
  session.add(
209
368
  "BusSchedules/index.php", {"L1": [_scheduled("979962", "11/30/26 07:59 am", "L1")]}
File without changes
File without changes
File without changes