forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfare_table.py
More file actions
126 lines (105 loc) · 4.28 KB
/
Copy pathfare_table.py
File metadata and controls
126 lines (105 loc) · 4.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Structured fare table: the agency's GTFS-Fares feed as the source of truth
for fare *numbers*.
The hardest, most rider-dangerous failure this project has is a misread fare —
a real number read from the wrong row of a prose table (ground-024,
conv-forged-002). ADR 0016 showed that catching that with a prose heuristic is
infeasible (15:1+ false positives). The durable fix is architectural: stop
having the model read fare amounts out of prose at all, and take them from the
machine-readable GTFS-Fares feed the agency already publishes, where an amount
is bound to a typed rider category (`standard` $2.50, `reduced` $1.25, `free`
$0.00), not a table cell the model has to parse.
This module turns the snapshotted feed (`assistant.gtfs.parse_fares`) into a
typed, queryable `StructuredFare` list plus a rider-category lookup, and renders
an authoritative fare card. Step one of "numbers from typed data" (ADR 0017);
wiring the card into the answer prompt and a structured consistency check are
the next increments.
python -m assistant.fare_table SBMTD # print the agency's authoritative fares
"""
from __future__ import annotations
import sys
from dataclasses import dataclass
from decimal import Decimal
from assistant import gtfs
@dataclass(frozen=True)
class RiderCategory:
id: str
name: str
eligibility_url: str | None
@dataclass(frozen=True)
class StructuredFare:
agency: str
product: str
amount: Decimal
rider_category: RiderCategory | None
@property
def category_label(self) -> str:
return self.rider_category.name if self.rider_category else "All riders"
def load_rider_categories(agency: str) -> dict[str, RiderCategory]:
"""Rider categories declared in a v2 feed (`rider_categories.txt`), keyed by
id. Empty for a v1 feed or an agency with no snapshot — the fares then carry
no typed category, which callers handle as `None`."""
try:
path = gtfs.feed_snapshot_directory(agency) / "rider_categories.txt"
except FileNotFoundError:
return {}
if not path.exists():
return {}
out: dict[str, RiderCategory] = {}
for row in gtfs._read_csv(path):
cid = row.get("rider_category_id")
if not cid:
continue
out[cid] = RiderCategory(
id=cid,
name=(row.get("rider_category_name") or cid).strip(),
eligibility_url=(row.get("eligibility_url") or "").strip() or None,
)
return out
def structured_fares(agency: str) -> list[StructuredFare]:
"""Every fare in the agency's feed as a typed row, with its rider category
resolved to a label. Empty when the agency has no snapshotted feed."""
categories = load_rider_categories(agency)
fares: list[StructuredFare] = []
for feed in gtfs.parse_fares(agency):
fares.append(
StructuredFare(
agency=feed.agency,
product=feed.name,
amount=feed.amount,
rider_category=categories.get(feed.rider_category or ""),
)
)
return fares
def render_fare_card(agency: str) -> str:
"""The authoritative fare list for the agency, sourced from the feed — the
block a future increment injects into the answer prompt so the model states
numbers it did not have to parse from a table. Empty string when there is no
feed, so the caller falls back to today's prose-only behavior."""
fares = structured_fares(agency)
if not fares:
return ""
lines = [f"Authoritative fares for {agency} (from the agency's GTFS-Fares feed):"]
for fare in fares:
lines.append(f" - {fare.product} [{fare.category_label}]: ${fare.amount:.2f}")
urls = sorted(
{
f.rider_category.eligibility_url
for f in fares
if f.rider_category and f.rider_category.eligibility_url
}
)
for url in urls:
lines.append(f" Eligibility: {url}")
return "\n".join(lines)
def main() -> int:
if len(sys.argv) < 2:
print("usage: python -m assistant.fare_table <AGENCY>", file=sys.stderr)
return 2
card = render_fare_card(sys.argv[1])
if not card:
print(f"no GTFS-Fares snapshot for {sys.argv[1]}", file=sys.stderr)
return 1
print(card)
return 0
if __name__ == "__main__":
sys.exit(main())