#!/usr/bin/env python3 # benzina-abruzzo: prezzi carburanti Abruzzo dagli open data MIMIT. # Uso: app.py collect | serve [porta] [bind] | stats import csv import hashlib import datetime import io import json import math import mimetypes import os import sqlite3 import sys import threading import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse BASE = os.path.dirname(os.path.abspath(__file__)) DB = os.path.join(BASE, 'data', 'benzina.db') PAGE = os.path.join(BASE, 'index.html') STATIC = os.path.join(BASE, 'static') URL_ANA = 'https://www.mimit.gov.it/images/exportCSV/anagrafica_impianti_attivi.csv' URL_PRE = 'https://www.mimit.gov.it/images/exportCSV/prezzo_alle_8.csv' PROVINCE = ('AQ', 'CH', 'PE', 'TE') UA = {'User-Agent': 'Mozilla/5.0 (compatible; benzina-abruzzo/1.1)'} SCHEMA = [ '''CREATE TABLE IF NOT EXISTS stations( id INTEGER PRIMARY KEY, gestore TEXT, bandiera TEXT, tipo TEXT, nome TEXT, indirizzo TEXT, comune TEXT, provincia TEXT, lat REAL, lon REAL)''', '''CREATE TABLE IF NOT EXISTS prices( id INTEGER, carburante TEXT, prezzo REAL, self INTEGER, dt_comu TEXT, collected TEXT, PRIMARY KEY(id, carburante, self, collected))''', 'CREATE INDEX IF NOT EXISTS ix_prices ON prices(carburante, self, collected)', '''CREATE TABLE IF NOT EXISTS runs( collected TEXT PRIMARY KEY, source_date TEXT, stations INTEGER, prices INTEGER)''', ] def conn(): os.makedirs(os.path.dirname(DB), exist_ok=True) c = sqlite3.connect(DB, timeout=15) for stmt in SCHEMA: c.execute(stmt) return c def fetch(url): req = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(req, timeout=180) as r: return r.read().decode('utf-8', 'replace') def rows_of(text): lines = text.splitlines() src = '' if lines and 'Estrazione' in lines[0]: src = lines[0].replace('Estrazione del ', '').strip() body = '\n'.join(lines[1:]) return src, list(csv.DictReader(io.StringIO(body), delimiter='|')) def collect(): c = conn() src, ana = rows_of(fetch(URL_ANA)) _, pre = rows_of(fetch(URL_PRE)) now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') abruzzo = {} for r in ana: if (r.get('Provincia') or '').strip().upper() not in PROVINCE: continue try: i = int(r['idImpianto']) lat = float(r.get('Latitudine') or 0) lon = float(r.get('Longitudine') or 0) except (KeyError, ValueError, TypeError): continue abruzzo[i] = (r.get('Gestore', ''), r.get('Bandiera', ''), r.get('Tipo Impianto', ''), r.get('Nome Impianto', ''), r.get('Indirizzo', ''), r.get('Comune', ''), (r.get('Provincia') or '').strip().upper(), lat, lon) c.executemany('INSERT OR REPLACE INTO stations VALUES (?,?,?,?,?,?,?,?,?,?)', [(i,) + v for i, v in abruzzo.items()]) np = 0 for r in pre: try: i = int(r['idImpianto']) except (KeyError, ValueError, TypeError): continue if i not in abruzzo: continue try: pr = float((r.get('prezzo') or '').replace(',', '.')) except ValueError: continue if not (0.5 < pr < 4.0): continue c.execute('INSERT OR REPLACE INTO prices VALUES (?,?,?,?,?,?)', (i, (r.get('descCarburante') or '').strip(), pr, 1 if str(r.get('isSelf')).strip() in ('1', 'True', 'true') else 0, r.get('dtComu', ''), now)) np += 1 c.execute('INSERT OR REPLACE INTO runs VALUES (?,?,?,?)', (now, src, len(abruzzo), np)) c.commit() print('collected %s | fonte %s | impianti Abruzzo %d | prezzi %d' % (now, src, len(abruzzo), np)) return len(abruzzo), np def latest(c): return c.execute('SELECT MAX(collected) FROM prices').fetchone()[0] def meta(c): r = c.execute('SELECT collected, source_date FROM runs ORDER BY collected DESC LIMIT 1').fetchone() n = c.execute('SELECT COUNT(*) FROM stations').fetchone()[0] return {'aggiornato': r[0] if r else None, 'fonte': r[1] if r else None, 'impianti': n} def fuels(c): return [r[0] for r in c.execute( 'SELECT DISTINCT carburante FROM prices WHERE collected=? ORDER BY 1', (latest(c),))] def summary(c, fuel, self_only): sql = ('SELECT s.provincia, COUNT(*), MIN(p.prezzo), AVG(p.prezzo), MAX(p.prezzo) ' 'FROM prices p JOIN stations s ON s.id=p.id ' 'WHERE p.collected=? AND p.carburante=? ' + ('AND p.self=1 ' if self_only else '') + 'GROUP BY s.provincia ORDER BY s.provincia') return [{'provincia': r[0], 'impianti': r[1], 'min': round(r[2], 3), 'media': round(r[3], 3), 'max': round(r[4], 3)} for r in c.execute(sql, (latest(c), fuel))] def haversine(lat1, lon1, lat2, lon2): if not lat2 or not lon2: return None r = 6371.0 p1, p2 = math.radians(lat1), math.radians(lat2) dp = p2 - p1 dl = math.radians(lon2 - lon1) a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 return round(2 * r * math.asin(math.sqrt(a)), 2) def bandiere(c): return [{'bandiera': r[0], 'n': r[1]} for r in c.execute( 'SELECT bandiera, COUNT(*) FROM stations GROUP BY bandiera ORDER BY COUNT(*) DESC')] def comuni(c): return [{'comune': r[0], 'provincia': r[1], 'lat': round(r[2], 5), 'lon': round(r[3], 5), 'n': r[4]} for r in c.execute('''SELECT comune, provincia, AVG(lat), AVG(lon), COUNT(*) FROM stations WHERE lat<>0 GROUP BY comune, provincia ORDER BY comune''')] # ---------- cache ---------- # I prezzi MIMIT cambiano una volta al giorno: ricalcolare le stesse righe a # ogni caricamento e' lavoro sprecato. Teniamo le righe base in memoria per # PRICE_TTL secondi, chiave = (estrazione, carburante, self, provincia, bandiera). PRICE_TTL = 7200 _CACHE = {} _CACHE_LOCK = threading.Lock() def cache_get(key, ttl=None): t = ttl if ttl is not None else PRICE_TTL with _CACHE_LOCK: hit = _CACHE.get(key) if hit and (time.time() - hit[0]) < t: return hit[1] return None def cache_put(key, val): with _CACHE_LOCK: _CACHE[key] = (time.time(), val) if len(_CACHE) > 200: # anti-crescita: via le voci piu vecchie for k in sorted(_CACHE, key=lambda k: _CACHE[k][0])[:80]: _CACHE.pop(k, None) return val def cache_clear(): with _CACHE_LOCK: _CACHE.clear() def stations(c, fuel, self_only, provincia=None, bandiera=None): sql = ('SELECT s.id, s.bandiera, s.gestore, s.nome, s.indirizzo, s.comune, s.provincia, ' 's.tipo, p.prezzo, p.self, p.dt_comu, s.lat, s.lon ' 'FROM prices p JOIN stations s ON s.id=p.id ' 'WHERE p.collected=? AND p.carburante=? ' + ('AND p.self=1 ' if self_only else '') + ('AND s.provincia=? ' if provincia else '') + ('AND s.bandiera=? ' if bandiera else '') + 'ORDER BY p.prezzo ASC') lt = latest(c) args = [lt, fuel] if provincia: args.append(provincia) if bandiera: args.append(bandiera) by = {} for r in c.execute(sql, args): sid = r[0] rec = {'bandiera': r[1], 'gestore': r[2], 'nome': r[3], 'indirizzo': r[4], 'comune': r[5], 'provincia': r[6], 'tipo': r[7], 'dt': r[10], 'lat': r[11], 'lon': r[12], 'prezzi': {}} rec['prezzi']['self' if r[9] else 'servito'] = round(r[8], 3) if sid in by: by[sid]['prezzi'].update(rec['prezzi']) else: by[sid] = rec out = [] for sid, rec in by.items(): pz = rec.pop('prezzi') cheapest = min(pz.items(), key=lambda kv: kv[1]) rec['id'] = sid rec['prezzo'] = cheapest[1] rec['self'] = cheapest[0] == 'self' rec['p_self'] = pz.get('self') rec['p_serv'] = pz.get('servito') out.append(rec) out.sort(key=lambda r: r['prezzo']) return out def stations_cached(c, fuel, self_only, provincia=None, bandiera=None, lt=None): key = ('st', lt, fuel, self_only, provincia, bandiera) hit = cache_get(key) if hit is not None: return hit return cache_put(key, stations(c, fuel, self_only, provincia, bandiera)) def history(c, sid, fuel): return [{'t': r[0], 'p': round(r[1], 3)} for r in c.execute( 'SELECT collected, AVG(prezzo) FROM prices WHERE id=? AND carburante=? ' 'GROUP BY collected ORDER BY collected', (sid, fuel))] def station_detail(c, sid): '''Tutti i carburanti di un impianto, all'ultima estrazione disponibile. Serve al pannello di dettaglio: "cosa costa qui" in una schermata.''' st = c.execute('SELECT id, gestore, bandiera, tipo, nome, indirizzo, comune, ' 'provincia, lat, lon FROM stations WHERE id=?', (sid,)).fetchone() if not st: return None last = c.execute('SELECT MAX(collected) FROM prices WHERE id=?', (sid,)).fetchone()[0] rows = c.execute('SELECT carburante, self, prezzo, dt_comu FROM prices ' 'WHERE id=? AND collected=? ORDER BY carburante, self', (sid, last)).fetchall() fuels = {} for carb, selbst, prezzo, dt in rows: f = fuels.setdefault(carb, {'carburante': carb, 'servito': None, 'self': None, 'dt': dt}) if selbst: f['self'] = round(prezzo, 3) else: f['servito'] = round(prezzo, 3) return { 'id': st[0], 'gestore': st[1], 'bandiera': st[2], 'tipo': st[3], 'nome': st[4], 'indirizzo': st[5], 'comune': st[6], 'provincia': st[7], 'lat': st[8], 'lon': st[9], 'collected': last, 'fuels': sorted(fuels.values(), key=lambda f: f['carburante']), } def province_stats(c, fuel): return {s['provincia']: s for s in summary(c, fuel, False)} def stats(): c = conn() m = meta(c) print('fonte MIMIT: %s | raccolto: %s | impianti Abruzzo: %d' % (m['fonte'], m['aggiornato'], m['impianti'])) for f in fuels(c): print('\n' + f) for s in summary(c, f, False): print(' %s: min %.3f media %.3f max %.3f (%d impianti)' % (s['provincia'], s['min'], s['media'], s['max'], s['impianti'])) class Handler(BaseHTTPRequestHandler): server_version = 'benzina-abruzzo/1.1' def log_message(self, *a): pass def send(self, code, body, ctype='application/json; charset=utf-8', extra=None): import gzip as _gzip b = body.encode('utf-8') if isinstance(body, str) else body extra = dict(extra or {}) if 'Cache-Control' not in extra: extra['Cache-Control'] = 'no-store' ae = self.headers.get('Accept-Encoding', '') or '' compressible = ('json' in ctype or 'javascript' in ctype or 'css' in ctype or 'text/' in ctype or 'svg' in ctype) if compressible and 'gzip' in ae and len(b) > 1400: b = _gzip.compress(b, 6) extra['Content-Encoding'] = 'gzip' extra['Vary'] = 'Accept-Encoding' self.send_response(code) self.send_header('Content-Type', ctype) self.send_header('Content-Length', str(len(b))) self.send_header('Permissions-Policy', 'geolocation=(self)') for k, v in extra.items(): self.send_header(k, v) self.end_headers() try: self.wfile.write(b) except (BrokenPipeError, ConnectionResetError): pass def serve_file(self, path): if not os.path.isfile(path): return self.send(404, json.dumps({'error': 'not found'})) ctype = mimetypes.guess_type(path)[0] or 'application/octet-stream' if path.endswith('.webmanifest'): ctype = 'application/manifest+json' if path.endswith('.pmtiles'): ctype = 'application/vnd.pmtiles' fname = os.path.basename(path) cache = 'public, max-age=86400' if path == PAGE or path.endswith('sw.js'): cache = 'no-cache' elif fname in ('index.html',): cache = 'no-cache' if path.endswith('.pmtiles'): cache = 'public, max-age=604800, immutable' size = os.path.getsize(path) # --- Range requests: indispensabili per PMTiles (lettura a blocchi) --- rng = self.headers.get('Range') start, end = 0, size - 1 partial = False if rng and rng.startswith('bytes='): try: spec = rng.split('=', 1)[1].split(',')[0].strip() a_, _, b_ = spec.partition('-') if a_: start = int(a_) if b_: end = int(b_) elif b_: start = max(0, size - int(b_)) end = min(end, size - 1) if start > end or start >= size: self.send_response(416) self.send_header('Content-Range', 'bytes */%d' % size) self.send_header('Content-Length', '0') self.end_headers() return partial = True except Exception: start, end, partial = 0, size - 1, False length = end - start + 1 self.send_response(206 if partial else 200) self.send_header('Content-Type', ctype) self.send_header('Content-Length', str(length)) self.send_header('Cache-Control', cache) self.send_header('Accept-Ranges', 'bytes') self.send_header('Permissions-Policy', 'geolocation=(self)') if partial: self.send_header('Content-Range', 'bytes %d-%d/%d' % (start, end, size)) self.end_headers() remaining = length with open(path, 'rb') as f: f.seek(start) while remaining > 0: chunk = f.read(min(65536, remaining)) if not chunk: break try: self.wfile.write(chunk) except (BrokenPipeError, ConnectionResetError): return remaining -= len(chunk) def api_data(self, c, g): lt = latest(c) fuel = g('carburante', 'Benzina') prov = (g('provincia') or '').upper() or None self_only = g('self', '0') == '1' band = g('bandiera') or None try: ulat = float(g('lat')) if g('lat') else None ulon = float(g('lon')) if g('lon') else None except ValueError: ulat = ulon = None sort = g('sort', 'price') try: tank = float(g('tank', '50') or 50) except ValueError: tank = 50.0 try: cons = float((g('cons', '5.8') or '5.8').replace(',', '.')) except ValueError: cons = 5.8 lim = int(g('limit', '800') or 800) # 1) righe base in cache per 2 ore (dipendono dall'estrazione) rows = stations_cached(c, fuel, self_only, prov, band, lt) # 2) risposta gia' calcolata per questa combinazione esatta lat_r = round(ulat, 3) if ulat is not None else None lon_r = round(ulon, 3) if ulon is not None else None rkey = ('resp', lt, fuel, self_only, prov, band, sort, lat_r, lon_r, round(tank, 1), round(cons, 2), lim) cached = cache_get(rkey) if cached is not None: body, etag = cached inm = self.headers.get('If-None-Match') if inm and inm == etag: self.send_response(304) self.send_header('ETag', etag) self.send_header('Cache-Control', 'public, max-age=600') self.end_headers() return return self.send(200, body, extra={ 'Cache-Control': 'public, max-age=600, stale-while-revalidate=3600', 'ETag': etag}) # 3) calcolo (copia, per non sporcare la cache con km/costi) rows = [dict(r) for r in rows] if ulat is not None and ulon is not None: for r in rows: r['km'] = haversine(ulat, ulon, r['lat'], r['lon']) if sort == 'dist' and ulat is not None: rows.sort(key=lambda r: (r['km'] if r['km'] is not None else 9999, r['prezzo'])) elif sort == 'value' and ulat is not None: for r in rows: k = r['km'] or 0 litres = min(k, 60) * 2 * cons / 100.0 r['costo_pieno'] = round(r['prezzo'] * tank, 2) r['costo_viaggio'] = round(litres * r['prezzo'], 2) r['costo_totale'] = round(r['costo_pieno'] + r['costo_viaggio'], 2) rows.sort(key=lambda r: r['costo_totale']) body = json.dumps({ 'meta': meta(c), 'carburante': fuel, 'self': self_only, 'summary': summary(c, fuel, self_only), 'user': {'lat': ulat, 'lon': ulon}, 'cheapest': rows[:lim]}) etag = '"%s"' % hashlib.md5(body.encode('utf-8')).hexdigest()[:16] cache_put(rkey, (body, etag)) return self.send(200, body, extra={ 'Cache-Control': 'public, max-age=600, stale-while-revalidate=3600', 'ETag': etag}) def do_GET(self): u = urlparse(self.path) qs = parse_qs(u.query) def g(k, d=None): return (qs.get(k) or [d])[0] try: if u.path in ('/', '/index.html'): return self.serve_file(PAGE) if u.path.startswith('/static/'): safe = os.path.normpath(u.path.lstrip('/')) if not safe.startswith('static'): return self.send(403, json.dumps({'error': 'forbidden'})) return self.serve_file(os.path.join(BASE, safe)) if u.path == '/healthz': return self.send(200, json.dumps({'status': 'ok'})) c = conn() if u.path == '/api/meta': mk = ('meta', latest(c), g('carburante', 'Benzina')) hitc = cache_get(mk) if hitc is None: hitc = cache_put(mk, json.dumps({ 'meta': meta(c), 'carburanti': fuels(c), 'province': list(PROVINCE), 'province_stats': province_stats(c, g('carburante', 'Benzina')), 'bandiere': bandiere(c)})) return self.send(200, hitc, extra={ 'Cache-Control': 'public, max-age=1800, stale-while-revalidate=7200'}) if u.path == '/api/data': return self.api_data(c, g) if u.path == '/api/comuni': ck = ('comuni',) hitc = cache_get(ck, 86400) if hitc is None: hitc = cache_put(ck, json.dumps(comuni(c))) return self.send(200, hitc, extra={ 'Cache-Control': 'public, max-age=86400'}) if u.path == '/api/station': sid = int(g('id', '0')) ck = ('station', sid) hitc = cache_get(ck, 7200) if hitc is None: d = station_detail(c, sid) if d is None: return self.send(404, json.dumps({'error': 'impianto sconosciuto'})) hitc = cache_put(ck, json.dumps(d)) return self.send(200, hitc, extra={ 'Cache-Control': 'public, max-age=1800, stale-while-revalidate=7200'}) if u.path == '/api/history': return self.send(200, json.dumps(history(c, int(g('id', '0')), g('carburante', 'Benzina')))) return self.send(404, json.dumps({'error': 'not found'})) except Exception as e: return self.send(500, json.dumps({'error': str(e)})) def serve(port=2590, bind='172.18.0.1'): ThreadingHTTPServer.allow_reuse_address = True with ThreadingHTTPServer((bind, port), Handler) as httpd: print('benzina-abruzzo su %s:%d' % (bind, port), flush=True) httpd.serve_forever() if __name__ == '__main__': cmd = sys.argv[1] if len(sys.argv) > 1 else 'stats' if cmd == 'collect': collect() elif cmd == 'serve': serve(int(sys.argv[2]) if len(sys.argv) > 2 else 2590, sys.argv[3] if len(sys.argv) > 3 else '172.18.0.1') else: stats()