septa-api 0.2.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.2.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
@@ -133,6 +133,8 @@ Filter by `is_active()` first: train numbers repeat daily, so an expired alert w
133
133
 
134
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
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
+
136
138
  ### Exceptions
137
139
 
138
140
  - `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
@@ -118,6 +118,8 @@ Filter by `is_active()` first: train numbers repeat daily, so an expired alert w
118
118
 
119
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
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
+
121
123
  ### Exceptions
122
124
 
123
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.2.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, cancelled_trains
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
 
@@ -22,4 +22,5 @@ __all__ = [
22
22
  "Vehicle",
23
23
  "cancelled_trains",
24
24
  "load_catalog",
25
+ "unmatched_cancellations",
25
26
  ]
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  import json
7
+ import logging
7
8
  import re
8
9
  from collections.abc import Collection, Iterable, Mapping
9
10
  from datetime import datetime, timedelta
@@ -17,6 +18,8 @@ from google.transit import gtfs_realtime_pb2
17
18
  from .exceptions import SeptaConnectionError, SeptaError, SeptaRequestError
18
19
  from .models import Alert, StopDeparture, TrainDeparture, Trip, TripLeg, Vehicle
19
20
 
21
+ _LOGGER = logging.getLogger(__name__)
22
+
20
23
  API_URL = "https://www3.septa.org/api"
21
24
  ALERT_FEED_URLS = (
22
25
  "https://www3.septa.org/gtfsrt/septa-pa-us/Service/rtServiceAlerts.pb",
@@ -69,7 +72,11 @@ _RAIL_TRIP_RE = re.compile(r"^[A-Z]+(\d+)_")
69
72
  _CANCELLED_RE = re.compile(
70
73
  r"\b(?:is|are)\s+cancell?ed\b(?P<partial>\s+(?:to|from|between)\b)?", re.IGNORECASE
71
74
  )
72
- _TRAIN_NUMBER_RE = re.compile(r"#\s*(\d+)")
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()
73
80
 
74
81
  # SEPTA reports "delay unknown" as 998 or 999 minutes.
75
82
  _UNKNOWN_DELAYS = {998, 999}
@@ -339,7 +346,12 @@ def cancelled_trains(alerts: Iterable[Alert]) -> dict[str, str | None]:
339
346
  like "Inbound train #5319, scheduled to depart ... is canceled ...". Filter
340
347
  `alerts` by `is_active()` first so an expired text alert doesn't flag the
341
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().
342
353
  """
354
+ alerts = list(alerts) # read twice below; a generator would be empty the second time
343
355
  trains: dict[str, str | None] = {}
344
356
 
345
357
  def add(train: str, note: str | None) -> None:
@@ -354,15 +366,42 @@ def cancelled_trains(alerts: Iterable[Alert]) -> dict[str, str | None]:
354
366
  for trip_id in alert.trip_ids:
355
367
  if trip := _RAIL_TRIP_RE.match(trip_id):
356
368
  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
369
  if cancelled := _CANCELLED_RE.search(alert.header):
360
370
  note = alert.header if cancelled.group("partial") else None
361
371
  for train in _TRAIN_NUMBER_RE.findall(alert.header[: cancelled.start()]):
362
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
+ )
363
382
  return trains
364
383
 
365
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
+
366
405
  def _parse_alerts(body: bytes) -> list[Alert]:
367
406
  feed = gtfs_realtime_pb2.FeedMessage()
368
407
  try:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: septa-api
3
- Version: 0.2.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
@@ -133,6 +133,8 @@ Filter by `is_active()` first: train numbers repeat daily, so an expired alert w
133
133
 
134
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
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
+
136
138
  ### Exceptions
137
139
 
138
140
  - `SeptaRequestError`: SEPTA rejected the request, e.g. an unknown station or stop.
@@ -16,7 +16,9 @@ from septa_api import (
16
16
  SeptaError,
17
17
  SeptaRequestError,
18
18
  cancelled_trains,
19
+ unmatched_cancellations,
19
20
  )
21
+ from septa_api import client as client_module
20
22
  from septa_api.client import ALERT_FEED_URLS, _parse_trip, _time_near
21
23
 
22
24
 
@@ -196,9 +198,11 @@ class TestNextToArrive:
196
198
  assert _time_near(text, ref) == expected
197
199
 
198
200
 
199
- def _rail_alert(header: str, effect: str = "UNKNOWN_EFFECT", trip_ids=()) -> Alert:
201
+ def _rail_alert(
202
+ header: str, effect: str = "UNKNOWN_EFFECT", trip_ids=(), alert_id: str = "1"
203
+ ) -> Alert:
200
204
  return Alert(
201
- id="1",
205
+ id=alert_id,
202
206
  route_ids=frozenset() if trip_ids else frozenset({"LAN"}),
203
207
  trip_ids=frozenset(trip_ids),
204
208
  cause="OTHER_CAUSE",
@@ -211,41 +215,78 @@ def _rail_alert(header: str, effect: str = "UNKNOWN_EFFECT", trip_ids=()) -> Ale
211
215
  )
212
216
 
213
217
 
214
- class TestCancelledTrainIds:
215
- def test_real_alert_wording(self):
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):
216
273
  alerts = [
217
- # Structured cancellation from the rail GTFS-RT feed.
218
274
  _rail_alert(
219
275
  "Trip cancellation for trip LAN3508_20261019_SID189798.",
220
276
  effect="NO_SERVICE",
221
277
  trip_ids={"LAN3508_20261019_SID189798"},
222
278
  ),
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
279
  # Bus trip cancellations use numeric trip IDs and aren't trains.
235
280
  _rail_alert("Trip cancellation for trip 870680.", "NO_SERVICE", {"870680"}),
236
281
  ]
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
- }
282
+ assert cancelled_trains(alerts) == {"3508": None}
242
283
 
243
284
  def test_only_trains_before_cancelled_count(self):
244
285
  alerts = [
245
286
  _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."),
287
+ _rail_alert("Train #4321 on track #5 is canceled and will be replaced by train #8765."),
247
288
  ]
248
- assert cancelled_trains(alerts) == {"1234": None, "5678": None, "4321": None}
289
+ assert cancelled_trains(iter(alerts)) == {"1234": None, "5678": None, "4321": None}
249
290
 
250
291
  @pytest.mark.parametrize("order", [1, -1])
251
292
  def test_whole_train_outranks_partial(self, order):
@@ -255,6 +296,23 @@ class TestCancelledTrainIds:
255
296
  ][::order]
256
297
  assert cancelled_trains(alerts) == {"5319": None}
257
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
+
258
316
 
259
317
  class TestStopDepartures:
260
318
  async def test_overlays_live_delay_by_trip(self, session):
File without changes
File without changes
File without changes
File without changes