Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/dealers.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# dealers.py : coordonnées des concessionnaires (adresse, téléphone, GPS)91#92# 1 source = 1 site de concessionnaire (sauf portails/marketplaces) : on93# visite UNE page par site (l'accueil suffit — l'adresse et le téléphone94# sont dans l'en-tête/le pied de page, et la plupart des plateformes (D2C,95# SM360, Convertus…) émettent un JSON-LD AutoDealer/LocalBusiness complet).96# Extraction : JSON-LD d'abord (address/telephone/geo), replis regex97# (lien tel:, adresse avec code postal canadien). GPS par défaut : centre98# de la ville de la source (data/villes_gps.json).99#100# Budget : ~138 requêtes UNE fois (cache en base — on ne re-visite que les101# sources absentes de la table), throttle 1 s.102#103# One-shot : python3 -m autoka.dealers [--refresh]104# -----------------------------------------------------------------------------105from __future__ import annotations106107import json108import re109import sqlite3110import time111from pathlib import Path112113import requests114115from .normalize import city_gps116117SOURCES_PATH = Path(__file__).resolve().parent.parent / "data" / "sources.json"118119USER_AGENT = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "120 "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36 "121 "AutoKaBot/1.0 (+contact@spboucher.ai)")122123_SCHEMA = """124CREATE TABLE IF NOT EXISTS dealers (125 source TEXT PRIMARY KEY, -- id de la source (data/sources.json)126 name TEXT,127 address TEXT,128 phone TEXT,129 website TEXT,130 city TEXT,131 lat REAL,132 lng REAL,133 fetched_at REAL134);135"""136137_LD_RE = re.compile(138 r'<script[^>]*type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', re.S)139_TEL_RE = re.compile(r'href=["\']tel:([+\d][\d\s().\-]{6,18}\d)["\']', re.I)140# « 123 rue Untel, Ville (QC) J0X 1A0 » — ancré sur le code postal canadien141# (MAJUSCULES obligatoires et ; : # { } exclus : évite les couleurs hex et142# variables CSS inline des thèmes D2C qui imitent le motif postal)143_ADDR_RE = re.compile(144 r"(\d{1,5}[^<>{}|;:#\n]{5,90}?\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b)")145_STYLE_RE = re.compile(r"<(style|script)[^>]*>.*?</\1>", re.S | re.I)146_PHONE_TXT_RE = re.compile(r"(?<!\d)(\(?[2-9]\d{2}\)?[\s.\-]\d{3}[\s.\-]\d{4})(?!\d)")147148_DEALER_LD_TYPES = {"AutoDealer", "AutomotiveBusiness", "LocalBusiness",149 "MotorcycleDealer", "Organization", "AutoRepair", "Store"}150151152def ensure_schema(con: sqlite3.Connection) -> None:153 con.executescript(_SCHEMA)154 con.commit()155156157def _iter_ld(html: str):158 for blob in _LD_RE.findall(html):159 try:160 data = json.loads(blob.strip())161 except ValueError:162 continue163 stack = data if isinstance(data, list) else [data]164 for item in stack:165 if isinstance(item, dict):166 yield from _flatten_ld(item)167168169def _flatten_ld(item: dict):170 yield item171 for v in item.get("@graph", []) if isinstance(item.get("@graph"), list) else []:172 if isinstance(v, dict):173 yield v174175176def _fmt_address(addr) -> str:177 if isinstance(addr, str):178 return " ".join(addr.split())179 if isinstance(addr, dict):180 parts = [addr.get("streetAddress"), addr.get("addressLocality"),181 addr.get("addressRegion"), addr.get("postalCode")]182 return ", ".join(str(p).strip() for p in parts if p)183 return ""184185186def _clean_phone(raw: str) -> str:187 digits = re.sub(r"\D", "", raw or "")188 if digits.startswith("1") and len(digits) == 11:189 digits = digits[1:]190 if len(digits) != 10:191 return (raw or "").strip()192 return f"({digits[0:3]}) {digits[3:6]}-{digits[6:]}"193194195def _extract(html: str) -> dict:196 """address / phone / lat / lng depuis une page HTML de concessionnaire."""197 out: dict = {}198 for item in _iter_ld(html):199 types = item.get("@type") or ""200 types = {types} if isinstance(types, str) else set(types)201 if not (types & _DEALER_LD_TYPES):202 continue203 if not out.get("address") and item.get("address"):204 out["address"] = _fmt_address(item["address"])205 if not out.get("phone") and item.get("telephone"):206 out["phone"] = _clean_phone(str(item["telephone"]))207 geo = item.get("geo") or {}208 if isinstance(geo, dict) and not out.get("lat"):209 try:210 lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))211 if 44.0 <= lat <= 63.0 and -80.0 <= lng <= -57.0: # Québec212 out["lat"], out["lng"] = lat, lng213 except (TypeError, ValueError):214 pass215 if out.get("address") and out.get("phone"):216 break217 if not out.get("phone"):218 m = _TEL_RE.search(html) or _PHONE_TXT_RE.search(html)219 if m:220 out["phone"] = _clean_phone(m.group(1))221 if not out.get("address"):222 text = re.sub(r"<[^>]+>", " ", _STYLE_RE.sub(" ", html))223 m = _ADDR_RE.search(text)224 # garde-fou : une vraie adresse contient un mot (rue, boul., ville…)225 if m and re.search(r"[A-Za-zÀ-ÿ]{3,}", m.group(1)):226 out["address"] = " ".join(m.group(1).split())227 return out228229230def populate(con: sqlite3.Connection, refresh: bool = False,231 delay: float = 1.0) -> dict:232 """Peuple la table dealers — 1 requête par source manquante, throttle 1 s."""233 ensure_schema(con)234 registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]235 have = {r["source"] for r in con.execute("SELECT source FROM dealers")}236 session = requests.Session()237 session.headers["User-Agent"] = USER_AGENT238 fetched = filled_addr = filled_phone = errors = 0239 for s in registry:240 sid = s["id"]241 if s.get("type") == "marketplace": # Kijiji : pas un concessionnaire242 continue243 if sid in have and not refresh:244 continue245 info: dict = {}246 try:247 resp = session.get(s["url"], timeout=25)248 resp.raise_for_status()249 info = _extract(resp.text)250 fetched += 1251 except Exception as exc:252 errors += 1253 print(f"[auto-ka] dealers : {sid} — {exc}")254 gps = (info.get("lat"), info.get("lng"))255 if gps[0] is None or gps[1] is None:256 hit = city_gps(s.get("city"))257 gps = hit if hit else (None, None)258 con.execute(259 """INSERT INTO dealers (source, name, address, phone, website,260 city, lat, lng, fetched_at) VALUES (?,?,?,?,?,?,?,?,?)261 ON CONFLICT(source) DO UPDATE SET name=excluded.name,262 address=excluded.address, phone=excluded.phone,263 website=excluded.website, city=excluded.city,264 lat=excluded.lat, lng=excluded.lng,265 fetched_at=excluded.fetched_at""",266 (sid, s.get("name", sid), info.get("address", ""),267 info.get("phone", ""), s["url"], s.get("city", ""),268 gps[0], gps[1], time.time()))269 con.commit()270 if info.get("address"):271 filled_addr += 1272 if info.get("phone"):273 filled_phone += 1274 time.sleep(delay)275 total = con.execute("SELECT COUNT(*) c FROM dealers").fetchone()["c"]276 out = {"fetched": fetched, "errors": errors, "with_address": filled_addr,277 "with_phone": filled_phone, "dealers_total": total}278 print(f"[auto-ka] dealers : {out}")279 return out280281282def list_dealers(con: sqlite3.Connection) -> list[dict]:283 ensure_schema(con)284 counts = {r["source"]: r["n"] for r in con.execute(285 "SELECT source, COUNT(*) n FROM vehicles WHERE active=1 GROUP BY source")}286 rows = [dict(r) for r in con.execute(287 "SELECT * FROM dealers ORDER BY name COLLATE NOCASE")]288 for r in rows:289 r["active_listings"] = counts.get(r["source"], 0)290 return rows291292293if __name__ == "__main__":294 import sys295 from . import db296 con = db.connect()297 populate(con, refresh="--refresh" in sys.argv)298 con.close()299