aportee 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.
- aportee/__init__.py +11 -0
- aportee/cli.py +534 -0
- aportee/client.py +675 -0
- aportee/format.py +149 -0
- aportee/py.typed +0 -0
- aportee-0.1.0.dist-info/METADATA +160 -0
- aportee-0.1.0.dist-info/RECORD +10 -0
- aportee-0.1.0.dist-info/WHEEL +4 -0
- aportee-0.1.0.dist-info/entry_points.txt +3 -0
- aportee-0.1.0.dist-info/licenses/LICENSE +21 -0
aportee/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Python client and command-line tool for the à portée access API: walk, bike and transit.
|
|
2
|
+
|
|
3
|
+
Example:
|
|
4
|
+
>>> from aportee import Client
|
|
5
|
+
>>> Client().access((43.25085, -79.81809), types=["grocery"])["minutes"]["grocery"]
|
|
6
|
+
{'value': 6, 'reason': 'ok'}
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from aportee.client import ApiError, Client, LoginError, to_frame
|
|
10
|
+
|
|
11
|
+
__all__ = ["ApiError", "Client", "LoginError", "to_frame"]
|
aportee/cli.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"""The ``aportee`` command: one subcommand per API call, with exit codes an agent can branch on.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 ok, 2 bad input, 3 no data, 4 outside coverage, 5 rate limited, 1 anything else.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import csv
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import socket
|
|
14
|
+
import sys
|
|
15
|
+
import urllib.error
|
|
16
|
+
from collections.abc import Callable, Sequence
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from aportee import format as fmt
|
|
20
|
+
from aportee.client import (
|
|
21
|
+
ApiError,
|
|
22
|
+
Client,
|
|
23
|
+
LoginError,
|
|
24
|
+
Markers,
|
|
25
|
+
Point,
|
|
26
|
+
checked,
|
|
27
|
+
login_prompt,
|
|
28
|
+
open_link,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
MAP_PARAMS = ("zoom", "types", "theme", "lang", "w", "h")
|
|
32
|
+
EMBED_PARAMS = (*MAP_PARAMS, "dots")
|
|
33
|
+
CENSUS_ID_DIGITS = {"canale": 8, "sam": 11}
|
|
34
|
+
|
|
35
|
+
DESCRIPTION = "The à portée access API from the command line: walking, cycling and transit."
|
|
36
|
+
EPILOG = """\
|
|
37
|
+
exit codes: 0 ok · 2 bad input · 3 no data · 4 outside coverage · 5 rate limited · 1 error
|
|
38
|
+
|
|
39
|
+
examples:
|
|
40
|
+
aportee login
|
|
41
|
+
aportee access 43.25085 -79.81809 --include all
|
|
42
|
+
aportee access 45.5017 -73.5673 --mode transit --types grocery,pharmacy
|
|
43
|
+
aportee find "Fickle Fig" --near 48.43,-123.37
|
|
44
|
+
aportee routes 43.25085 -79.81809 --types grocery,school
|
|
45
|
+
aportee image --place Hamilton --out hamilton.png
|
|
46
|
+
aportee image 53.5465 -113.555 --zoom 15 --markers-file permits.csv --out permits.png
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class UsageError(Exception):
|
|
51
|
+
"""The arguments parsed but don't describe a request; exits 2."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def exit_code(status: int) -> int:
|
|
55
|
+
"""The exit code for an HTTP status."""
|
|
56
|
+
if status == 204:
|
|
57
|
+
return 3
|
|
58
|
+
if status in (400, 422):
|
|
59
|
+
return 2
|
|
60
|
+
if status == 404:
|
|
61
|
+
return 4
|
|
62
|
+
if status == 429:
|
|
63
|
+
return 5
|
|
64
|
+
return 0 if 200 <= status < 300 else 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _say(text: str) -> None:
|
|
68
|
+
print(text, file=sys.stderr)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _print_json(value: Any) -> None:
|
|
72
|
+
print(json.dumps(value, indent=2, ensure_ascii=False))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _pair(text: str) -> Point:
|
|
76
|
+
"""``"lat,lon"`` as a point."""
|
|
77
|
+
try:
|
|
78
|
+
lat, lon = (float(part) for part in text.split(","))
|
|
79
|
+
except ValueError as error:
|
|
80
|
+
raise UsageError(f'expected "lat,lon", got "{text}"') from error
|
|
81
|
+
return lat, lon
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _coords(client: Client, args: argparse.Namespace) -> Point:
|
|
85
|
+
"""The point from ``--place NAME`` or the ``lat lon`` positionals."""
|
|
86
|
+
if args.place:
|
|
87
|
+
if args.lat is not None:
|
|
88
|
+
raise UsageError("give either <lat> <lon> or --place, not both")
|
|
89
|
+
found = client.search(args.place).get("places") or []
|
|
90
|
+
if not found:
|
|
91
|
+
raise ApiError(404, f'no place found for "{args.place}"')
|
|
92
|
+
return found[0]["lat"], found[0]["lon"]
|
|
93
|
+
if args.lat is None or args.lon is None:
|
|
94
|
+
raise UsageError("give <lat> <lon> or --place NAME")
|
|
95
|
+
return args.lat, args.lon
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _map_params(args: argparse.Namespace, names: tuple[str, ...] = MAP_PARAMS) -> dict[str, object]:
|
|
99
|
+
return {name: getattr(args, name) for name in names if getattr(args, name, None) is not None}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def cmd_access(client: Client, args: argparse.Namespace) -> Any:
|
|
103
|
+
"""Access snapshot at a point, on foot or by another mode."""
|
|
104
|
+
snapshot = client.access(
|
|
105
|
+
_coords(client, args),
|
|
106
|
+
include=args.include,
|
|
107
|
+
types=args.types,
|
|
108
|
+
lang=args.lang,
|
|
109
|
+
walk_minutes=args.walk_minutes,
|
|
110
|
+
mode=args.mode,
|
|
111
|
+
period=args.period,
|
|
112
|
+
statistic=args.statistic,
|
|
113
|
+
)
|
|
114
|
+
return snapshot, fmt.snapshot
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cmd_describe(client: Client, args: argparse.Namespace) -> Any:
|
|
118
|
+
"""Just the generated narrative."""
|
|
119
|
+
snapshot = client.access(_coords(client, args), include="narrative", lang=args.lang)
|
|
120
|
+
return snapshot, lambda s: s.get("narrative") or "(no narrative)"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_where(client: Client, args: argparse.Namespace) -> Any:
|
|
124
|
+
"""The nearest populated place."""
|
|
125
|
+
snapshot = client.access(_coords(client, args), include="place", lang=args.lang)
|
|
126
|
+
return snapshot, lambda s: fmt.place(s["place"]) if s.get("place") else "(no place)"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _find_text(result: dict[str, Any]) -> str:
|
|
130
|
+
parts = [fmt.places(result.get("places") or [])]
|
|
131
|
+
if "pois" in result:
|
|
132
|
+
parts += [
|
|
133
|
+
"",
|
|
134
|
+
f"POIs within a {result['walk_minutes']}-minute walk:",
|
|
135
|
+
fmt.pois(result["pois"]),
|
|
136
|
+
]
|
|
137
|
+
elif result.get("detail"):
|
|
138
|
+
parts += ["", result["detail"]]
|
|
139
|
+
return "\n".join(parts)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def cmd_find(client: Client, args: argparse.Namespace) -> Any:
|
|
143
|
+
"""Places by name, and named amenities near a point."""
|
|
144
|
+
near = _pair(args.near) if args.near else None
|
|
145
|
+
return client.search(args.name, near=near, walk_minutes=args.walk_minutes), _find_text
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def cmd_routes(client: Client, args: argparse.Namespace) -> Any:
|
|
149
|
+
"""Walked paths to the nearest place of each type."""
|
|
150
|
+
return client.routes(_coords(client, args), args.types), fmt.routes
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def cmd_compass(client: Client, args: argparse.Namespace) -> Any:
|
|
154
|
+
"""Each everyday trip's nearest places, by direction."""
|
|
155
|
+
return client.compass(_coords(client, args), args.types), fmt.compass
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def cmd_compare(client: Client, args: argparse.Namespace) -> Any:
|
|
159
|
+
"""Minutes at two points, and the difference."""
|
|
160
|
+
travel = {"mode": args.mode, "period": args.period, "statistic": args.statistic}
|
|
161
|
+
a = client.access(_pair(args.a), include="minutes", types=args.types, **travel)
|
|
162
|
+
b = client.access(_pair(args.b), include="minutes", types=args.types, **travel)
|
|
163
|
+
return {"a": a, "b": b}, lambda pair: fmt.compare(pair["a"], pair["b"])
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def cmd_amenities(client: Client, args: argparse.Namespace) -> Any:
|
|
167
|
+
"""The amenity types and their labels."""
|
|
168
|
+
payload = checked(client.request("GET", "/v1/amenities"))
|
|
169
|
+
return payload, lambda p: fmt.amenities(p["amenities"])
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def cmd_embed(client: Client, args: argparse.Namespace) -> Any:
|
|
173
|
+
"""An iframe snippet."""
|
|
174
|
+
lat, lon = _coords(client, args)
|
|
175
|
+
markers = _read_markers(args.markers_file) if args.markers_file else None
|
|
176
|
+
try:
|
|
177
|
+
snippet = client.embed(lat, lon, markers=markers, **_map_params(args, EMBED_PARAMS))
|
|
178
|
+
except ValueError as error:
|
|
179
|
+
raise UsageError(str(error)) from None
|
|
180
|
+
return snippet, lambda e: e["html"]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_me(client: Client, args: argparse.Namespace) -> Any:
|
|
184
|
+
"""The key's tier and what is left of today's limit."""
|
|
185
|
+
return client.me(), fmt.me
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_reference(client: Client, args: argparse.Namespace) -> Any:
|
|
189
|
+
"""The reference catalogue, or one Can-ALE or SAM record."""
|
|
190
|
+
has_point = args.lat is not None or args.place is not None
|
|
191
|
+
if args.dataset is None:
|
|
192
|
+
if args.id or args.mode or has_point:
|
|
193
|
+
raise UsageError("--id, --mode and a point need a dataset: canale or sam")
|
|
194
|
+
return client.reference(), _pretty
|
|
195
|
+
if args.id is not None:
|
|
196
|
+
if has_point or not re.fullmatch(rf"[0-9]{{{CENSUS_ID_DIGITS[args.dataset]}}}", args.id):
|
|
197
|
+
digits = CENSUS_ID_DIGITS[args.dataset]
|
|
198
|
+
raise UsageError(f"--id is a {digits}-digit census ID, without a point or --place")
|
|
199
|
+
return client.reference(args.dataset, id=args.id, mode=args.mode), _pretty
|
|
200
|
+
point = _coords(client, args)
|
|
201
|
+
return client.reference(args.dataset, point=point, mode=args.mode), _pretty
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _pretty(value: Any) -> str:
|
|
205
|
+
return json.dumps(value, indent=2, ensure_ascii=False)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def cmd_image(client: Client, args: argparse.Namespace) -> int:
|
|
209
|
+
"""A PNG map, written to --out or a pipe."""
|
|
210
|
+
lat, lon = _coords(client, args)
|
|
211
|
+
markers = _read_markers(args.markers_file) if args.markers_file else None
|
|
212
|
+
png = client.image(lat, lon, markers=markers, **_map_params(args))
|
|
213
|
+
if args.out:
|
|
214
|
+
with open(args.out, "wb") as file:
|
|
215
|
+
file.write(png)
|
|
216
|
+
print(f"wrote {args.out} ({len(png)} bytes)")
|
|
217
|
+
elif sys.stdout.isatty():
|
|
218
|
+
_say("refusing to write binary to a terminal; pass --out FILE or pipe stdout")
|
|
219
|
+
return 2
|
|
220
|
+
else:
|
|
221
|
+
sys.stdout.buffer.write(png)
|
|
222
|
+
return 0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _read_points(source: str) -> list[Point]:
|
|
226
|
+
"""``lat,lon`` rows from a file or stdin (``-``). A first row that isn't numbers is a header.
|
|
227
|
+
|
|
228
|
+
Any other bad row is an error rather than skipped, which would misalign the results.
|
|
229
|
+
"""
|
|
230
|
+
if source == "-":
|
|
231
|
+
text = sys.stdin.read()
|
|
232
|
+
else:
|
|
233
|
+
with open(source, encoding="utf-8") as file:
|
|
234
|
+
text = file.read()
|
|
235
|
+
points: list[Point] = []
|
|
236
|
+
for number, line in enumerate(text.strip().splitlines(), start=1):
|
|
237
|
+
try:
|
|
238
|
+
points.append(_pair(",".join(line.split(",")[:2])))
|
|
239
|
+
except UsageError:
|
|
240
|
+
if number != 1:
|
|
241
|
+
raise UsageError(f'row {number} is not a valid "lat,lon": {line}') from None
|
|
242
|
+
if not points:
|
|
243
|
+
raise UsageError('no valid "lat,lon" rows found')
|
|
244
|
+
return points
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _read_markers(path: str) -> Markers:
|
|
248
|
+
"""Markers from a GeoJSON FeatureCollection, or a CSV of ``lat,lon`` with an optional label.
|
|
249
|
+
|
|
250
|
+
A ``.geojson`` or ``.json`` file is sent as it is. In a CSV a first row that isn't numbers
|
|
251
|
+
is a header, and a third column is the marker's label.
|
|
252
|
+
"""
|
|
253
|
+
with open(path, encoding="utf-8") as file:
|
|
254
|
+
text = file.read()
|
|
255
|
+
if path.lower().endswith((".geojson", ".json")):
|
|
256
|
+
try:
|
|
257
|
+
collection = json.loads(text)
|
|
258
|
+
except ValueError as error:
|
|
259
|
+
raise UsageError(f"{path} is not valid JSON: {error}") from None
|
|
260
|
+
if not isinstance(collection, dict) or collection.get("type") != "FeatureCollection":
|
|
261
|
+
raise UsageError(f"{path} must hold a GeoJSON FeatureCollection of Points")
|
|
262
|
+
return collection
|
|
263
|
+
rows: list[tuple[float, float] | tuple[float, float, str]] = []
|
|
264
|
+
for number, row in enumerate(csv.reader(io.StringIO(text)), start=1):
|
|
265
|
+
if not row:
|
|
266
|
+
continue
|
|
267
|
+
try:
|
|
268
|
+
lat, lon = _pair(",".join(row[:2]))
|
|
269
|
+
except UsageError:
|
|
270
|
+
if number != 1:
|
|
271
|
+
detail = f'row {number} of {path} is not a valid "lat,lon": {row}'
|
|
272
|
+
raise UsageError(detail) from None
|
|
273
|
+
continue
|
|
274
|
+
label = row[2].strip() if len(row) > 2 else ""
|
|
275
|
+
rows.append((lat, lon, label) if label else (lat, lon))
|
|
276
|
+
if not rows:
|
|
277
|
+
raise UsageError(f'no valid "lat,lon" rows found in {path}')
|
|
278
|
+
return rows
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def cmd_batch(client: Client, args: argparse.Namespace) -> int:
|
|
282
|
+
"""Many points: one JSON line per row, or a GeoJSON FeatureCollection."""
|
|
283
|
+
points = _read_points(args.source)
|
|
284
|
+
results = client.access(
|
|
285
|
+
points,
|
|
286
|
+
include=args.include,
|
|
287
|
+
types=args.types,
|
|
288
|
+
mode=args.mode,
|
|
289
|
+
period=args.period,
|
|
290
|
+
statistic=args.statistic,
|
|
291
|
+
)
|
|
292
|
+
if args.format == "geojson":
|
|
293
|
+
features = [
|
|
294
|
+
{
|
|
295
|
+
"type": "Feature",
|
|
296
|
+
"geometry": {"type": "Point", "coordinates": [lon, lat]},
|
|
297
|
+
"properties": result,
|
|
298
|
+
}
|
|
299
|
+
for (lat, lon), result in zip(points, results, strict=False)
|
|
300
|
+
]
|
|
301
|
+
print(json.dumps({"type": "FeatureCollection", "features": features}, ensure_ascii=False))
|
|
302
|
+
else:
|
|
303
|
+
for result in results:
|
|
304
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
305
|
+
return 0
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def cmd_login(client: Client, args: argparse.Namespace) -> int:
|
|
309
|
+
"""Get a key that a person approves in their browser; print the line that sets it."""
|
|
310
|
+
started = client.start_login(args.name or f"aportee CLI on {socket.gethostname()}")
|
|
311
|
+
_say(login_prompt(started))
|
|
312
|
+
open_link(started["verification_url_complete"])
|
|
313
|
+
try:
|
|
314
|
+
approved = client.wait_for_login(started)
|
|
315
|
+
except LoginError as error:
|
|
316
|
+
if args.json:
|
|
317
|
+
_print_json(error.body)
|
|
318
|
+
else:
|
|
319
|
+
_say(str(error))
|
|
320
|
+
return 1
|
|
321
|
+
if args.json:
|
|
322
|
+
_print_json(approved)
|
|
323
|
+
return 0
|
|
324
|
+
print(f"export APORTEE_API_KEY={approved['api_key']}")
|
|
325
|
+
_say(
|
|
326
|
+
"Approved. The key is shown once: add the line above to your shell profile, "
|
|
327
|
+
"or pass the key with --key. Revoke it on your account page."
|
|
328
|
+
)
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _globals() -> argparse.ArgumentParser:
|
|
333
|
+
shared = argparse.ArgumentParser(add_help=False)
|
|
334
|
+
shared.add_argument(
|
|
335
|
+
"--json", action="store_true", default=argparse.SUPPRESS, help="print the API payload"
|
|
336
|
+
)
|
|
337
|
+
shared.add_argument(
|
|
338
|
+
"--key", default=argparse.SUPPRESS, help="API key (default: $APORTEE_API_KEY)"
|
|
339
|
+
)
|
|
340
|
+
shared.add_argument(
|
|
341
|
+
"--base",
|
|
342
|
+
default=argparse.SUPPRESS,
|
|
343
|
+
help="site serving the API (default: $APORTEE_BASE, then https://aportee.ca)",
|
|
344
|
+
)
|
|
345
|
+
return shared
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _point_args(parser: argparse.ArgumentParser) -> None:
|
|
349
|
+
parser.add_argument("lat", type=float, nargs="?", help="latitude")
|
|
350
|
+
parser.add_argument("lon", type=float, nargs="?", help="longitude")
|
|
351
|
+
parser.add_argument("--place", help="a place name instead of <lat> <lon>")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _travel_args(parser: argparse.ArgumentParser) -> None:
|
|
355
|
+
parser.add_argument(
|
|
356
|
+
"--mode",
|
|
357
|
+
choices=["walk", "bike", "transit", "combo"],
|
|
358
|
+
help="how the minutes are travelled (default walk; combo is bike + transit)",
|
|
359
|
+
)
|
|
360
|
+
parser.add_argument(
|
|
361
|
+
"--period",
|
|
362
|
+
choices=["weekday_peak", "weekday_night", "saturday_midday", "sunday_midday"],
|
|
363
|
+
help="transit and combo: the time of the week (default weekday_peak)",
|
|
364
|
+
)
|
|
365
|
+
parser.add_argument(
|
|
366
|
+
"--statistic",
|
|
367
|
+
choices=["p50", "p90"],
|
|
368
|
+
help="transit and combo: p50 the typical trip (default), p90 the worst case (keyed)",
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _map_args(parser: argparse.ArgumentParser) -> None:
|
|
373
|
+
parser.add_argument("--help", action="help", help="show this help message and exit")
|
|
374
|
+
for name in ("zoom", "types", "theme", "lang"):
|
|
375
|
+
parser.add_argument(f"--{name}")
|
|
376
|
+
parser.add_argument("-w", dest="w", help="width in pixels")
|
|
377
|
+
parser.add_argument("-h", dest="h", help="height in pixels")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _command_parsers(shared: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]:
|
|
381
|
+
"""One parser per command.
|
|
382
|
+
|
|
383
|
+
Each is parsed intermixed, so options and coordinates can come in any order, as in
|
|
384
|
+
``access --types grocery 43.25 -79.82``.
|
|
385
|
+
"""
|
|
386
|
+
parsers: dict[str, argparse.ArgumentParser] = {}
|
|
387
|
+
|
|
388
|
+
def add(name: str, func: Callable[..., Any], help_text: str, **kwargs: Any) -> Any:
|
|
389
|
+
sub = argparse.ArgumentParser(
|
|
390
|
+
prog=f"aportee {name}", description=help_text, parents=[shared], **kwargs
|
|
391
|
+
)
|
|
392
|
+
sub.set_defaults(func=func)
|
|
393
|
+
parsers[name] = sub
|
|
394
|
+
return sub
|
|
395
|
+
|
|
396
|
+
access = add("access", cmd_access, "minutes at a point by foot, bike or transit")
|
|
397
|
+
_point_args(access)
|
|
398
|
+
_travel_args(access)
|
|
399
|
+
access.add_argument("--include", help="minutes,population,place,narrative,walk_counts or all")
|
|
400
|
+
access.add_argument(
|
|
401
|
+
"--walk-minutes", type=int, help="walk for walk_counts, 5-55 minutes (default 15)"
|
|
402
|
+
)
|
|
403
|
+
access.add_argument("--types", help="amenity types, comma-separated")
|
|
404
|
+
access.add_argument("--lang", choices=["en", "fr"])
|
|
405
|
+
for name, func, text in (
|
|
406
|
+
("describe", cmd_describe, "the generated walkability narrative"),
|
|
407
|
+
("where", cmd_where, "the nearest populated place"),
|
|
408
|
+
):
|
|
409
|
+
sub = add(name, func, text)
|
|
410
|
+
_point_args(sub)
|
|
411
|
+
sub.add_argument("--lang", choices=["en", "fr"])
|
|
412
|
+
find = add("find", cmd_find, "place search; named amenities with --near (keyed)")
|
|
413
|
+
find.add_argument("name")
|
|
414
|
+
find.add_argument("--near", help="lat,lon")
|
|
415
|
+
find.add_argument(
|
|
416
|
+
"--walk-minutes", type=int, help="how far to walk from --near, 5-55 minutes (default 15)"
|
|
417
|
+
)
|
|
418
|
+
compare = add("compare", cmd_compare, "minutes at two points and the difference")
|
|
419
|
+
compare.add_argument("a", help="lat,lon")
|
|
420
|
+
compare.add_argument("b", help="lat,lon")
|
|
421
|
+
compare.add_argument("--types", help="amenity types, comma-separated")
|
|
422
|
+
_travel_args(compare)
|
|
423
|
+
batch = add("batch", cmd_batch, "many points from a lat,lon CSV (keyed)")
|
|
424
|
+
batch.add_argument("source", help="a CSV file, or - for stdin")
|
|
425
|
+
batch.add_argument("--include")
|
|
426
|
+
batch.add_argument("--types")
|
|
427
|
+
batch.add_argument("--format", choices=["json", "geojson"], default="json")
|
|
428
|
+
_travel_args(batch)
|
|
429
|
+
for name, func, text in (
|
|
430
|
+
("image", cmd_image, "a PNG map to --out FILE (keyed)"),
|
|
431
|
+
("embed", cmd_embed, "an iframe snippet"),
|
|
432
|
+
):
|
|
433
|
+
sub = add(name, func, text, add_help=False)
|
|
434
|
+
_point_args(sub)
|
|
435
|
+
_map_args(sub)
|
|
436
|
+
sub.add_argument(
|
|
437
|
+
"--markers-file",
|
|
438
|
+
help="points to draw: a CSV of lat,lon[,label] or a GeoJSON FeatureCollection"
|
|
439
|
+
+ (" (up to 500)" if name == "image" else " (up to 20, no labels)"),
|
|
440
|
+
)
|
|
441
|
+
if name == "image":
|
|
442
|
+
sub.add_argument("--out", help="file to write the PNG to")
|
|
443
|
+
else:
|
|
444
|
+
sub.add_argument("--dots", help="0 hides the amenity dots")
|
|
445
|
+
add("amenities", cmd_amenities, "the amenity types and their labels")
|
|
446
|
+
reference = add("reference", cmd_reference, "Can-ALE and Spatial Access Measures records")
|
|
447
|
+
reference.add_argument("dataset", nargs="?", choices=sorted(CENSUS_ID_DIGITS))
|
|
448
|
+
_point_args(reference)
|
|
449
|
+
reference.add_argument("--id", help="8-digit DAUID (canale) or 11-digit DBUID (sam)")
|
|
450
|
+
reference.add_argument("--mode", help="SAM travel mode, such as walking")
|
|
451
|
+
routes = add("routes", cmd_routes, "walked paths to the nearest place of each type (keyed)")
|
|
452
|
+
_point_args(routes)
|
|
453
|
+
routes.add_argument("--types", required=True, help="1-5 amenity types, comma-separated")
|
|
454
|
+
compass = add("compass", cmd_compass, "each everyday trip's nearest places, by direction")
|
|
455
|
+
_point_args(compass)
|
|
456
|
+
compass.add_argument("--types", help="some of the eight everyday trips, comma-separated")
|
|
457
|
+
add("me", cmd_me, "the key's tier and how much of today's limit is left")
|
|
458
|
+
login = add("login", cmd_login, "get a free API key: approve it in your browser")
|
|
459
|
+
login.add_argument("--name", help="the name shown on the approval page")
|
|
460
|
+
return parsers
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def build_parser() -> tuple[argparse.ArgumentParser, dict[str, argparse.ArgumentParser]]:
|
|
464
|
+
"""The top-level parser, which picks the command, and each command's parser."""
|
|
465
|
+
shared = _globals()
|
|
466
|
+
commands = _command_parsers(shared)
|
|
467
|
+
listing = "\n".join(f" {name:<12}{sub.description}" for name, sub in commands.items())
|
|
468
|
+
parser = argparse.ArgumentParser(
|
|
469
|
+
prog="aportee",
|
|
470
|
+
description=DESCRIPTION,
|
|
471
|
+
epilog=f"commands:\n{listing}\n\n{EPILOG}",
|
|
472
|
+
parents=[shared],
|
|
473
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
474
|
+
)
|
|
475
|
+
parser.add_argument(
|
|
476
|
+
"command",
|
|
477
|
+
nargs="?",
|
|
478
|
+
choices=list(commands),
|
|
479
|
+
metavar="<command>",
|
|
480
|
+
help="one of the commands below",
|
|
481
|
+
)
|
|
482
|
+
parser.add_argument("args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
|
|
483
|
+
return parser, commands
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _run(client: Client, args: argparse.Namespace) -> int:
|
|
487
|
+
"""Run a command and print its result; API errors become exit codes."""
|
|
488
|
+
try:
|
|
489
|
+
result = args.func(client, args)
|
|
490
|
+
except ApiError as error:
|
|
491
|
+
if args.json and error.body is not None:
|
|
492
|
+
_print_json(error.body)
|
|
493
|
+
else:
|
|
494
|
+
_say(error.detail)
|
|
495
|
+
hint = error.body.get("hint") if isinstance(error.body, dict) else None
|
|
496
|
+
if isinstance(hint, str):
|
|
497
|
+
_say(hint)
|
|
498
|
+
return exit_code(error.status)
|
|
499
|
+
if isinstance(result, int):
|
|
500
|
+
return result
|
|
501
|
+
payload, render = result
|
|
502
|
+
print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json else render(payload))
|
|
503
|
+
return 0
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
507
|
+
"""Run the CLI.
|
|
508
|
+
|
|
509
|
+
Args:
|
|
510
|
+
argv: The arguments, without the program name. Defaults to ``sys.argv[1:]``.
|
|
511
|
+
|
|
512
|
+
Returns:
|
|
513
|
+
The exit code.
|
|
514
|
+
"""
|
|
515
|
+
parser, commands = build_parser()
|
|
516
|
+
top = parser.parse_args(argv)
|
|
517
|
+
if not top.command:
|
|
518
|
+
parser.print_help()
|
|
519
|
+
return 0
|
|
520
|
+
args = commands[top.command].parse_intermixed_args(top.args, namespace=top)
|
|
521
|
+
args.json = getattr(args, "json", False)
|
|
522
|
+
client = Client(key=getattr(args, "key", None), base=getattr(args, "base", None))
|
|
523
|
+
try:
|
|
524
|
+
return _run(client, args)
|
|
525
|
+
except UsageError as error:
|
|
526
|
+
_say(f"aportee {args.command}: {error}")
|
|
527
|
+
return 2
|
|
528
|
+
except (urllib.error.URLError, OSError) as error:
|
|
529
|
+
_say(f"aportee {args.command}: {error}")
|
|
530
|
+
return 1
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
if __name__ == "__main__":
|
|
534
|
+
sys.exit(main())
|