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/__init__.py +3 -0
- pitstop/__main__.py +4 -0
- pitstop/chargers.py +281 -0
- pitstop/cli.py +418 -0
- pitstop/core.py +572 -0
- pitstop/cpo_tariffs.py +60 -0
- pitstop/geocoding.py +146 -0
- pitstop/mcp_server.py +264 -0
- pitstop/overpass.py +83 -0
- pitstop/version.py +1 -0
- pitstop_cli-1.0.0.dist-info/METADATA +170 -0
- pitstop_cli-1.0.0.dist-info/RECORD +15 -0
- pitstop_cli-1.0.0.dist-info/WHEEL +4 -0
- pitstop_cli-1.0.0.dist-info/entry_points.txt +3 -0
- pitstop_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
pitstop/core.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
"""Fetch, cache, parse, and join the Italian MIMIT "Osservaprezzi Carburanti"
|
|
2
|
+
open data: a station registry (anagrafica) and a daily practiced-price file,
|
|
3
|
+
keyed on idImpianto. Standard library only."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import csv
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import statistics
|
|
11
|
+
import time
|
|
12
|
+
import urllib.request
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from datetime import date, datetime, timezone
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
ANAGRAFICA_URL = "https://www.mimit.gov.it/images/exportCSV/anagrafica_impianti_attivi.csv"
|
|
18
|
+
PREZZO_URL = "https://www.mimit.gov.it/images/exportCSV/prezzo_alle_8.csv"
|
|
19
|
+
|
|
20
|
+
SOURCE_NAME = "MIMIT Osservaprezzi Carburanti (open data)"
|
|
21
|
+
SOURCE_URL = (
|
|
22
|
+
"https://www.mimit.gov.it/it/open-data/elenco-dataset/"
|
|
23
|
+
"carburanti-prezzi-praticati-e-anagrafica-degli-impianti"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DISCLAIMER = (
|
|
27
|
+
"Unofficial tool. Source: MIMIT Osservaprezzi Carburanti open data. "
|
|
28
|
+
"Prices are values reported by operators as of ~08:00 the day before the "
|
|
29
|
+
"price extraction date; they are not real-time."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
DEFAULT_MAX_AGE = 24 * 60 * 60 # seconds
|
|
33
|
+
DEFAULT_TIMEOUT = 180 # seconds
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Price:
|
|
38
|
+
fuel: str
|
|
39
|
+
price: float
|
|
40
|
+
self_service: bool
|
|
41
|
+
updated: str
|
|
42
|
+
regional_median: float | None = None
|
|
43
|
+
deviation_pct: float | None = None
|
|
44
|
+
outlier: bool = False
|
|
45
|
+
|
|
46
|
+
def to_dict(self) -> dict:
|
|
47
|
+
d = {
|
|
48
|
+
"fuel": self.fuel,
|
|
49
|
+
"price": self.price,
|
|
50
|
+
"self_service": self.self_service,
|
|
51
|
+
"updated": self.updated,
|
|
52
|
+
}
|
|
53
|
+
if self.regional_median is not None:
|
|
54
|
+
d["regional_median"] = self.regional_median
|
|
55
|
+
d["deviation_pct"] = self.deviation_pct
|
|
56
|
+
if self.outlier:
|
|
57
|
+
d["outlier"] = True
|
|
58
|
+
return d
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def navigation_url(lat: float, lon: float) -> str:
|
|
62
|
+
"""Return a Google Maps search URL for the given coordinates."""
|
|
63
|
+
return f"https://www.google.com/maps/search/?api=1&query={lat},{lon}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Station:
|
|
68
|
+
id: str
|
|
69
|
+
operator: str
|
|
70
|
+
brand: str
|
|
71
|
+
type: str
|
|
72
|
+
name: str
|
|
73
|
+
address: str
|
|
74
|
+
comune: str
|
|
75
|
+
provincia: str
|
|
76
|
+
lat: float
|
|
77
|
+
lon: float
|
|
78
|
+
prices: list[Price] = field(default_factory=list)
|
|
79
|
+
distance_km: float | None = None
|
|
80
|
+
coordinate_suspect: bool = False
|
|
81
|
+
|
|
82
|
+
def to_dict(self) -> dict:
|
|
83
|
+
d = {
|
|
84
|
+
"id": self.id,
|
|
85
|
+
"operator": self.operator,
|
|
86
|
+
"brand": self.brand,
|
|
87
|
+
"type": self.type,
|
|
88
|
+
"name": self.name,
|
|
89
|
+
"address": self.address,
|
|
90
|
+
"comune": self.comune,
|
|
91
|
+
"provincia": self.provincia,
|
|
92
|
+
"lat": self.lat,
|
|
93
|
+
"lon": self.lon,
|
|
94
|
+
"navigation_url": navigation_url(self.lat, self.lon),
|
|
95
|
+
"prices": [p.to_dict() for p in self.prices],
|
|
96
|
+
}
|
|
97
|
+
if self.distance_km is not None:
|
|
98
|
+
d["distance_km"] = self.distance_km
|
|
99
|
+
if self.coordinate_suspect:
|
|
100
|
+
d["coordinate_suspect"] = True
|
|
101
|
+
return d
|
|
102
|
+
|
|
103
|
+
def to_geojson_feature(self) -> dict:
|
|
104
|
+
props = self.to_dict()
|
|
105
|
+
lat = props.pop("lat")
|
|
106
|
+
lon = props.pop("lon")
|
|
107
|
+
return {
|
|
108
|
+
"type": "Feature",
|
|
109
|
+
"geometry": {"type": "Point", "coordinates": [lon, lat]},
|
|
110
|
+
"properties": props,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class Dataset:
|
|
116
|
+
stations: dict[str, Station]
|
|
117
|
+
registry_date: str
|
|
118
|
+
price_date: str
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cache_dir() -> Path:
|
|
122
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
123
|
+
d = Path(base) / "pitstop"
|
|
124
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
125
|
+
return d
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _cached_file(
|
|
129
|
+
url: str, name: str, *, refresh: bool, max_age: int, timeout: int
|
|
130
|
+
) -> Path:
|
|
131
|
+
"""Return a local path to the CSV, downloading when missing, stale, or forced."""
|
|
132
|
+
path = cache_dir() / name
|
|
133
|
+
if not refresh and path.exists():
|
|
134
|
+
age = time.time() - path.stat().st_mtime
|
|
135
|
+
if max_age <= 0 or age < max_age:
|
|
136
|
+
return path
|
|
137
|
+
|
|
138
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
139
|
+
req = urllib.request.Request(url, headers={"User-Agent": "pitstop"})
|
|
140
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
141
|
+
data = resp.read()
|
|
142
|
+
tmp.write_bytes(data)
|
|
143
|
+
tmp.replace(path) # atomic; a partial download never clobbers a good cache file
|
|
144
|
+
return path
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _read_rows(path: Path) -> tuple[str, list[list[str]]]:
|
|
148
|
+
"""Parse a MIMIT pipe-delimited file. Returns (extraction_date, data_rows).
|
|
149
|
+
|
|
150
|
+
Line 0 is "Estrazione del YYYY-MM-DD", line 1 is the header, the rest is data.
|
|
151
|
+
"""
|
|
152
|
+
with path.open("r", encoding="utf-8", errors="replace", newline="") as f:
|
|
153
|
+
reader = csv.reader(f, delimiter="|")
|
|
154
|
+
rows = list(reader)
|
|
155
|
+
if len(rows) < 2:
|
|
156
|
+
raise ValueError(f"{path.name} has no data rows")
|
|
157
|
+
extraction = ""
|
|
158
|
+
if rows[0]:
|
|
159
|
+
extraction = rows[0][0].removeprefix("Estrazione del ").strip()
|
|
160
|
+
return extraction, rows[2:]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _parse_registry(path: Path) -> tuple[dict[str, Station], str]:
|
|
164
|
+
date, rows = _read_rows(path)
|
|
165
|
+
stations: dict[str, Station] = {}
|
|
166
|
+
for row in rows:
|
|
167
|
+
if len(row) < 10:
|
|
168
|
+
continue
|
|
169
|
+
sid = row[0].strip()
|
|
170
|
+
if not sid:
|
|
171
|
+
continue
|
|
172
|
+
stations[sid] = Station(
|
|
173
|
+
id=sid,
|
|
174
|
+
operator=row[1].strip(),
|
|
175
|
+
brand=row[2].strip(),
|
|
176
|
+
type=row[3].strip(),
|
|
177
|
+
name=row[4].strip(),
|
|
178
|
+
address=row[5].strip(),
|
|
179
|
+
comune=row[6].strip(),
|
|
180
|
+
provincia=row[7].strip(),
|
|
181
|
+
lat=_to_float(row[8]),
|
|
182
|
+
lon=_to_float(row[9]),
|
|
183
|
+
)
|
|
184
|
+
return stations, date
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _attach_prices(path: Path, stations: dict[str, Station]) -> str:
|
|
188
|
+
date, rows = _read_rows(path)
|
|
189
|
+
for row in rows:
|
|
190
|
+
if len(row) < 5:
|
|
191
|
+
continue
|
|
192
|
+
st = stations.get(row[0].strip())
|
|
193
|
+
if st is None:
|
|
194
|
+
continue
|
|
195
|
+
price = _to_float(row[2], default=None)
|
|
196
|
+
if price is None:
|
|
197
|
+
continue
|
|
198
|
+
st.prices.append(
|
|
199
|
+
Price(
|
|
200
|
+
fuel=row[1].strip(),
|
|
201
|
+
price=price,
|
|
202
|
+
self_service=row[3].strip() == "1",
|
|
203
|
+
updated=_normalize_ts(row[4].strip()),
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
return date
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def load(
|
|
210
|
+
*,
|
|
211
|
+
refresh: bool = False,
|
|
212
|
+
max_age: int = DEFAULT_MAX_AGE,
|
|
213
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
214
|
+
) -> Dataset:
|
|
215
|
+
"""Fetch (or read from cache) both files and return the joined dataset."""
|
|
216
|
+
ana = _cached_file(
|
|
217
|
+
ANAGRAFICA_URL,
|
|
218
|
+
"anagrafica_impianti_attivi.csv",
|
|
219
|
+
refresh=refresh,
|
|
220
|
+
max_age=max_age,
|
|
221
|
+
timeout=timeout,
|
|
222
|
+
)
|
|
223
|
+
prezzo = _cached_file(
|
|
224
|
+
PREZZO_URL,
|
|
225
|
+
"prezzo_alle_8.csv",
|
|
226
|
+
refresh=refresh,
|
|
227
|
+
max_age=max_age,
|
|
228
|
+
timeout=timeout,
|
|
229
|
+
)
|
|
230
|
+
stations, registry_date = _parse_registry(ana)
|
|
231
|
+
price_date = _attach_prices(prezzo, stations)
|
|
232
|
+
return Dataset(stations=stations, registry_date=registry_date, price_date=price_date)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def filter_prices(
|
|
236
|
+
prices: list[Price],
|
|
237
|
+
fuel: str = "",
|
|
238
|
+
self_only: bool = False,
|
|
239
|
+
served_only: bool = False,
|
|
240
|
+
min_price: float = 0.0,
|
|
241
|
+
max_age_days: int = 0,
|
|
242
|
+
today: date | None = None,
|
|
243
|
+
) -> list[Price]:
|
|
244
|
+
fuels = [f.strip().lower() for f in fuel.split(",") if f.strip()]
|
|
245
|
+
if max_age_days > 0 and today is None:
|
|
246
|
+
today = date.today()
|
|
247
|
+
out = []
|
|
248
|
+
for p in prices:
|
|
249
|
+
if fuels and not any(f in p.fuel.lower() for f in fuels):
|
|
250
|
+
continue
|
|
251
|
+
if self_only and not p.self_service:
|
|
252
|
+
continue
|
|
253
|
+
if served_only and p.self_service:
|
|
254
|
+
continue
|
|
255
|
+
if min_price > 0 and p.price < min_price:
|
|
256
|
+
continue
|
|
257
|
+
if max_age_days > 0:
|
|
258
|
+
age = price_age_days(p.updated, today)
|
|
259
|
+
if age is not None and age > max_age_days:
|
|
260
|
+
continue
|
|
261
|
+
out.append(p)
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def price_age_days(updated: str, today: date | None = None) -> int | None:
|
|
266
|
+
"""Age of a price in days from its `updated` timestamp. None if unparseable."""
|
|
267
|
+
if today is None:
|
|
268
|
+
today = date.today()
|
|
269
|
+
try:
|
|
270
|
+
d = datetime.fromisoformat(updated).date()
|
|
271
|
+
except ValueError:
|
|
272
|
+
try:
|
|
273
|
+
d = datetime.strptime(updated.split()[0], "%d/%m/%Y").date()
|
|
274
|
+
except (ValueError, IndexError):
|
|
275
|
+
return None
|
|
276
|
+
return (today - d).days
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def min_price_of(prices: list[Price]) -> float | None:
|
|
280
|
+
return min((p.price for p in prices), default=None)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def default_floor(fuel: str) -> float:
|
|
284
|
+
"""A sensible default min-price floor for ranking, given a fuel name.
|
|
285
|
+
|
|
286
|
+
The common placeholder value (1.000) only corrupts cheapest-ranking for
|
|
287
|
+
fuels whose real price is above it (petrol, diesel, methane ~1.3-2.5/kg), so
|
|
288
|
+
those get a 1.2 floor. GPL (LPG, ~0.7-0.9) sits below 1.000, so a 1.2 floor
|
|
289
|
+
would wrongly drop every real price; GPL gets no floor (its 1.000 placeholders
|
|
290
|
+
sink harmlessly to the bottom of an ascending sort)."""
|
|
291
|
+
f = fuel.strip().lower()
|
|
292
|
+
if not f:
|
|
293
|
+
return 0.0
|
|
294
|
+
return 0.0 if "gpl" in f else 1.2
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def query_stations(
|
|
298
|
+
ds: Dataset,
|
|
299
|
+
*,
|
|
300
|
+
comune: str = "",
|
|
301
|
+
provincia: str = "",
|
|
302
|
+
brand: str = "",
|
|
303
|
+
near: tuple[float, float] | None = None,
|
|
304
|
+
radius_km: float = 10.0,
|
|
305
|
+
fuel: str = "",
|
|
306
|
+
self_only: bool = False,
|
|
307
|
+
served_only: bool = False,
|
|
308
|
+
cheapest: bool = False,
|
|
309
|
+
min_price: float = 0.0,
|
|
310
|
+
max_age_days: int = 0,
|
|
311
|
+
max_deviation_pct: float = 0.0,
|
|
312
|
+
drop_outliers: bool = False,
|
|
313
|
+
limit: int = 20,
|
|
314
|
+
validate_comune: bool = True,
|
|
315
|
+
comune_coords: dict[str, tuple[float, float]] | None = None,
|
|
316
|
+
) -> list[Station]:
|
|
317
|
+
"""Filter, sort, and limit stations. Mutates the dataset's Station objects
|
|
318
|
+
(narrows prices, sets distance_km), so pass a freshly loaded Dataset."""
|
|
319
|
+
today = date.today() if max_age_days > 0 else None
|
|
320
|
+
centroids = comune_centroids(ds)
|
|
321
|
+
stats = fuel_provincia_stats(ds)
|
|
322
|
+
if validate_comune and comune_coords is None:
|
|
323
|
+
from . import geocoding
|
|
324
|
+
comune_coords = geocoding.load_comune_coords()
|
|
325
|
+
elif comune_coords is None:
|
|
326
|
+
comune_coords = {}
|
|
327
|
+
|
|
328
|
+
out: list[Station] = []
|
|
329
|
+
for st in ds.stations.values():
|
|
330
|
+
if comune and st.comune.casefold() != comune.strip().casefold():
|
|
331
|
+
continue
|
|
332
|
+
if provincia and st.provincia.casefold() != provincia.strip().casefold():
|
|
333
|
+
continue
|
|
334
|
+
if brand and brand.lower() not in st.brand.lower():
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
prices = filter_prices(
|
|
338
|
+
st.prices, fuel, self_only, served_only, min_price, max_age_days, today
|
|
339
|
+
)
|
|
340
|
+
# Annotate each surviving price with its (fuel, provincia) market context,
|
|
341
|
+
# then optionally drop prices that fall too far below the local market.
|
|
342
|
+
# outlier flag fires if the price is below EITHER the percentage threshold
|
|
343
|
+
# OR the Tukey lower fence (Q1 - 1.5*IQR) — combining catches both
|
|
344
|
+
# gross misreports in diverse markets and subtle ones in tight markets.
|
|
345
|
+
prov = st.provincia.strip().upper()
|
|
346
|
+
kept_prices: list[Price] = []
|
|
347
|
+
for p in prices:
|
|
348
|
+
s = stats.get((p.fuel.strip().lower(), prov))
|
|
349
|
+
if s is not None:
|
|
350
|
+
med = s["median"]
|
|
351
|
+
p.regional_median = round(med, 3)
|
|
352
|
+
p.deviation_pct = round((p.price - med) / med * 100, 1)
|
|
353
|
+
p.outlier = (p.deviation_pct < -OUTLIER_DEVIATION_PCT
|
|
354
|
+
or p.price < s["lower_fence"])
|
|
355
|
+
if max_deviation_pct > 0 and s is not None and p.deviation_pct < -max_deviation_pct:
|
|
356
|
+
continue
|
|
357
|
+
if drop_outliers and p.outlier:
|
|
358
|
+
continue
|
|
359
|
+
kept_prices.append(p)
|
|
360
|
+
active_filter = (fuel or self_only or served_only or min_price > 0
|
|
361
|
+
or max_age_days > 0 or max_deviation_pct > 0 or drop_outliers)
|
|
362
|
+
if active_filter and not kept_prices:
|
|
363
|
+
continue
|
|
364
|
+
st.prices = kept_prices
|
|
365
|
+
|
|
366
|
+
# Flag coordinates that are implausible or far from where they should be.
|
|
367
|
+
# Prefer the data-derived centroid when available (robust if >=3 stations);
|
|
368
|
+
# fall back to the true ISTAT-derived coord (handles single-station comuni).
|
|
369
|
+
c = centroids.get(st.comune.upper())
|
|
370
|
+
true_coord = comune_coords.get(st.comune.upper()) if comune_coords else None
|
|
371
|
+
|
|
372
|
+
if not in_italy(st.lat, st.lon):
|
|
373
|
+
st.coordinate_suspect = True
|
|
374
|
+
elif c is not None:
|
|
375
|
+
if haversine_km(c[0], c[1], st.lat, st.lon) > SUSPECT_DISTANCE_KM:
|
|
376
|
+
st.coordinate_suspect = True
|
|
377
|
+
elif true_coord is not None:
|
|
378
|
+
if haversine_km(true_coord[0], true_coord[1], st.lat, st.lon) > SUSPECT_DISTANCE_KM:
|
|
379
|
+
st.coordinate_suspect = True
|
|
380
|
+
|
|
381
|
+
if near is not None:
|
|
382
|
+
if not in_italy(st.lat, st.lon):
|
|
383
|
+
continue # invalid coords cannot be reliably near anything
|
|
384
|
+
# Reject stations whose declared comune is geographically too far
|
|
385
|
+
# from the query point. Prefer centroid, fall back to true_coord.
|
|
386
|
+
ref_comune_coord = c or true_coord
|
|
387
|
+
if ref_comune_coord is not None:
|
|
388
|
+
comune_dist = haversine_km(near[0], near[1], ref_comune_coord[0], ref_comune_coord[1])
|
|
389
|
+
if comune_dist > radius_km + 30.0:
|
|
390
|
+
continue
|
|
391
|
+
d = haversine_km(near[0], near[1], st.lat, st.lon)
|
|
392
|
+
if d > radius_km:
|
|
393
|
+
continue
|
|
394
|
+
st.distance_km = round(d, 2)
|
|
395
|
+
out.append(st)
|
|
396
|
+
|
|
397
|
+
if cheapest:
|
|
398
|
+
out.sort(key=lambda s: (min_price_of(s.prices) is None, min_price_of(s.prices) or 0.0))
|
|
399
|
+
elif near is not None:
|
|
400
|
+
out.sort(key=lambda s: s.distance_km if s.distance_km is not None else float("inf"))
|
|
401
|
+
else:
|
|
402
|
+
out.sort(key=lambda s: (s.comune, s.name))
|
|
403
|
+
|
|
404
|
+
if limit > 0:
|
|
405
|
+
out = out[:limit]
|
|
406
|
+
return out
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def response_envelope(ds: Dataset, stations: list[Station], query: dict) -> dict:
|
|
410
|
+
"""Build the stable JSON response object shared by the CLI and MCP server."""
|
|
411
|
+
return {
|
|
412
|
+
"source": SOURCE_NAME,
|
|
413
|
+
"source_url": SOURCE_URL,
|
|
414
|
+
"registry_extraction_date": ds.registry_date,
|
|
415
|
+
"price_extraction_date": ds.price_date,
|
|
416
|
+
"generated_at": now_iso(),
|
|
417
|
+
"query": query,
|
|
418
|
+
"count": len(stations),
|
|
419
|
+
"stations": [s.to_dict() for s in stations],
|
|
420
|
+
"disclaimer": DISCLAIMER,
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def geojson_envelope(ds: Dataset, stations: list[Station], query: dict) -> dict:
|
|
425
|
+
"""Build a standard GeoJSON FeatureCollection."""
|
|
426
|
+
return {
|
|
427
|
+
"type": "FeatureCollection",
|
|
428
|
+
"metadata": {
|
|
429
|
+
"source": SOURCE_NAME,
|
|
430
|
+
"registry_extraction_date": ds.registry_date,
|
|
431
|
+
"price_extraction_date": ds.price_date,
|
|
432
|
+
"generated_at": now_iso(),
|
|
433
|
+
"query": query,
|
|
434
|
+
"disclaimer": DISCLAIMER,
|
|
435
|
+
},
|
|
436
|
+
"features": [s.to_geojson_feature() for s in stations],
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def fuel_stats(ds: Dataset, fuel: str = "") -> dict:
|
|
441
|
+
"""Return median, min, max prices per province and region for each fuel."""
|
|
442
|
+
fuels = [f.strip().lower() for f in fuel.split(",") if f.strip()]
|
|
443
|
+
|
|
444
|
+
# Fuel -> Province/Region -> list[Price]
|
|
445
|
+
prov_bucket: dict[str, dict[str, list[float]]] = {}
|
|
446
|
+
reg_bucket: dict[str, dict[str, list[float]]] = {}
|
|
447
|
+
|
|
448
|
+
# Mapping of province codes to regions (simplified for core advisory)
|
|
449
|
+
# In a full app we'd use a static lookup, for now we derive from provincia data
|
|
450
|
+
for st in ds.stations.values():
|
|
451
|
+
prov = st.provincia.strip().upper()
|
|
452
|
+
if not prov or len(prov) != 2:
|
|
453
|
+
continue
|
|
454
|
+
for p in st.prices:
|
|
455
|
+
f_key = p.fuel.strip().lower()
|
|
456
|
+
if fuels and not any(f in f_key for f in fuels):
|
|
457
|
+
continue
|
|
458
|
+
prov_bucket.setdefault(p.fuel, {}).setdefault(prov, []).append(p.price)
|
|
459
|
+
# Use provincia as a proxy for region for now, or just focus on prov
|
|
460
|
+
|
|
461
|
+
out: dict[str, dict] = {}
|
|
462
|
+
for f_name, prov_data in prov_bucket.items():
|
|
463
|
+
f_stats = {"provinces": {}}
|
|
464
|
+
all_prices = []
|
|
465
|
+
for prov, prices in prov_data.items():
|
|
466
|
+
all_prices.extend(prices)
|
|
467
|
+
f_stats["provinces"][prov] = {
|
|
468
|
+
"median": round(statistics.median(prices), 3),
|
|
469
|
+
"min": min(prices),
|
|
470
|
+
"max": max(prices),
|
|
471
|
+
"count": len(prices),
|
|
472
|
+
}
|
|
473
|
+
f_stats["national"] = {
|
|
474
|
+
"median": round(statistics.median(all_prices), 3),
|
|
475
|
+
"min": min(all_prices),
|
|
476
|
+
"max": max(all_prices),
|
|
477
|
+
"count": len(all_prices),
|
|
478
|
+
}
|
|
479
|
+
out[f_name] = f_stats
|
|
480
|
+
|
|
481
|
+
return out
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
ITALY_BBOX = (35.0, 47.6, 6.0, 19.0) # min_lat, max_lat, min_lon, max_lon
|
|
485
|
+
SUSPECT_DISTANCE_KM = 30.0
|
|
486
|
+
OUTLIER_DEVIATION_PCT = 15.0 # a price more than this far below its (fuel, provincia) median is flagged
|
|
487
|
+
MIN_SAMPLES_FOR_MEDIAN = 15
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def fuel_provincia_stats(ds: "Dataset", min_n: int = MIN_SAMPLES_FOR_MEDIAN) -> dict[tuple[str, str], dict]:
|
|
491
|
+
"""Per (fuel-lowercase, provincia-uppercase) statistics for outlier detection:
|
|
492
|
+
median, Q1, Q3, IQR, and Tukey lower fence (Q1 - 1.5*IQR). Only returned
|
|
493
|
+
where at least `min_n` samples exist. The Tukey fence catches misreports
|
|
494
|
+
in tight markets that a fixed-percentage threshold misses (e.g. a 1.787
|
|
495
|
+
diesel in BZ where the median is 2.099 — only -14.9% but well below the
|
|
496
|
+
1.949 fence)."""
|
|
497
|
+
bucket: dict[tuple[str, str], list[float]] = {}
|
|
498
|
+
for st in ds.stations.values():
|
|
499
|
+
prov = st.provincia.strip().upper()
|
|
500
|
+
if not prov:
|
|
501
|
+
continue
|
|
502
|
+
for p in st.prices:
|
|
503
|
+
fuel = p.fuel.strip().lower()
|
|
504
|
+
if not fuel:
|
|
505
|
+
continue
|
|
506
|
+
bucket.setdefault((fuel, prov), []).append(p.price)
|
|
507
|
+
out: dict[tuple[str, str], dict] = {}
|
|
508
|
+
for key, prices in bucket.items():
|
|
509
|
+
if len(prices) < min_n:
|
|
510
|
+
continue
|
|
511
|
+
q1, _, q3 = statistics.quantiles(prices, n=4)
|
|
512
|
+
iqr = q3 - q1
|
|
513
|
+
out[key] = {
|
|
514
|
+
"median": statistics.median(prices),
|
|
515
|
+
"q1": q1, "q3": q3, "iqr": iqr,
|
|
516
|
+
"lower_fence": q1 - 1.5 * iqr,
|
|
517
|
+
}
|
|
518
|
+
return out
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
# Back-compat: original median-only helper kept as a thin wrapper.
|
|
522
|
+
def fuel_provincia_medians(ds: "Dataset", min_n: int = MIN_SAMPLES_FOR_MEDIAN) -> dict[tuple[str, str], float]:
|
|
523
|
+
return {k: v["median"] for k, v in fuel_provincia_stats(ds, min_n).items()}
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def in_italy(lat: float, lon: float) -> bool:
|
|
527
|
+
"""Whether a coordinate sits inside a generous Italy bounding box."""
|
|
528
|
+
return ITALY_BBOX[0] <= lat <= ITALY_BBOX[1] and ITALY_BBOX[2] <= lon <= ITALY_BBOX[3]
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def comune_centroids(ds: "Dataset", min_stations: int = 3) -> dict[str, tuple[float, float]]:
|
|
532
|
+
"""Median (lat, lon) per comune, only for comuni with at least `min_stations`
|
|
533
|
+
stations. The median resists individual mis-geocoded outliers."""
|
|
534
|
+
groups: dict[str, list[tuple[float, float]]] = {}
|
|
535
|
+
for st in ds.stations.values():
|
|
536
|
+
if not in_italy(st.lat, st.lon):
|
|
537
|
+
continue
|
|
538
|
+
groups.setdefault(st.comune.upper(), []).append((st.lat, st.lon))
|
|
539
|
+
return {
|
|
540
|
+
com: (statistics.median(p[0] for p in pts), statistics.median(p[1] for p in pts))
|
|
541
|
+
for com, pts in groups.items()
|
|
542
|
+
if len(pts) >= min_stations
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
547
|
+
r = 6371.0
|
|
548
|
+
d_lat = math.radians(lat2 - lat1)
|
|
549
|
+
d_lon = math.radians(lon2 - lon1)
|
|
550
|
+
a = (
|
|
551
|
+
math.sin(d_lat / 2) ** 2
|
|
552
|
+
+ math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(d_lon / 2) ** 2
|
|
553
|
+
)
|
|
554
|
+
return r * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def now_iso() -> str:
|
|
558
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _to_float(s: str, default: float | None = 0.0) -> float | None:
|
|
562
|
+
try:
|
|
563
|
+
return float(s.strip().replace(",", "."))
|
|
564
|
+
except (ValueError, AttributeError):
|
|
565
|
+
return default
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _normalize_ts(raw: str) -> str:
|
|
569
|
+
try:
|
|
570
|
+
return datetime.strptime(raw, "%d/%m/%Y %H:%M:%S").strftime("%Y-%m-%dT%H:%M:%S")
|
|
571
|
+
except ValueError:
|
|
572
|
+
return raw
|
pitstop/cpo_tariffs.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Curated registry of Italian EV charge-point operators (CPOs) → their
|
|
2
|
+
official tariff pages.
|
|
3
|
+
|
|
4
|
+
**Why this exists instead of per-station prices.** As of mid-2026:
|
|
5
|
+
- AFIR DATEX II is a CPO→NAP upload channel, not a consumer query API.
|
|
6
|
+
- Italy's PUN (piattaformaunicanazionale.it) is an ArcGIS SPA with no
|
|
7
|
+
documented public tariff endpoint.
|
|
8
|
+
- Chargeprice and Eco-Movement carry per-station tariffs but require paid
|
|
9
|
+
licenses.
|
|
10
|
+
- OSM tags `fee=yes/no` but not actual €/kWh.
|
|
11
|
+
|
|
12
|
+
So real per-station prices aren't free + open + machine-readable yet. The
|
|
13
|
+
honest thing pitstop can do today is surface the **operator's own tariff page**
|
|
14
|
+
so the agent / user can read authoritative numbers in one click."""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
# Keyed by normalized operator substring (lowercased). Lookup is by substring
|
|
19
|
+
# match against the station's `operator` tag, so minor naming differences
|
|
20
|
+
# (e.g. "Alperia Smart Mobility" vs "Alperia") still resolve.
|
|
21
|
+
TARIFF_URLS: dict[str, str] = {
|
|
22
|
+
"alperia": "https://www.alperia.eu/it/elettrica-ricarica.html",
|
|
23
|
+
"neogy": "https://www.neogy.it/it/ricarica-pubblica.html",
|
|
24
|
+
"enel x way": "https://www.enelxway.com/it/it/privati/ricaricare-elettrica/pubblica",
|
|
25
|
+
"enel x": "https://www.enelxway.com/it/it/privati/ricaricare-elettrica/pubblica",
|
|
26
|
+
"enel": "https://www.enelxway.com/it/it/privati/ricaricare-elettrica/pubblica",
|
|
27
|
+
"be charge": "https://www.be-charge.com/it/tariffe/",
|
|
28
|
+
"becharge": "https://www.be-charge.com/it/tariffe/",
|
|
29
|
+
"free to x": "https://www.freetox.com/tariffe/",
|
|
30
|
+
"freetox": "https://www.freetox.com/tariffe/",
|
|
31
|
+
"ionity": "https://ionity.eu/it/charging/network/pricing",
|
|
32
|
+
"tesla": "https://www.tesla.com/it_it/supercharger",
|
|
33
|
+
"plenitude": "https://eniplenitude.com/mobilita-elettrica",
|
|
34
|
+
"eni": "https://eniplenitude.com/mobilita-elettrica",
|
|
35
|
+
"atlante": "https://www.atlante.energy/",
|
|
36
|
+
"repower": "https://www.repower.com/it/clienti-business/e-mobility/",
|
|
37
|
+
"duferco": "https://www.duferco.it/it/duferco-energia/mobilita-elettrica.html",
|
|
38
|
+
"a2a": "https://www.a2aenergia.eu/casa/mobilita-elettrica",
|
|
39
|
+
"edison": "https://www.edisonenergia.it/edison/mobilita-elettrica",
|
|
40
|
+
"acea": "https://www.acea.it/clienti-acea-energia/mobilita-elettrica",
|
|
41
|
+
"evway": "https://www.evway.net/it/",
|
|
42
|
+
"ev-now": "https://www.ev-now.it/",
|
|
43
|
+
"movyon": "https://www.movyon.com/",
|
|
44
|
+
"bike-energy": "https://www.bike-energy.com/", # for e-bike chargers
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def lookup(operator: str) -> str | None:
|
|
49
|
+
"""Return the official tariff page URL for an operator, or None if unknown.
|
|
50
|
+
|
|
51
|
+
Substring match (case-insensitive) so naming variants resolve."""
|
|
52
|
+
if not operator:
|
|
53
|
+
return None
|
|
54
|
+
op = operator.strip().lower()
|
|
55
|
+
# Try exact-substring matches in order of decreasing key length so that
|
|
56
|
+
# "Enel X Way" wins over "Enel" when both would match.
|
|
57
|
+
for key in sorted(TARIFF_URLS.keys(), key=len, reverse=True):
|
|
58
|
+
if key in op:
|
|
59
|
+
return TARIFF_URLS[key]
|
|
60
|
+
return None
|