SPB Git

Repository Public

gaz.py 8.7 KB 214 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/gaz.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2313# Last Modified    : 2026-09-0414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# gaz.py : stations-service à proximité et prix de l'essence — gazquebec.ca91#92#   gazquebec.ca expose un GeoJSON public de ~2 450 stations du Québec avec93#   les prix courants par carburant (Régulier / Super / Diesel). On garde une94#   copie locale (data/gaz.db) rafraîchie automatiquement au plus toutes les95#   4 h ; `nearby(lat, lng)` retourne les stations les plus proches avec96#   leurs prix et la médiane du rayon pour situer chaque prix.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import json101import math102import sqlite3103import time104import urllib.request105from pathlib import Path106from statistics import median107108DB_PATH = Path(__file__).resolve().parent.parent / "data" / "gaz.db"109API = "https://gazquebec.ca/api/stations"110UA = "LouKaBot/1.0 (+https://www.lou-ka.com; contact@spboucher.ai)"111TTL = 4 * 3600                      # fraîcheur maximale de la copie locale112113114def _connect() -> sqlite3.Connection:115    DB_PATH.parent.mkdir(parents=True, exist_ok=True)116    con = sqlite3.connect(DB_PATH, timeout=15)117    con.row_factory = sqlite3.Row118    con.executescript("""119        CREATE TABLE IF NOT EXISTS gaz_stations (120            id INTEGER PRIMARY KEY, nom TEXT, banniere TEXT, adresse TEXT,121            region TEXT, lat REAL, lng REAL,122            prix_regulier REAL, prix_super REAL, prix_diesel REAL);123        CREATE INDEX IF NOT EXISTS idx_gaz_latlng ON gaz_stations (lat, lng);124        CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v);125    """)126    return con127128129def refresh(con: sqlite3.Connection | None = None) -> int:130    """Télécharge le GeoJSON des stations et remplace la copie locale."""131    own = con is None132    con = con or _connect()133    req = urllib.request.Request(API, headers={"User-Agent": UA})134    with urllib.request.urlopen(req, timeout=60) as r:135        data = json.load(r)136    rows = []137    for f in data.get("features", []):138        try:139            lng, lat = f["geometry"]["coordinates"][:2]140        except (KeyError, TypeError, ValueError):141            continue142        p = f.get("properties") or {}143        prix = {"Régulier": None, "Super": None, "Diesel": None}144        try:145            for e in json.loads(p.get("allPrices") or "[]"):146                if e.get("fuelType") in prix and e.get("priceCents"):147                    prix[e["fuelType"]] = e["priceCents"] / 10.0   # ¢/L148        except ValueError:149            pass150        rows.append((p.get("id"), p.get("name"), p.get("brand"),151                     p.get("address"), p.get("region"), lat, lng,152                     prix["Régulier"], prix["Super"], prix["Diesel"]))153    with con:154        con.execute("DELETE FROM gaz_stations")155        con.executemany(156            "INSERT OR REPLACE INTO gaz_stations VALUES (?,?,?,?,?,?,?,?,?,?)",157            rows)158        con.execute("INSERT OR REPLACE INTO meta VALUES ('maj', ?)",159                    (time.time(),))160    if own:161        con.close()162    return len(rows)163164165def _dist_m(lat1, lng1, lat2, lng2) -> float:166    dlat = math.radians(lat2 - lat1)167    dlng = math.radians(lng2 - lng1)168    a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1))169         * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2)170    return 6371000 * 2 * math.asin(math.sqrt(a))171172173def nearby(lat: float, lng: float, radius_m: int = 5000,174           limit: int = 5) -> dict:175    """Stations les plus proches + médiane du prix Régulier dans le rayon."""176    con = _connect()177    row = con.execute("SELECT v FROM meta WHERE k='maj'").fetchone()178    if row is None or time.time() - float(row["v"]) > TTL:179        try:180            refresh(con)181        except Exception:182            pass                     # copie périmée mieux que rien183    d = radius_m / 111320.0184    dl = d / max(0.2, math.cos(math.radians(lat)))185    rows = con.execute(186        "SELECT * FROM gaz_stations WHERE lat BETWEEN ? AND ? "187        "AND lng BETWEEN ? AND ?",188        (lat - d, lat + d, lng - dl, lng + dl)).fetchall()189    maj = con.execute("SELECT v FROM meta WHERE k='maj'").fetchone()190    con.close()191    hits = []192    for r in rows:193        dist = _dist_m(lat, lng, r["lat"], r["lng"])194        if dist <= radius_m:195            hits.append((dist, r))196    hits.sort(key=lambda t: t[0])197    regs = [r["prix_regulier"] for _, r in hits if r["prix_regulier"]]198    med = round(median(regs), 1) if len(regs) >= 3 else None199    mini = round(min(regs), 1) if regs else None200    items = [{"nom": r["banniere"] or r["nom"], "adresse": r["adresse"],201              "dist_m": round(dist),202              # position (2026-09-04) : filtre « Essence » de la carte de la fiche203              "lat": r["lat"], "lng": r["lng"],204              "regulier": r["prix_regulier"], "super": r["prix_super"],205              "diesel": r["prix_diesel"],206              "moins_chere": bool(r["prix_regulier"] and mini207                                  and r["prix_regulier"] <= mini)}208             for dist, r in hits[:limit]]209    return {"n": len(hits), "rayon_m": radius_m, "mediane_regulier": med,210            "min_regulier": mini, "stations": items,211            "maj": time.strftime("%Y-%m-%d %H:%M",212                                 time.localtime(float(maj["v"])))213                   if maj else None}214
Files main
Menu

Theme