Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/recalls.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1813# Last Modified : 2026-08-1814#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# recalls.py : rappels de sécurité — Base de données des rappels de véhicules91# de Transports Canada (données ouvertes, gratuit)92#93# Source : dump mensuel complet CSV du jeu de données « Vehicle Recalls94# Database » (ouvert.canada.ca, jeu 1ec92326-47ef-4110-b7ca-959fab03f96d) :95# https://opendatatc.tc.canada.ca/vrdb_full_monthly.csv (~200 Mo)96# 1 ligne = 1 rappel × marque × modèle × année-modèle. L'API REST officielle97# (tc.api.canada.ca) exige une clé délivrée manuellement — le CSV ouvert est98# la voie sans clé, rafraîchi mensuellement par TC.99#100# Table `recalls` (make/model/year normalisés en MAJUSCULES sans accents) +101# croisement par (make, model, year) avec les annonces : le modèle TC est102# souvent plus court que le nôtre (« CIVIC » vs « Civic Sport Touring ») —103# on matche si l'un préfixe l'autre au premier mot près, année exacte.104#105# Peuplement one-shot / mensuel : python3 -m autoka.recalls [--limit-years N]106# -----------------------------------------------------------------------------107from __future__ import annotations108109import csv110import io111import sqlite3112import sys113import time114import unicodedata115116import requests117118CSV_URL = "https://opendatatc.tc.canada.ca/vrdb_full_monthly.csv"119120_SCHEMA = """121CREATE TABLE IF NOT EXISTS recalls (122 recall_number TEXT NOT NULL,123 make TEXT NOT NULL, -- MAJUSCULES sans accents (norme TC)124 model TEXT NOT NULL, -- MAJUSCULES sans accents (norme TC)125 year INTEGER, -- année-modèle visée126 date TEXT, -- date du rappel (YYYY-MM-DD)127 component TEXT, -- système visé (FR, repli EN)128 description TEXT, -- description (FR, repli EN)129 category TEXT, -- Car / Truck / Motorcycle... (norme TC)130 units_affected INTEGER,131 PRIMARY KEY (recall_number, make, model, year)132);133CREATE INDEX IF NOT EXISTS idx_recalls_mmy ON recalls(make, model, year);134"""135136# alias marques Auto-Ka -> marque TC quand l'orthographe diffère137_MAKE_ALIASES = {138 "MERCEDES-BENZ": ("MERCEDES-BENZ", "MERCEDES"),139 "LAND ROVER": ("LAND ROVER", "LANDROVER"),140 "VOLKSWAGEN": ("VOLKSWAGEN", "VW"),141 "CHEVROLET": ("CHEVROLET", "CHEV"),142 "MINI": ("MINI", "BMW MINI"),143}144145146def _norm(text: str | None) -> str:147 """MAJUSCULES sans accents, espaces réduits — clé de croisement."""148 if not text:149 return ""150 t = unicodedata.normalize("NFKD", text)151 t = "".join(c for c in t if not unicodedata.combining(c))152 return " ".join(t.upper().split())153154155def ensure_schema(con: sqlite3.Connection) -> None:156 con.executescript(_SCHEMA)157 con.commit()158159160# ---------------------------------------------------------------------------161# Peuplement depuis le dump CSV mensuel de Transports Canada162# ---------------------------------------------------------------------------163164def _fr_or_en(fr: str, en: str) -> str:165 fr = (fr or "").strip()166 if fr and fr.lower() not in ("translation not available", "non saisie"):167 return fr168 return (en or "").strip()169170171def populate(con: sqlite3.Connection, csv_path: str | None = None,172 min_year: int = 1980) -> dict:173 """(Re)charge la table depuis le dump complet (téléchargé si besoin).174175 `min_year` écarte les années-modèles antérieures au parc plausible176 d'Auto-Ka (schema.py borne les annonces à 1980+).177 """178 ensure_schema(con)179 t0 = time.time()180 if csv_path:181 fh = open(csv_path, encoding="utf-8", errors="replace", newline="")182 else:183 print(f"[auto-ka] rappels TC : téléchargement {CSV_URL} ...")184 resp = requests.get(CSV_URL, timeout=600)185 resp.raise_for_status()186 fh = io.StringIO(resp.content.decode("utf-8", errors="replace"))187188 con.execute("DELETE FROM recalls")189 n = kept = 0190 with fh:191 for row in csv.DictReader(fh):192 n += 1193 try:194 year = int(float(row.get("YEAR") or 0)) or None195 except ValueError:196 year = None197 if year is not None and year < min_year:198 continue199 make = _norm(row.get("MAKE_NAME_NM"))200 model = _norm(row.get("MODEL_NAME_NM"))201 if not make or not row.get("RECALL_NUMBER_NUM"):202 continue203 try:204 units = int(float((row.get("UNIT_AFFECTED_NBR") or "0")205 .replace(",", "")))206 except ValueError:207 units = 0208 con.execute(209 """INSERT OR REPLACE INTO recalls (recall_number, make, model,210 year, date, component, description, category, units_affected)211 VALUES (?,?,?,?,?,?,?,?,?)""",212 (row["RECALL_NUMBER_NUM"], make, model, year,213 (row.get("RECALL_DATE_DTE") or "")[:10],214 _fr_or_en(row.get("SYSTEM_TYPE_FTXT"), row.get("SYSTEM_TYPE_ETXT")),215 _fr_or_en(row.get("COMMENT_FTXT"), row.get("COMMENT_ETXT")),216 row.get("CATEGORY_ETXT") or "",217 units))218 kept += 1219 con.commit()220 total = con.execute("SELECT COUNT(*) c FROM recalls").fetchone()["c"]221 out = {"csv_rows": n, "kept": kept, "recalls_rows": total,222 "seconds": round(time.time() - t0, 1)}223 print(f"[auto-ka] rappels TC : {out}")224 return out225226227# ---------------------------------------------------------------------------228# Croisement avec une annonce (make/model/year normalisés)229# ---------------------------------------------------------------------------230231def for_vehicle(con: sqlite3.Connection, make: str, model: str,232 year: int | None, ensure: bool = True) -> list[dict]:233 """Rappels TC visant ce (marque, modèle, année) — année exacte requise.234235 Le modèle TC est générique (« CIVIC », « F-150 ») alors que le nôtre porte236 parfois la version ; on matche par préfixe dans les deux sens, ancré sur237 le premier mot pour éviter les faux positifs.238 """239 if not make or not model or year is None:240 return []241 if ensure:242 ensure_schema(con)243 n_make, n_model = _norm(make), _norm(model)244 makes = _MAKE_ALIASES.get(n_make, (n_make,))245 first_word = n_model.split()[0]246247 q = f"""SELECT recall_number, make, model, year, date, component,248 description, category, units_affected249 FROM recalls250 WHERE make IN ({','.join('?' * len(makes))}) AND year=?251 AND (model=? OR model LIKE ? OR ? LIKE model || ' %'252 OR (length(model) >= 3 AND ? LIKE model || '%'))253 ORDER BY date DESC"""254 rows = con.execute(q, (*makes, year, n_model, f"{first_word} %",255 n_model, first_word)).fetchall()256 seen: set[str] = set()257 out = []258 for r in rows:259 if r["recall_number"] in seen:260 continue261 seen.add(r["recall_number"])262 out.append(dict(r))263 return out264265266if __name__ == "__main__":267 from . import db268 con = db.connect()269 path = sys.argv[1] if len(sys.argv) > 1 else None270 populate(con, csv_path=path)271 con.close()272