SPB Git

Repository Public

vindecode.py 11.0 KB 287 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/vindecode.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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# Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# vindecode.py : fiche technique constructeur via le VIN — API vPIC de la NHTSA91#                (gratuite, sans clé), décodage paresseux + cache SQLite.92# -----------------------------------------------------------------------------93from __future__ import annotations9495import json96import sqlite397import time9899import requests100101VPIC_URL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/"102TIMEOUT = 12103104# Champs vPIC retenus → libellé français affiché sur la fiche.105# L'ordre du dict = l'ordre d'affichage.106_FIELDS: dict[str, str] = {107    "Trim": "Version (usine)",108    "Series": "Série",109    "BodyClass": "Carrosserie (usine)",110    "DriveType": "Motricité (usine)",111    "EngineCylinders": "Cylindres",112    "DisplacementL": "Cylindrée (L)",113    "EngineHP": "Puissance (ch)",114    "EngineConfiguration": "Configuration moteur",115    "FuelTypePrimary": "Carburant (usine)",116    "FuelTypeSecondary": "Carburant secondaire",117    "ElectrificationLevel": "Électrification",118    "BatteryKWh": "Batterie (kWh)",119    "TransmissionStyle": "Transmission (usine)",120    "TransmissionSpeeds": "Rapports",121    "Turbo": "Turbo",122    "Doors": "Portes (usine)",123    "Seats": "Places (usine)",124    "GVWR": "PNBV",125    "PlantCountry": "Pays d'assemblage",126    "PlantCity": "Ville d'assemblage",127    "ABS": "Freins ABS",128    "AirBagLocFront": "Coussins avant",129    "AirBagLocSide": "Coussins latéraux",130    "AirBagLocCurtain": "Coussins rideaux",131    "TPMS": "Surveillance pneus (TPMS)",132    "AdaptiveCruiseControl": "Régulateur adaptatif",133    "ForwardCollisionWarning": "Alerte de collision avant",134    "LaneDepartureWarning": "Alerte de sortie de voie",135    "BlindSpotMon": "Surveillance angles morts",136    "RearVisibilitySystem": "Caméra de recul",137}138139# Traductions des valeurs vPIC les plus fréquentes (anglais → français).140_VALUES_FR: dict[str, str] = {141    "Gasoline": "Essence", "Diesel": "Diesel", "Electric": "Électrique",142    "Sedan/Saloon": "Berline", "Hatchback/Liftback/Notchback": "Hayon",143    "Sport Utility Vehicle (SUV)/Multi-Purpose Vehicle (MPV)": "VUS",144    "Sport Utility Vehicle [SUV]/Multipurpose Vehicle [MPV]": "VUS",145    "Crossover Utility Vehicle (CUV)": "VUS multisegment",146    "Pickup": "Camionnette", "Minivan": "Minifourgonnette",147    "Coupe": "Coupé", "Convertible/Cabriolet": "Cabriolet", "Wagon": "Familiale",148    "4WD/4-Wheel Drive/4x4": "4x4", "AWD/All-Wheel Drive": "Intégrale (AWD)",149    "FWD/Front-Wheel Drive": "Traction (FWD)",150    "RWD/Rear-Wheel Drive": "Propulsion (RWD)",151    "Automatic": "Automatique", "Manual/Standard": "Manuelle",152    "Continuously Variable Transmission (CVT)": "CVT",153    "Automated Manual Transmission (AMT)": "Manuelle automatisée",154    "Dual-Clutch Transmission (DCT)": "Double embrayage (DCT)",155    "Strong HEV (Hybrid Electric Vehicle)": "Hybride",156    "Mild HEV (Hybrid Electric Vehicle)": "Hybride légère",157    "PHEV (Plug-in Hybrid Electric Vehicle)": "Hybride rechargeable",158    "BEV (Battery Electric Vehicle)": "100 % électrique",159    "Standard": "De série", "Optional": "En option", "Yes": "Oui", "No": "Non",160    "Direct": "Directe (TPMS direct)", "Indirect": "Indirecte",161    "1st Row (Driver and Passenger)": "1re rangée (conducteur et passager)",162    "1st and 2nd Rows": "1re et 2e rangées",163    "1st, 2nd and 3rd Rows": "1re, 2e et 3e rangées",164    "All Rows": "Toutes les rangées",165    "UNITED STATES (USA)": "États-Unis", "CANADA": "Canada", "MEXICO": "Mexique",166    "JAPAN": "Japon", "GERMANY": "Allemagne", "SOUTH KOREA": "Corée du Sud",167    "V-Shaped": "En V", "In-Line": "En ligne", "Horizontally opposed (boxer)": "Boxer",168}169170_SCHEMA = """171CREATE TABLE IF NOT EXISTS vin_decode (172    vin        TEXT PRIMARY KEY,173    data       TEXT,      -- JSON {libellé fr: valeur} (vide = décodage sans résultat)174    fetched_at REAL175);176"""177178179def _ensure(con: sqlite3.Connection) -> None:180    con.executescript(_SCHEMA)181182183def _fr(value: str) -> str:184    return _VALUES_FR.get(value, value)185186187def _extract(raw: dict) -> dict[str, str]:188    out: dict[str, str] = {}189    for key, label in _FIELDS.items():190        val = (raw.get(key) or "").strip()191        if not val or val.lower() in ("not applicable", "n/a", "0"):192            continue193        out[label] = _fr(val)194    return out195196197def decode(con: sqlite3.Connection, vin: str) -> dict[str, str] | None:198    """Fiche constructeur d'un VIN (cache DB, appel réseau au premier accès).199200    Retourne un dict {libellé fr: valeur} ou None si indisponible.201    """202    vin = (vin or "").strip().upper()203    if len(vin) != 17:204        return None205    _ensure(con)206    row = con.execute("SELECT data FROM vin_decode WHERE vin=?", (vin,)).fetchone()207    if row is not None:208        try:209            data = json.loads(row["data"] or "{}")210        except ValueError:211            data = {}212        return data or None213    try:214        resp = requests.post(VPIC_URL, data={"format": "json", "data": vin},215                             timeout=TIMEOUT)216        resp.raise_for_status()217        results = resp.json().get("Results") or []218        data = _extract(results[0]) if results else {}219    except Exception:220        # échec réseau : ne pas mettre en cache, on retentera au prochain accès221        return None222    con.execute(223        "INSERT OR REPLACE INTO vin_decode (vin, data, fetched_at) VALUES (?,?,?)",224        (vin, json.dumps(data, ensure_ascii=False), time.time()))225    con.commit()226    return data or None227228229# ---------------------------------------------------------------------------230# v2 : lecture du cache historique (base partagée, lecture seule), écriture231# des nouveaux décodages dans la base de caches de la v2.232# ---------------------------------------------------------------------------233234def decode_v2(vin: str, reseau: bool = True) -> dict[str, str] | None:235    """Fiche constructeur d'un NIV. `reseau=False` : cache seulement (None si236    le NIV n'a jamais été décodé)."""237    from . import db238    vin = (vin or "").strip().upper()239    if len(vin) != 17:240        return None241    for ouvre in (db.connect_cache, db.connect_ro):242        con = ouvre()243        try:244            row = con.execute("SELECT data FROM vin_decode WHERE vin=?", (vin,)).fetchone()245        except sqlite3.Error:246            row = None247        finally:248            con.close()249        if row is not None:250            try:251                return json.loads(row["data"] or "{}") or None252            except ValueError:253                return None254    if not reseau:255        return None256    try:257        resp = requests.post(VPIC_URL, data={"format": "json", "data": vin},258                             timeout=TIMEOUT)259        resp.raise_for_status()260        results = resp.json().get("Results") or []261        data = _extract(results[0]) if results else {}262    except Exception:263        return None264    con = db.connect_cache()265    try:266        con.execute("INSERT OR REPLACE INTO vin_decode (vin, data, fetched_at)"267                    " VALUES (?,?,?)", (vin, json.dumps(data, ensure_ascii=False), time.time()))268        con.commit()269    finally:270        con.close()271    return data or None272273274def en_cache(vin: str) -> bool:275    from . import db276    vin = (vin or "").strip().upper()277    for ouvre in (db.connect_cache, db.connect_ro):278        con = ouvre()279        try:280            if con.execute("SELECT 1 FROM vin_decode WHERE vin=?", (vin,)).fetchone():281                return True282        except sqlite3.Error:283            pass284        finally:285            con.close()286    return False287
Files main
Menu

Theme