amunition 0.1.0__py3-none-any.whl

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.
amunition/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ import os
2
+ from dotenv import load_dotenv, dotenv_values
3
+ from pathlib import Path
4
+ from importlib.metadata import version, PackageNotFoundError
5
+
6
+ CONFIG = f"{Path.home()}/.amunition"
7
+ try:
8
+ VERSION = version("amunition")
9
+ except PackageNotFoundError:
10
+ VERSION = "dev"
11
+
12
+ load_dotenv(CONFIG)
13
+ api_key = os.getenv("KEY_511")
14
+
15
+ if not api_key:
16
+ print("KEY_511 not found in ~/.amunition, please set it using 'key <your-key>'.")
amunition/api.py ADDED
@@ -0,0 +1,152 @@
1
+ import gzip
2
+ import json
3
+ import requests
4
+ from rapidfuzz import fuzz, process
5
+ from datetime import datetime, timezone
6
+ from . import api_key
7
+ from .types import *
8
+
9
+
10
+ def get_operator_list() -> dict[str, str]:
11
+ operators_url: str = "http://api.511.org/transit/operators"
12
+ operators_raw = requests.get(operators_url, params={"api_key": api_key}, timeout=10)
13
+ operators_raw.raise_for_status()
14
+
15
+ ret = dict()
16
+ operators = operators_raw.content
17
+
18
+ if operators.startswith(b"\x1f\x8b"):
19
+ operators = gzip.decompress(operators)
20
+ operators = json.loads(operators.decode("utf-8-sig"))
21
+ for op in operators:
22
+ if op.get("Name").startswith("511") or op.get("Name").startswith("Regional"):
23
+ pass
24
+ else:
25
+ ret.update({ op.get("PrivateCode"): op.get("ShortName") or op.get("Name")})
26
+ return ret
27
+ def get_operator_routes(private_code: str) -> TransitList:
28
+ routes_url: str = "http://api.511.org/transit/lines"
29
+ routes_raw = requests.get(routes_url, params={"api_key": api_key, "operator_id": private_code}, timeout=10)
30
+ routes_raw.raise_for_status()
31
+
32
+ ret: TransitList = []
33
+ routes = routes_raw.content
34
+
35
+ if routes.startswith(b"\x1f\x8b"):
36
+ routes = gzip.decompress(routes)
37
+ routes = json.loads(routes.decode("utf-8-sig"))
38
+ for ro in routes:
39
+ ret.append([ro.get("Id"), ro.get("Name"), ro.get("TransportMode"), private_code])
40
+ return ret
41
+ def get_operator_stops(private_code: str) -> TransitList:
42
+ stops_url: str = "http://api.511.org/transit/stops"
43
+ stops_raw = requests.get(stops_url, params={"api_key": api_key, "Operator_id": private_code}, timeout=10)
44
+
45
+ ret: TransitList = []
46
+ stops = stops_raw.content
47
+
48
+ if stops.startswith(b"\x1f\x8b"):
49
+ stops = gzip.decompress(stops)
50
+
51
+ data = json.loads(stops.decode("utf-8-sig"))
52
+
53
+ points = (
54
+ data.get("Contents", {})
55
+ .get("dataObjects", {})
56
+ .get("ScheduledStopPoint", [])
57
+ )
58
+
59
+ for stop in points:
60
+ ret.append([stop["id"], stop["Name"], private_code])
61
+
62
+ return ret
63
+
64
+ def get_next_bus(stop_id: str, private_code: str) -> TransitList:
65
+ stop_url: str = "http://api.511.org/transit/StopMonitoring"
66
+ stop_raw = requests.get(stop_url, params={"api_key": api_key, "agency": private_code, "stopCode": stop_id}, timeout=10)
67
+ stop_raw.raise_for_status()
68
+
69
+ ret: list[list[str]] = []
70
+ stop = stop_raw.content
71
+
72
+ if stop.startswith(b"\x1f\x8b"):
73
+ stop = gzip.decompress(stop)
74
+ stop = json.loads(stop.decode("utf-8-sig"))
75
+ visits = (
76
+ stop.get("ServiceDelivery", {})
77
+ .get("StopMonitoringDelivery", {})
78
+ .get("MonitoredStopVisit", {})
79
+ )
80
+ for st in visits[:5]:
81
+ journey = st.get("MonitoredVehicleJourney", {})
82
+ call = journey.get("MonitoredCall", {})
83
+ expected_departure_min = ( bus_time_to_minutes(call.get("AimedDepartureTime"))
84
+ or bus_time_to_minutes(call.get("ExpectedDepartureTime")
85
+ or bus_time_to_minutes(call.get("AimedArrivalTime"))
86
+ or bus_time_to_minutes(call.get("AimedDepartureTime")))
87
+ or "Unknown"
88
+ )
89
+ ret.append([
90
+ str(stop_id),
91
+ call.get("StopPointName").removeprefix("Metro "),
92
+ str(expected_departure_min),
93
+ journey.get("LineRef"),
94
+ journey.get("PublishedLineName"),
95
+ journey.get("DestinationDisplay") or journey.get("DestinationName")
96
+ ])
97
+ return ret
98
+
99
+ def get_route_stops(line_id: str, private_code: str) -> TransitList:
100
+ stops_url: str = "http://api.511.org/transit/stops"
101
+ stops_raw = requests.get(stops_url, params={"api_key": api_key, "Operator_id": private_code, "Line_id": line_id}, timeout=10)
102
+
103
+ ret: TransitList = []
104
+ stops = stops_raw.content
105
+
106
+ if stops.startswith(b"\x1f\x8b"):
107
+ stops = gzip.decompress(stops)
108
+
109
+ data = json.loads(stops.decode("utf-8-sig"))
110
+ points = (
111
+ data.get("Contents", {})
112
+ .get("dataObjects", {})
113
+ .get("ScheduledStopPoint", [])
114
+ )
115
+
116
+ for stop in points:
117
+ ret.append([stop["id"], stop["Name"], private_code])
118
+
119
+ return ret
120
+
121
+ def bus_time_to_minutes(dep_time: str) -> str:
122
+ cur_dt: datetime = datetime.now(timezone.utc)
123
+ dep_dt: datetime = datetime.fromisoformat(dep_time)
124
+ mins: int = int((dep_dt - cur_dt).total_seconds() // 60)
125
+ if mins < 0:
126
+ return "has [bold cyan]Departed[/]"
127
+ elif mins > 1 or mins == 0:
128
+ ret = str(f"in {mins} minutes")
129
+ else:
130
+ ret = str(f"in {mins} minute")
131
+
132
+ return ret
133
+
134
+ def query(db: TransitList, query: str, max_r: int = 50) -> TransitList:
135
+ ret: TransitList = []
136
+ if not query.strip():
137
+ ret.append(["No", "Query"])
138
+ else:
139
+ searchable: dict[str, str] = {s[0]: f"{s[0]} {s[1]}" for s in db}
140
+ lookup: dict[str, list[str]] = {s[0]: s for s in db}
141
+
142
+ matches = process.extract(
143
+ query,
144
+ searchable,
145
+ scorer=fuzz.WRatio,
146
+ limit=max_r,
147
+ score_cutoff=70,
148
+ )
149
+ ret = [lookup[stop_id] for _, _, stop_id in matches]
150
+ if not ret:
151
+ ret.append(["No", "Results"])
152
+ return ret
amunition/types.py ADDED
@@ -0,0 +1 @@
1
+ type TransitList = list[list[str]]
amunition/ui.py ADDED
@@ -0,0 +1,251 @@
1
+ import sys
2
+ import shlex
3
+ from rich import print
4
+ from rich.console import Console
5
+ from . import *
6
+ from .api import *
7
+
8
+ MUNI_METRO: dict[str, str] = {
9
+ "J": "bold bright_white on #c85a00",
10
+ "K": "bold bright_white on #2b7296",
11
+ "L": "bold bright_white on #8d188f",
12
+ "M": "bold bright_white on #007748",
13
+ "N": "bold bright_white on #1e4a7e",
14
+ "T": "bold bright_white on #d50f41",
15
+ "F": "bold bright_white on #e17b10",
16
+ "E": "bold bright_white on #e17b10"
17
+ }
18
+
19
+ help_doc: str = """[white]A([red]muni[/])tion commands:
20
+ [cyan]help[/]: prints this message
21
+ [cyan]exit[/]: exits A([red]muni[/])tion
22
+ [cyan]quit[/]: same as exit
23
+ [cyan]get[/] <op> <routes/stops>: gets that agencies routes/stops
24
+ [cyan]line-get[/] <op> <line number> <stops/name/mode>: gets the info of the line queried
25
+ [cyan]stop-get[/] <op> <stop number>: gets the info of the line queried
26
+ [cyan]search-stops[/] <op> <query>: gets the stops tied to the query
27
+ [cyan]operators[/]: lists valid operators
28
+ [cyan]pager/less/more[/]: turns on pager for next command only
29
+ [cyan]about[/]: credits
30
+ [cyan]search-lines[/] <op> <query>: searches for the route number tied to that query
31
+ [cyan]key[/] <your-key>: sets your 511 key"""
32
+
33
+ welcome: str = f"""[white]Welcome to A([red]muni[/])tion ({VERSION})!
34
+ (Type '[cyan]help[/]' to see commands, '[cyan]about[/]' for credits)"""
35
+
36
+ about: str = f"""[white]A[/]([red]muni[/])tion is powered by 511.org data, and is not affiliated with the SFMTA, MTC, or any other transit authority.
37
+ (c) 2026 goldcoin10 (LICENSE is available at https://raw.githubusercontent.com/goldcoin10/amunition/refs/heads/master/LICENSE)
38
+ (you are on version {VERSION})
39
+ """
40
+
41
+ console = Console()
42
+
43
+ def sh_511(pager: bool = False) -> None:
44
+ if pager:
45
+ raw = input("pager> ").strip()
46
+ else:
47
+ raw = input("> ").strip()
48
+ if raw == "":
49
+ sh_511()
50
+ else:
51
+ term_arr: list[str] = shlex.split(raw)
52
+ if term_arr[0] == "pager" or term_arr[0] == "less" or term_arr[0] == "more":
53
+ sh_511(True)
54
+ else:
55
+ result = check_command(term_arr)
56
+ if pager == False:
57
+ print(result)
58
+ else:
59
+ with console.pager():
60
+ console.print(result)
61
+
62
+
63
+ def check_command(command: list[str]) -> str:
64
+ len_com: int = len(command)
65
+ ret: str = ""
66
+
67
+ if command[0] == "help":
68
+ return help_doc
69
+ elif command[0] == "exit" or command[0] == "quit":
70
+ sys.exit(0)
71
+ elif command[0] == "operators":
72
+ for id, name in get_operator_list().items():
73
+ ret = f"{ret}\n{id} {name}"
74
+ elif command[0] == "about":
75
+ return about
76
+ elif command[0] == "get":
77
+ if len_com < 2:
78
+ return "too few arguments"
79
+ elif not api_key:
80
+ return "invalid api key"
81
+
82
+ if command[1].upper() in get_operator_list():
83
+ operator_id = command[1].upper()
84
+ operator_name = get_operator_list()[command[1].upper()]
85
+ else:
86
+ return "operator not found"
87
+
88
+ if len_com < 3:
89
+ return operator_name
90
+ elif command[2] == "routes":
91
+ for line_num, line_nom, line_frm, line_prv in get_operator_routes(operator_id):
92
+ ret = f"{ret}\n{line_num} {line_nom}"
93
+ elif command[2] == "stops":
94
+ for stop_num, stop_nom, stop_prv in get_operator_stops(operator_id):
95
+ ret = f"{ret}\n{stop_num} {stop_nom}"
96
+ else:
97
+ ret = "wrong syntax"
98
+ elif command[0] == "line-get":
99
+ if len_com < 4:
100
+ return "too few arguments"
101
+ elif not api_key:
102
+ return "invalid api key"
103
+
104
+ operator_id = command[1].upper()
105
+ if operator_id not in get_operator_list():
106
+ return "operator not found"
107
+
108
+ operator_routes = get_operator_routes(operator_id)
109
+ line_id = command[2]
110
+ valid_lines = {num.upper(): num for num, _, _, _ in operator_routes}
111
+ if line_id.upper() not in valid_lines:
112
+ return "line not found"
113
+
114
+ canonical_line_id = valid_lines[line_id.upper()]
115
+
116
+ if command[3].strip().lower() == "stops":
117
+ stop_data = get_route_stops(canonical_line_id, operator_id)
118
+ for stop_num, stop_nom, _ in stop_data:
119
+ ret = f"{ret}\n{stop_num} {stop_nom}"
120
+ elif command[3].strip().lower() == "name":
121
+ for num, nom, _, _ in operator_routes:
122
+ if canonical_line_id == num:
123
+ ret = nom
124
+ elif command[3].strip().lower() == "mode":
125
+ for num, _, mode, _ in operator_routes:
126
+ if canonical_line_id == num:
127
+ ret = mode
128
+ else:
129
+ return "wrong syntax"
130
+ elif command[0] == "stop-get":
131
+ if len_com < 3:
132
+ return "too few arguments"
133
+ elif not api_key:
134
+ return "invalid api key"
135
+
136
+ operator_id = command[1].upper()
137
+ if operator_id not in get_operator_list():
138
+ return "operator not found"
139
+
140
+ operator_stops = get_operator_stops(operator_id)
141
+ stop_id = command[2]
142
+ valid_stops = {num.upper(): (num, nom) for num, nom, _ in operator_stops}
143
+ if stop_id.upper() not in valid_stops:
144
+ return "stop not found"
145
+
146
+ canonical_stop_id, stop_nom = valid_stops[stop_id.upper()]
147
+ ret = f"\n{ret}\n{display_sign(canonical_stop_id, operator_id)}"
148
+
149
+ if not ret.strip():
150
+ ret = f"\n{stop_nom} ({canonical_stop_id})\n\nNo upcoming departures."
151
+ else:
152
+ ret = f"\n{stop_nom} ({canonical_stop_id}){ret}"
153
+
154
+ elif command[0] == "search-stops":
155
+ if len_com < 3:
156
+ return "too few arguments"
157
+ elif not api_key:
158
+ return "invalid api key"
159
+
160
+ operator_id = command[1].upper()
161
+ if operator_id not in get_operator_list():
162
+ return "operator not found"
163
+
164
+ search: str = " ".join(command[2:])
165
+
166
+ stops = query(get_operator_stops(operator_id), search, 5)
167
+
168
+ for stop_id, stop_name, *_ in stops:
169
+ ret = f"{ret}\n{stop_id} {stop_name}"
170
+
171
+ elif command[0] == "search-lines":
172
+ if len_com < 3:
173
+ return "too few arguments"
174
+ elif not api_key:
175
+ return "invalid api key"
176
+
177
+ operator_id = command[1].upper()
178
+ if operator_id not in get_operator_list():
179
+ return "operator not found"
180
+
181
+ search = " ".join(command[2:])
182
+ if operator_id == "SF":
183
+
184
+ # fuck you muni
185
+
186
+ lines = query(get_operator_routes(operator_id), search.upper(), 5)
187
+ else:
188
+ lines = query(get_operator_routes(operator_id), search, 5)
189
+
190
+ for line_id, line_name, _, _ in lines:
191
+ ret = f"{ret}\n{line_id} {line_name}"
192
+ elif command[0] == "key":
193
+ if len_com < 2:
194
+ if api_key:
195
+ return f"your api key is {api_key}"
196
+ else:
197
+ return "no api key found"
198
+ try:
199
+ operators_raw = requests.get("http://api.511.org/transit/operators", params={"api_key": command[1]}, timeout=10)
200
+ operators_raw.raise_for_status()
201
+ except Exception:
202
+ return "an error occured"
203
+ else:
204
+ with open(CONFIG, "w") as file:
205
+ file.write(f"KEY_511={command[1]}\n")
206
+ os.chmod(CONFIG, 0o600)
207
+ print("key has been changed successfully, exiting")
208
+ sys.exit(0)
209
+ else:
210
+ return "wrong syntax"
211
+ return ret
212
+
213
+ def cls() -> None:
214
+ print("\033c", end="", flush=True) # stupid ass hack
215
+
216
+ def display_sign(stop_id: str, private_code: str) -> str:
217
+ nb_list = get_next_bus(stop_id, private_code)
218
+ line_color: str = "cyan bold"
219
+ ret: str = ""
220
+ for stop_num, stop_name, next_time, line_num, line_name, terminus in nb_list:
221
+ if private_code == "SF":
222
+ line_color = MUNI_METRO.get(line_num, "cyan bold")
223
+ ret = f"{ret}\n[{line_color}]{line_num}[/] [yellow]{line_name}[/] to [green]{terminus}[/] {next_time}"
224
+ return ret
225
+
226
+ def debug():
227
+ print("---DEBUG---")
228
+ ro_list = get_operator_routes("BA")
229
+ for route_id, name, mode, _ in ro_list:
230
+ if mode == "OP":
231
+ print(name)
232
+ else:
233
+ print(f"{route_id} {name}: {mode}")
234
+ op_list = get_operator_list()
235
+ print("OPERATORS")
236
+ print(op_list)
237
+ print("STOP 15781 (MUNI)")
238
+ nb_list = get_next_bus("15781", "SF")
239
+ print(nb_list)
240
+ print("L TARAVAL")
241
+ st_list = get_route_stops("L", "SF")
242
+ for stop_id, stop_name, operator in st_list:
243
+ print(stop_id, stop_name)
244
+ def main() -> None:
245
+ #routes: list[Route] = get_operator_routes("BA")
246
+ #for route in routes:
247
+ # print(str(route))
248
+ #debug()
249
+ print(welcome)
250
+ while True:
251
+ sh_511()
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.3
2
+ Name: amunition
3
+ Version: 0.1.0
4
+ Summary: a(muni)tion is a transit app running on the bay's 511 api
5
+ Author: goldcoin10
6
+ Author-email: goldcoin10 <vwebaccount@protonmail.com>
7
+ Requires-Dist: python-dotenv>=1.2.4
8
+ Requires-Dist: pythondialog>=3.5.3
9
+ Requires-Dist: rapidfuzz>=3.14.6
10
+ Requires-Dist: requests>=2.34.2
11
+ Requires-Dist: rich>=15.0.0
12
+ Requires-Python: >=3.13
13
+ Description-Content-Type: text/markdown
14
+
15
+ # A(muni)tion
16
+
17
+ predict buses from your terminal with ease
18
+
19
+ ## Introduction
20
+
21
+ A(muni)tion is a transit app running on the bay's* 511 API. With it, you can easily determine when the next bus will arrive at the stop of your choosing. You can also search
22
+ for lines and operators.
23
+
24
+ ## Installation
25
+
26
+ To begin using A(muni)tion, you will have to download it via PyPI. For this example, I will be using `uv`.
27
+
28
+ `uv tool install amunition`
29
+
30
+ After this, you will have to get an API key from [511](https://511.org/open-data/token). (this will take a few days)
31
+
32
+ At first run, A(muni)tion will say `KEY_511 not found in ~/.amunition, please set it using 'key <your-key>'.`
33
+
34
+ To fix this, type `> key <your-valid-key>`. If the key is valid, it will exit and you will have to start A(muni)tion again.
35
+
36
+ ## Footnotes
37
+
38
+ A(muni)tion is NOT affiliated with the MTC, 511, SFMTA, or any other transit agency.
39
+ (c) 2026 goldcoin10
40
+
41
+ *not chesapeake ffs
@@ -0,0 +1,8 @@
1
+ amunition/__init__.py,sha256=mb4hE-CKYcfYvBiOanE4fr48mZYj3W9ffouEDTGdYMg,425
2
+ amunition/api.py,sha256=5qBaXz9wfoSQ0fXkGdxrUN3nIpZdpk0GRKFriWgWKs0,5153
3
+ amunition/types.py,sha256=ZhlmIxK-8X_bvDyemGodCeYAuPLyrNHaS5TKqISTfck,34
4
+ amunition/ui.py,sha256=dp77-9y_0BYwbqiWSjjLzZi1LoF-jQcWJo_70GfCP4M,8824
5
+ amunition-0.1.0.dist-info/WHEEL,sha256=si2p8vW03RnhyBnhWl4tj-ObJa78SpE-c9HsEtblGR0,80
6
+ amunition-0.1.0.dist-info/entry_points.txt,sha256=1tvmLP-zrWcSzIj1BQA1ugcjStOG0JC7rgt8LoUaQ5M,49
7
+ amunition-0.1.0.dist-info/METADATA,sha256=I8nctYLbcyDz6vRoQ45wztvrtA7p4Q2bqH7qiHB_CaY,1345
8
+ amunition-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.5
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ amunition = amunition.ui:main
3
+