Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/jlkauto.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1214#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# connectors/jlkauto.py : JLK Auto (Montréal) — plateforme EDealer91# (edealer.ca ; WordPress + inventaire EDealer, CDN media.edealer.ca).92#93# Stratégie : le sitemap Yoast `/inventory-listing-sitemap.xml` recense les94# pages véhicule (…-<token>vdp/) en FR et EN. Chaque page détail (VDP)95# expose un JSON-LD schema.org @graph avec un nœud @type [Product, Car]96# complet : prix, VIN, km, transmission, carrosserie, couleurs, moteur.97# Pages détail mises en cache BD (clé hebdomadaire), comme les sites D2C.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import datetime102import json103import os104import re105106from ..schema import Vehicle107from .base import BaseConnector108109# …/inventaire/2005-chrysler-crossfire-limitee-jGKAbGVgRXus0SSkyI35kgvdp/110# le token (id EDealer) est le dernier segment alphanumérique SANS tiret :111# le même véhicule a un slug différent en FR et en EN, mais le même token112_VDP_RE = re.compile(r"-([A-Za-z0-9]{12,})vdp/?$")113114_LD_RE = re.compile(115 r'<script type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', re.S)116117_DRIVE_MAP = {118 "FrontWheelDriveConfiguration": "Traction",119 "RearWheelDriveConfiguration": "Propulsion",120 "AllWheelDriveConfiguration": "Intégrale / 4x4",121 "FourWheelDriveConfiguration": "Intégrale / 4x4",122}123124125def _qty(node) -> float | None:126 """QuantitativeValue -> float ; accepte aussi un scalaire nu."""127 value = node.get("value") if isinstance(node, dict) else node128 try:129 v = float(value)130 return v if v > 0 else None131 except (TypeError, ValueError):132 return None133134135class JLKAuto(BaseConnector):136 source_id = "jlkauto"137 base_url = "https://www.jlkauto.ca"138 dealer_name = "JLK Auto"139 city = "Montréal"140 request_delay: float = 1.0141 max_details = 400142143 # -- sitemap ----------------------------------------------------------------144 def _vehicle_urls(self) -> list[str]:145 xml = self.get(f"{self.base_url}/inventory-listing-sitemap.xml").text146 by_token: dict[str, str] = {}147 for loc in re.findall(r"<loc>([^<]+)</loc>", xml):148 loc = loc.strip()149 m = _VDP_RE.search(loc)150 if not m:151 continue # pages listes (…vlp) et autres152 token = m.group(1)153 # préférer la page FR (/inventaire/) à la page EN (/inventory/)154 if token not in by_token or "/inventaire/" in loc:155 by_token[token] = loc156 return [by_token[t] for t in sorted(by_token)]157158 # -- page détail -> nœud JSON-LD [Product, Car] ------------------------------159 def _fetch_detail(self, url: str) -> dict:160 html = self.get(url).text161 for block in _LD_RE.findall(html):162 try:163 data = json.loads(block.strip())164 except ValueError:165 continue166 nodes = data.get("@graph") if isinstance(data, dict) else None167 if nodes is None:168 nodes = data if isinstance(data, list) else [data]169 for node in nodes:170 types = node.get("@type")171 types = types if isinstance(types, list) else [types]172 if "Car" in types or "Vehicle" in types:173 # galerie complète depuis le CDN EDealer (JSON-LD n'a174 # qu'une photo)175 imgs = re.findall(176 r'https://media\.edealer\.ca/[^"\'\\\s]+\.(?:webp|jpe?g|png)',177 html)178 seen: set[str] = set()179 node["_gallery"] = [u for u in imgs180 if not (u in seen or seen.add(u))][:20]181 return node182 return {}183184 # -- contrat -----------------------------------------------------------------185 def fetch(self) -> list[Vehicle]:186 urls = self._vehicle_urls()187 week = datetime.date.today().isocalendar()188 cache_key = f"v1:{week.year}w{week.week}"189 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))190191 vehicles: list[Vehicle] = []192 real_fetches = 0193 for url in urls:194 ext_id = _VDP_RE.search(url).group(1)195196 def _fetch(u=url):197 return self._fetch_detail(u)198199 if real_fetches >= cap: # plafond : cache seulement200 from .. import db201 if self._detail_con is None:202 self._detail_con = db.connect()203 data = db.get_cached_detail(self._detail_con, self.source_id,204 ext_id, cache_key)205 if data is None:206 continue207 else:208 before = self._last_request209 data = self.detail(ext_id, cache_key, _fetch)210 if self._last_request != before:211 real_fetches += 1212 if not data:213 continue214 veh = self._to_vehicle(ext_id, url, data)215 if veh is not None:216 vehicles.append(veh)217 return vehicles218219 def _to_vehicle(self, ext_id: str, url: str, d: dict) -> Vehicle | None:220 # véhicules usagés uniquement221 cond = str(d.get("itemCondition") or "")222 if cond and "Used" not in cond:223 return None224225 title = " ".join(str(d.get("name") or "").split())226 if not title:227 return None228229 offers = d.get("offers") or {}230 price = None231 try:232 p = float(offers.get("price"))233 price = p if p > 0 else None234 except (TypeError, ValueError):235 pass236237 km = _qty(d.get("mileageFromOdometer"))238239 brand = d.get("brand") or {}240 make = brand.get("name") if isinstance(brand, dict) else str(brand)241242 drivetrain = ""243 drive_raw = str(d.get("driveWheelConfiguration") or "")244 for key, canon in _DRIVE_MAP.items():245 if key in drive_raw:246 drivetrain = canon247 break248249 year = None250 for k in ("vehicleModelDate", "modelDate", "productionDate"):251 try:252 year = int(str(d.get(k))[:4])253 break254 except (TypeError, ValueError):255 continue256257 engine = d.get("vehicleEngine") or {}258 engine_name = engine.get("name") if isinstance(engine, dict) else ""259260 images = d.get("_gallery") or []261 if not images and isinstance(d.get("image"), str):262 images = [d["image"]]263264 doors = d.get("numberOfDoors")265 doors = doors if isinstance(doors, int) else None266 try:267 seats = int(str(d.get("vehicleSeatingCapacity")))268 except (TypeError, ValueError):269 seats = None270271 details = {k: d[k] for k in ("numberOfForwardGears", "wheelbase",272 "fuelConsumption") if d.get(k)}273274 return Vehicle(275 source=self.source_id,276 external_id=ext_id,277 url=url,278 title=title,279 make=str(make or ""),280 model=str(d.get("model") or ""),281 trim=str(d.get("vehicleConfiguration") or ""),282 year=year,283 price=price,284 price_label=(f"{price:,.0f} $".replace(",", " ") if price else ""),285 mileage_km=km,286 mileage_label=(f"{km:,.0f} km".replace(",", " ") if km else ""),287 transmission=str(d.get("vehicleTransmission") or ""),288 fuel=str(d.get("fuelType") or ""),289 drivetrain=drivetrain,290 body_type=str(d.get("bodyType") or ""),291 exterior_color=str(d.get("color") or ""),292 interior_color=str(d.get("vehicleInteriorColor") or ""),293 engine=str(engine_name or ""),294 doors=doors,295 seats=seats,296 vin=str(d.get("vehicleIdentificationNumber") or ""),297 stock_number=str(d.get("sku") or ""),298 dealer_name=self.dealer_name,299 city=self.city,300 description=" ".join(str(d.get("description") or "").split())[:4000],301 details=details,302 images=images,303 )304