pitstop-cli 1.0.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.
pitstop/cli.py ADDED
@@ -0,0 +1,418 @@
1
+ """pitstop command-line surface: JSON-first, stdlib-only.
2
+
3
+ Exit codes: 0 success, 1 runtime error, 2 usage error."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import sys
10
+ import urllib.error
11
+
12
+ from . import core
13
+ from .version import __version__
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> int:
17
+ argv = list(sys.argv[1:] if argv is None else argv)
18
+ parser = _build_parser()
19
+ args = parser.parse_args(argv)
20
+ if not getattr(args, "func", None):
21
+ parser.print_help(sys.stderr)
22
+ return 2
23
+ try:
24
+ return args.func(args)
25
+ except urllib.error.URLError as e:
26
+ print(f"error: could not fetch source data: {e}", file=sys.stderr)
27
+ return 1
28
+ except (ValueError, OSError) as e:
29
+ print(f"error: {e}", file=sys.stderr)
30
+ return 1
31
+
32
+
33
+ def _build_parser() -> argparse.ArgumentParser:
34
+ p = argparse.ArgumentParser(
35
+ prog="pitstop",
36
+ description=(
37
+ "Unofficial JSON-first CLI for Italian fuel-station prices, backed by "
38
+ "MIMIT Osservaprezzi Carburanti open data."
39
+ ),
40
+ formatter_class=argparse.RawDescriptionHelpFormatter,
41
+ epilog=(
42
+ "Examples:\n"
43
+ " pitstop stations --comune ROMA --fuel Gasolio --cheapest --limit 5\n"
44
+ " pitstop stations --near 46.498,11.354 --radius 5 --fuel Benzina --self --json\n"
45
+ " pitstop fuels"
46
+ ),
47
+ )
48
+ p.set_defaults(func=None)
49
+ sub = p.add_subparsers(dest="command")
50
+
51
+ stations = sub.add_parser("stations", help="list and filter fuel stations with prices")
52
+ _add_load_args(stations)
53
+ stations.add_argument("--comune", default="", help="municipality name (case-insensitive)")
54
+ stations.add_argument("--provincia", default="", help="2-letter province code, e.g. BZ, RM")
55
+ stations.add_argument("--brand", default="", help="brand/bandiera substring (case-insensitive)")
56
+ stations.add_argument("--near", default="", help='proximity to "lat,lon"')
57
+ stations.add_argument("--radius", type=float, default=10.0, help="radius in km for --near")
58
+ stations.add_argument("--fuel", default="", help="keep only this fuel (substring, case-insensitive)")
59
+ stations.add_argument("--self", dest="self_only", action="store_true", help="only self-service prices")
60
+ stations.add_argument("--served", dest="served_only", action="store_true", help="only served prices")
61
+ stations.add_argument("--cheapest", action="store_true", help="sort by ascending price (needs --fuel)")
62
+ stations.add_argument("--min-price", dest="min_price", type=float, default=0.0,
63
+ help="drop prices below this floor (e.g. 1.2 to skip placeholder values); 0 = off")
64
+ stations.add_argument("--fresh-within-days", dest="fresh_days", type=int, default=0,
65
+ help="drop prices last updated more than N days ago; 0 = off")
66
+ stations.add_argument("--max-deviation-pct", dest="max_dev_pct", type=float, default=0.0,
67
+ help="drop prices more than N%% below their (fuel, provincia) median; 0 = off")
68
+ stations.add_argument("--drop-outliers", dest="drop_outliers", action="store_true",
69
+ help="drop any price flagged outlier (combined 15%% + Tukey IQR rule)")
70
+ stations.add_argument("--no-comune-validate", dest="validate_comune", action="store_false",
71
+ help="skip validating coordinates against the comune-coords reference")
72
+ stations.add_argument("--limit", type=int, default=20, help="max stations; 0 = no limit")
73
+ stations.set_defaults(func=_cmd_stations)
74
+
75
+ fuels = sub.add_parser("fuels", help="list the fuel types present in the dataset")
76
+ _add_load_args(fuels)
77
+ fuels.set_defaults(func=_cmd_fuels)
78
+
79
+ stats = sub.add_parser("stats", help="show macro price statistics by province")
80
+ _add_load_args(stats)
81
+ stats.add_argument("--fuel", default="", help="filter stats to these fuels (comma-separated)")
82
+ stats.set_defaults(func=_cmd_stats)
83
+
84
+ chargers = sub.add_parser("chargers", help="find EV charging stations (OSM)")
85
+ chargers.add_argument("--near", default="", help='proximity to "lat,lon" (or use --comune)')
86
+ chargers.add_argument("--comune", default="", help="center the search on this Italian comune")
87
+ chargers.add_argument("--radius", type=float, default=10.0, help="radius in km (default 10)")
88
+ chargers.add_argument("--operator", default="", help="operator substring (case-insensitive)")
89
+ chargers.add_argument("--socket", default="", help="plug-type substring, e.g. ccs, chademo, type2")
90
+ chargers.add_argument("--min-power", dest="min_power_kw", type=float, default=0.0,
91
+ help="minimum max-power kW")
92
+ chargers.add_argument("--fast", action="store_true", help="shortcut for --min-power 50")
93
+ chargers.add_argument("--ultra-fast", dest="ultra_fast", action="store_true",
94
+ help="shortcut for --min-power 150")
95
+ chargers.add_argument("--free", action="store_true", help="only chargers explicitly free (fee=no)")
96
+ chargers.add_argument("--public", action="store_true", help="only public access")
97
+ chargers.add_argument("--limit", type=int, default=20, help="max stations; 0 = no limit")
98
+ chargers.add_argument("--json", dest="as_json", action="store_true")
99
+ chargers.add_argument("--geojson", dest="as_geojson", action="store_true", help="emit GeoJSON FeatureCollection")
100
+ chargers.add_argument("--refresh", action="store_true",
101
+ help="bypass the 7-day OSM cache")
102
+ chargers.set_defaults(func=_cmd_chargers)
103
+
104
+ version = sub.add_parser("version", help="print version metadata")
105
+ version.set_defaults(func=lambda _a: (print(f"pitstop {__version__}") or 0))
106
+
107
+ return p
108
+
109
+
110
+ def _add_load_args(sp: argparse.ArgumentParser) -> None:
111
+ sp.add_argument("--json", dest="as_json", action="store_true", help="emit JSON instead of a table")
112
+ sp.add_argument("--geojson", dest="as_geojson", action="store_true", help="emit GeoJSON FeatureCollection")
113
+ sp.add_argument("--refresh", action="store_true", help="bypass cache and re-download source files")
114
+ sp.add_argument("--max-age", type=int, default=core.DEFAULT_MAX_AGE,
115
+ help="seconds a cached file stays fresh")
116
+ sp.add_argument("--timeout", type=int, default=core.DEFAULT_TIMEOUT,
117
+ help="per-request download timeout in seconds")
118
+
119
+
120
+ def _load(args) -> core.Dataset:
121
+ return core.load(refresh=args.refresh, max_age=args.max_age, timeout=args.timeout)
122
+
123
+
124
+ def _cmd_stations(args) -> int:
125
+ from . import geocoding
126
+ if args.self_only and args.served_only:
127
+ print("error: --self and --served are mutually exclusive", file=sys.stderr)
128
+ return 2
129
+ if args.cheapest and not args.fuel.strip():
130
+ print("error: --cheapest requires --fuel", file=sys.stderr)
131
+ return 2
132
+
133
+ use_near = bool(args.near.strip())
134
+ near_lat = near_lon = 0.0
135
+ if use_near:
136
+ try:
137
+ near_lat, near_lon = _parse_latlon(args.near)
138
+ except ValueError as e:
139
+ print(f"error: invalid --near value: {e}", file=sys.stderr)
140
+ return 2
141
+
142
+ ds = _load(args)
143
+ comune_norm = geocoding.normalize_comune(args.comune)
144
+
145
+ out = core.query_stations(
146
+ ds,
147
+ comune=comune_norm,
148
+ provincia=args.provincia,
149
+ brand=args.brand,
150
+ near=(near_lat, near_lon) if use_near else None,
151
+ radius_km=args.radius,
152
+ fuel=args.fuel,
153
+ self_only=args.self_only,
154
+ served_only=args.served_only,
155
+ cheapest=args.cheapest,
156
+ min_price=args.min_price,
157
+ max_age_days=args.fresh_days,
158
+ max_deviation_pct=args.max_dev_pct,
159
+ drop_outliers=args.drop_outliers,
160
+ validate_comune=args.validate_comune,
161
+ limit=args.limit,
162
+ )
163
+
164
+ query: dict = {}
165
+ for key, val in (("comune", comune_norm or args.comune), ("provincia", args.provincia),
166
+ ("brand", args.brand), ("fuel", args.fuel)):
167
+ if val.strip():
168
+ query[key] = val
169
+ if use_near:
170
+ query["near"] = args.near
171
+ query["radius_km"] = args.radius
172
+ if args.self_only:
173
+ query["self"] = True
174
+ if args.served_only:
175
+ query["served"] = True
176
+ if args.cheapest:
177
+ query["cheapest"] = True
178
+ if args.min_price > 0:
179
+ query["min_price"] = args.min_price
180
+ if args.fresh_days > 0:
181
+ query["fresh_within_days"] = args.fresh_days
182
+ if args.max_dev_pct > 0:
183
+ query["max_deviation_pct"] = args.max_dev_pct
184
+ if args.drop_outliers:
185
+ query["drop_outliers"] = True
186
+
187
+ if args.as_json:
188
+ return _print_stations_json(ds, out, query)
189
+ if args.as_geojson:
190
+ return _print_stations_geojson(ds, out, query)
191
+ return _print_stations_table(out, use_near)
192
+
193
+
194
+ def _cmd_stats(args) -> int:
195
+ ds = _load(args)
196
+ stats = core.fuel_stats(ds, fuel=args.fuel)
197
+
198
+ if args.as_json:
199
+ _dump({
200
+ "source": core.SOURCE_NAME,
201
+ "price_extraction_date": ds.price_date,
202
+ "generated_at": core.now_iso(),
203
+ "stats": stats
204
+ })
205
+ return 0
206
+
207
+ return _print_stats_table(stats)
208
+
209
+
210
+ def _print_stats_table(stats: dict) -> int:
211
+ for fuel, data in stats.items():
212
+ print(f"\n--- {fuel.upper()} ---")
213
+ print(f"{'PR'.ljust(4)} {'MEDIAN'.ljust(8)} {'MIN'.ljust(8)} {'MAX'.ljust(8)} {'SAMPLES'}")
214
+
215
+ # Sort provinces by code
216
+ sorted_provs = sorted(data["provinces"].items())
217
+ for prov, p_stats in sorted_provs:
218
+ print(f"{prov.ljust(4)} "
219
+ f"{p_stats['median']:<8.3f} "
220
+ f"{p_stats['min']:<8.3f} "
221
+ f"{p_stats['max']:<8.3f} "
222
+ f"{p_stats['count']}")
223
+
224
+ nat = data["national"]
225
+ print(f"{'---'.ljust(4)} {'---'.ljust(8)} {'---'.ljust(8)} {'---'.ljust(8)} {'---'}")
226
+ print(f"{'NAT'.ljust(4)} "
227
+ f"{nat['median']:<8.3f} "
228
+ f"{nat['min']:<8.3f} "
229
+ f"{nat['max']:<8.3f} "
230
+ f"{nat['count']}")
231
+ return 0
232
+
233
+
234
+ def _cmd_chargers(args) -> int:
235
+ from . import chargers, geocoding
236
+ if not args.near.strip() and not args.comune.strip():
237
+ print("error: pass --near \"lat,lon\" or --comune NAME", file=sys.stderr)
238
+ return 2
239
+
240
+ if args.near.strip():
241
+ try:
242
+ lat, lon = _parse_latlon(args.near)
243
+ except ValueError as e:
244
+ print(f"error: invalid --near value: {e}", file=sys.stderr)
245
+ return 2
246
+ else:
247
+ coords = geocoding.load_comune_coords()
248
+ comune_norm = geocoding.normalize_comune(args.comune)
249
+ true = coords.get(comune_norm)
250
+ if not true:
251
+ print(f"error: comune '{args.comune}' not found in the comune-coords reference",
252
+ file=sys.stderr)
253
+ return 1
254
+ lat, lon = true
255
+
256
+ min_kw = args.min_power_kw
257
+ if args.ultra_fast:
258
+ min_kw = max(min_kw, 150.0)
259
+ elif args.fast:
260
+ min_kw = max(min_kw, 50.0)
261
+
262
+ stations, error = chargers.find_chargers(
263
+ near=(lat, lon),
264
+ radius_km=args.radius,
265
+ operator=args.operator,
266
+ socket=args.socket,
267
+ min_power_kw=min_kw,
268
+ free_only=args.free,
269
+ public_only=args.public,
270
+ refresh=args.refresh,
271
+ )
272
+ if args.limit > 0:
273
+ stations = stations[: args.limit]
274
+
275
+ query = {"near": f"{lat},{lon}", "radius_km": args.radius}
276
+ if args.comune:
277
+ query["comune"] = args.comune
278
+ if args.operator:
279
+ query["operator"] = args.operator
280
+ if args.socket:
281
+ query["socket"] = args.socket
282
+ if min_kw > 0:
283
+ query["min_power_kw"] = min_kw
284
+ if args.free:
285
+ query["free"] = True
286
+ if args.public:
287
+ query["public"] = True
288
+
289
+ if args.as_json:
290
+ _dump(chargers.response_envelope(stations, query, error=error))
291
+ return 0
292
+ if args.as_geojson:
293
+ _dump(chargers.geojson_envelope(stations, query, error=error))
294
+ return 0
295
+ return _print_chargers_table(stations)
296
+
297
+
298
+ def _print_chargers_table(stations) -> int:
299
+ headers = ["DIST_KM", "OPERATOR", "MAX_KW", "PLUGS", "CAP", "FEE", "ACCESS", "NAME"]
300
+ rows = [headers]
301
+ for st in stations:
302
+ plugs = ", ".join(f"{s.type}x{s.count}" for s in st.sockets[:3]) or "?"
303
+ fee = "" if st.fee is None else ("yes" if st.fee else "no")
304
+ rows.append([
305
+ f"{st.distance_km:.2f}" if st.distance_km is not None else "",
306
+ (st.operator or "?")[:24],
307
+ f"{st.max_power_kw:g}" if st.max_power_kw is not None else "?",
308
+ plugs[:36],
309
+ str(st.capacity) if st.capacity is not None else "",
310
+ fee,
311
+ (st.access or "")[:10],
312
+ (st.name or "")[:30],
313
+ ])
314
+ widths = [max(len(r[i]) for r in rows) for i in range(len(headers))]
315
+ for r in rows:
316
+ print(" ".join(c.ljust(widths[i]) for i, c in enumerate(r)))
317
+
318
+ if stations:
319
+ top = stations[0]
320
+ print(f"\nTop result map: {core.navigation_url(top.lat, top.lon)}")
321
+
322
+ with_tariff = sum(1 for s in stations if s.tariff_info_url)
323
+ if with_tariff:
324
+ print(f"\n{with_tariff}/{len(stations)} stations have an operator tariff page "
325
+ f"(--json to see `tariff_info_url`). Per-station prices are not in open data.")
326
+ return 0
327
+
328
+
329
+ def _cmd_fuels(args) -> int:
330
+ ds = _load(args)
331
+ counts: dict[str, int] = {}
332
+ for st in ds.stations.values():
333
+ for p in st.prices:
334
+ counts[p.fuel] = counts.get(p.fuel, 0) + 1
335
+ items = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
336
+
337
+ if args.as_json:
338
+ _dump({
339
+ "source": core.SOURCE_NAME,
340
+ "source_url": core.SOURCE_URL,
341
+ "price_extraction_date": ds.price_date,
342
+ "fuels": [{"fuel": f, "count": c} for f, c in items],
343
+ })
344
+ return 0
345
+
346
+ width = max((len(f) for f, _ in items), default=4)
347
+ print(f"{'FUEL'.ljust(width)} PRICE ROWS")
348
+ for f, c in items:
349
+ print(f"{f.ljust(width)} {c}")
350
+ return 0
351
+
352
+
353
+ def _print_stations_json(ds: core.Dataset, stations: list[core.Station], query: dict) -> int:
354
+ _dump(core.response_envelope(ds, stations, query))
355
+ return 0
356
+
357
+
358
+ def _print_stations_geojson(ds: core.Dataset, stations: list[core.Station], query: dict) -> int:
359
+ _dump(core.geojson_envelope(ds, stations, query))
360
+ return 0
361
+
362
+
363
+ def _print_stations_table(stations: list[core.Station], use_near: bool) -> int:
364
+ any_suspect = False
365
+ any_outlier = False
366
+ rows = []
367
+ for st in stations:
368
+ prices = st.prices or [None]
369
+ for p in prices:
370
+ mode = "" if p is None else ("self" if p.self_service else "served")
371
+ fuel = "" if p is None else p.fuel
372
+ if p is None:
373
+ price = ""
374
+ else:
375
+ outlier_mark = " ?" if p.outlier else ""
376
+ price = f"{p.price:.3f}{outlier_mark}"
377
+ if p.outlier:
378
+ any_outlier = True
379
+ updated = "" if p is None else (p.updated[:10])
380
+ name = st.name + (" *" if st.coordinate_suspect else "")
381
+ if st.coordinate_suspect:
382
+ any_suspect = True
383
+ base = [st.brand, st.comune, st.provincia, fuel, price, mode, updated, name]
384
+ if use_near:
385
+ base = [f"{st.distance_km:.2f}"] + base
386
+ rows.append(base)
387
+
388
+ headers = (["DIST_KM"] if use_near else []) + ["BRAND", "COMUNE", "PR", "FUEL", "PRICE", "MODE", "UPDATED", "NAME"]
389
+ rows.insert(0, headers)
390
+ widths = [max(len(r[i]) for r in rows) for i in range(len(headers))]
391
+ for r in rows:
392
+ print(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(r)))
393
+
394
+ if stations:
395
+ top = stations[0]
396
+ print(f"\nTop result map: {core.navigation_url(top.lat, top.lon)}")
397
+
398
+ if any_outlier:
399
+ print("\n? price >15% below its (fuel, provincia) median — may be a misreport.")
400
+ if any_suspect:
401
+ print("* coordinate_suspect: registry coordinate is far from the comune's other stations.")
402
+ return 0
403
+
404
+
405
+ def _parse_latlon(s: str) -> tuple[float, float]:
406
+ parts = s.split(",")
407
+ if len(parts) != 2:
408
+ raise ValueError('expected "lat,lon"')
409
+ return float(parts[0].strip()), float(parts[1].strip())
410
+
411
+
412
+ def _dump(obj) -> None:
413
+ json.dump(obj, sys.stdout, ensure_ascii=False, indent=2)
414
+ sys.stdout.write("\n")
415
+
416
+
417
+ if __name__ == "__main__":
418
+ raise SystemExit(main())