Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/albioccasion.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/albioccasion.py : connecteur ALBI Occasion (albioccasion.com),91# la division occasion d'ALBI le Géant — très grosse chaîne multi-92# succursales (Mascouche, Repentigny, Blainville, Laval, Rive-Nord…),93# ~800 véhicules d'occasion.94#95# Plateforme (refonte constatée le 2026-11-26, en ligne depuis le96# 2026-10-23) : application Nuxt. L'ancien site ASP.NET WebForms97# (/fr/inventaire/?page=N, /fr/vehicule/<id>/<slug>/, microdata) n'existe98# plus. Stratégie :99# - le sitemap /__sitemap__/fr-CA-vehicles.xml recense chaque fiche100# /fr/vehicule/<slug>-<no d'inventaire> ;101# - chaque fiche embarque l'état Nuxt (<script id="__NUXT_DATA__">, format102# « devalue » : un tableau où chaque valeur est un index vers une autre103# case) contenant l'objet véhicule complet : prix en cents, kilométrage,104# NIV, succursale réelle, statut, galerie, équipements ;105# - repli : le JSON-LD schema.org (@graph Vehicle) de la même page.106#107# Pages détail en cache BD (clé hebdomadaire — le prix est revalidé chaque108# semaine). AUTOKA_MAX_DETAILS plafonne les vraies requêtes détail par sync.109# Le paiement hebdomadaire (weeklyPaymentCents) n'est JAMAIS pris pour un prix.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import datetime114import html as htmllib115import json116import os117import re118119from ..schema import Vehicle120from .base import BaseConnector121122_SITEMAP = "/__sitemap__/fr-CA-vehicles.xml"123_LOC_RE = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")124_NUXT_RE = re.compile(125 r'<script[^>]*id="__NUXT_DATA__"[^>]*>(.*?)</script>', re.S)126_LD_RE = re.compile(127 r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', re.S)128129# enveloppes « devalue » : ["Reactive", index] etc.130_WRAPPERS = {"ShallowReactive", "Reactive", "Ref", "ShallowRef"}131132_EXCLUDE_RE = re.compile(133 r"moto(?:cyclette|neige|marine)?\b|\bvtt\b|scooter|spyder|ryker|"134 r"can-?am|ski-?doo|sea-?doo|roulotte|remorque|\bvr\b|campeur", re.I)135136MAX_IMAGES = 30137138139def _clean(text) -> str:140 if not text:141 return ""142 out = htmllib.unescape(str(text))143 out = re.sub(r"<[^>]+>", " ", out)144 return re.sub(r"\s{2,}", " ", out).strip()145146147def _resolve(table: list, idx, depth: int = 0):148 """Reconstitue la valeur d'index `idx` d'un tableau « devalue »."""149 if depth > 8 or not isinstance(idx, int) or isinstance(idx, bool) \150 or idx < 0 or idx >= len(table):151 return None152 val = table[idx]153 if isinstance(val, dict):154 return {k: _resolve(table, v, depth + 1) for k, v in val.items()}155 if isinstance(val, list):156 if val and isinstance(val[0], str):157 if val[0] in _WRAPPERS:158 return _resolve(table, val[1], depth + 1) if len(val) > 1 else None159 return None # Date, Set, Map… : inutiles ici160 return [_resolve(table, v, depth + 1) for v in val]161 return val162163164def _nuxt_vehicle(html: str) -> dict:165 """Objet véhicule de l'état Nuxt de la fiche ({} si introuvable)."""166 m = _NUXT_RE.search(html)167 if not m:168 return {}169 try:170 table = json.loads(m.group(1))171 except ValueError:172 return {}173 if not isinstance(table, list):174 return {}175 for i, val in enumerate(table):176 if isinstance(val, dict) and "stockNumber" in val \177 and "priceCents" in val and "vin" in val:178 obj = _resolve(table, i)179 return obj if isinstance(obj, dict) else {}180 return {}181182183def _ld_vehicle(html: str) -> dict:184 """Bloc schema.org Vehicle de la fiche (repli)."""185 for block in _LD_RE.findall(html):186 try:187 cand = json.loads(block.strip())188 except ValueError:189 continue190 items = cand if isinstance(cand, list) else [cand]191 for item in list(items):192 if isinstance(item, dict) and isinstance(item.get("@graph"), list):193 items = items + item["@graph"]194 for item in items:195 if not isinstance(item, dict):196 continue197 types = item.get("@type")198 types = types if isinstance(types, list) else [types]199 if "Vehicle" in types or "Car" in types:200 return item201 return {}202203204def _num(value) -> float | None:205 try:206 return float(value) if value not in (None, "") else None207 except (TypeError, ValueError):208 return None209210211class AlbiOccasion(BaseConnector):212 """ALBI Occasion — sitemap des fiches + état Nuxt de chaque fiche."""213214 source_id = "albioccasion"215 base_url = "https://www.albioccasion.com"216 dealer_name = "ALBI Occasion"217 city = "Mascouche"218 request_delay = 1.5219 max_details = 400 # plafond de vraies requêtes par sync220221 def get(self, url, **kw):222 """GET avec backoff sur 429 (rate-limit ALBI)."""223 import time as _t224225 import requests as _rq226 for attempt in range(4):227 try:228 return super().get(url, **kw)229 except _rq.exceptions.HTTPError as exc:230 if exc.response is not None and exc.response.status_code == 429 \231 and attempt < 3:232 _t.sleep(20 * (attempt + 1)) # 20 s, 40 s, 60 s233 continue234 raise235236 # -- sitemap -> URLs des fiches ------------------------------------------237 def _vehicle_urls(self) -> list[str]:238 xml = self.get(self.base_url + _SITEMAP).text239 urls, seen = [], set()240 for loc in _LOC_RE.findall(xml):241 loc = htmllib.unescape(loc)242 if "/fr/vehicule/" in loc and loc not in seen:243 seen.add(loc)244 urls.append(loc)245 return urls246247 # -- fiche -> payload -----------------------------------------------------248 def _fetch_detail(self, url: str) -> dict:249 html = self.get(url).text250 v = _nuxt_vehicle(html)251 if v:252 return {"nuxt": {k: v.get(k) for k in (253 "id", "stockNumber", "make", "model", "version", "year",254 "priceCents", "mileageKm", "bodyType", "category", "fuelType",255 "fuelTypeName", "transmission", "drivetrain", "dealership",256 "dealershipName", "status", "isOutlet", "isPowersports",257 "certified", "imageUrl", "photos", "vin", "color",258 "interiorColor", "numberOfDoors", "seats",259 "engineDisplacementL", "engineCylinders", "features",260 "legalWarranty")}}261 ld = _ld_vehicle(html)262 if ld:263 return {"ld": ld}264 raise LookupError(f"fiche ALBI illisible : {url}") # jamais en cache265266 # -- contrat ----------------------------------------------------------------267 def fetch(self) -> list[Vehicle]:268 urls = self._vehicle_urls()269 week = datetime.date.today().isocalendar()270 cache_key = f"n1:{week.year}w{week.week}"271 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))272273 vehicles: list[Vehicle] = []274 real_fetches = failures = 0275 for url in urls:276 slug = url.rstrip("/").rsplit("/", 1)[-1]277278 def _fetch(u=url):279 return self._fetch_detail(u)280281 if real_fetches >= cap:282 from .. import db283 if self._detail_con is None:284 self._detail_con = db.connect()285 data = db.get_cached_detail(self._detail_con, self.source_id,286 slug, cache_key)287 if data is None:288 continue289 else:290 before = self._last_request291 try:292 data = self.detail(slug, cache_key, _fetch)293 except Exception:294 failures += 1295 if self._last_request != before:296 real_fetches += 1297 continue298 if self._last_request != before:299 real_fetches += 1300 veh = self._to_vehicle(slug, url, data or {})301 if veh is not None:302 vehicles.append(veh)303 # gabarit changé : échec consigné (inventaire conservé), jamais zéro304 if urls and not vehicles and failures >= min(5, len(urls)):305 raise RuntimeError(306 f"albioccasion : {failures} fiche(s) illisible(s) sur "307 f"{len(urls)} au sitemap — gabarit changé ?")308 return vehicles309310 def _to_vehicle(self, slug: str, url: str, data: dict) -> Vehicle | None:311 n = data.get("nuxt") or {}312 ld = data.get("ld") or {}313 if n:314 if n.get("isPowersports"):315 return None316 status = str(n.get("status") or "").lower()317 if status and status not in ("in_stock", "available", "incoming",318 "in_transit"):319 return None # vendu / réservé / retiré320 make, model = _clean(n.get("make")), _clean(n.get("model"))321 trim = _clean(n.get("version"))322 year = n.get("year")323 cents = _num(n.get("priceCents"))324 price = round(cents / 100.0, 2) if cents else None325 km = _num(n.get("mileageKm"))326 stock = _clean(n.get("stockNumber"))327 ext_id = str(n.get("id") or stock or slug)328 body = _clean(n.get("category") or n.get("bodyType"))329 fuel = _clean(n.get("fuelTypeName") or n.get("fuelType"))330 images = [u for u in (n.get("photos") or []) if isinstance(u, str)]331 if not images and n.get("imageUrl"):332 images = [str(n["imageUrl"])]333 branch = _clean(n.get("dealership"))334 dealer = _clean(n.get("dealershipName")) or self.dealer_name335 engine = ""336 if _num(n.get("engineDisplacementL")):337 engine = f"{float(n['engineDisplacementL']):.1f}L"338 if n.get("engineCylinders"):339 engine += f" {int(n['engineCylinders'])} cyl."340 details = {}341 if n.get("certified"):342 details["certified"] = True343 if n.get("isOutlet"):344 details["outlet"] = True345 if n.get("legalWarranty"):346 details["legal_warranty"] = _clean(n["legalWarranty"])347 veh = Vehicle(348 source=self.source_id, external_id=ext_id, url=url,349 title=" ".join(str(x) for x in (make, model, trim, year) if x),350 make=make, model=model, trim=trim,351 year=int(year) if isinstance(year, (int, float)) else None,352 price=price,353 price_label=f"{price:,.0f} $".replace(",", " ") if price else "",354 mileage_km=km,355 mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",356 transmission=_clean(n.get("transmission")),357 fuel=fuel, drivetrain=_clean(n.get("drivetrain")),358 body_type=body, exterior_color=_clean(n.get("color")),359 interior_color=_clean(n.get("interiorColor")), engine=engine,360 doors=n.get("numberOfDoors") if isinstance(n.get("numberOfDoors"), int) else None,361 seats=n.get("seats") if isinstance(n.get("seats"), int) else None,362 vin=_clean(n.get("vin")), stock_number=stock,363 dealer_name=dealer, city=branch or self.city,364 features=[_clean(f) for f in (n.get("features") or [])365 if isinstance(f, str) and _clean(f)][:80],366 details=details, images=images[:MAX_IMAGES],367 )368 elif ld:369 offers = ld.get("offers") or {}370 price = _num(offers.get("price")) or None371 odo = ld.get("mileageFromOdometer") or {}372 km = _num(odo.get("value") if isinstance(odo, dict) else odo)373 brand = ld.get("brand")374 make = brand.get("name") if isinstance(brand, dict) else brand375 img = ld.get("image") or []376 year = None377 try:378 year = int(str(ld.get("vehicleModelDate"))[:4])379 except (TypeError, ValueError):380 pass381 stock = _clean(ld.get("sku"))382 veh = Vehicle(383 source=self.source_id, external_id=stock or slug, url=url,384 title=_clean(ld.get("name")), make=_clean(make),385 model=_clean(ld.get("model")), year=year, price=price,386 price_label=f"{price:,.0f} $".replace(",", " ") if price else "",387 mileage_km=km,388 transmission=_clean(ld.get("vehicleTransmission")),389 fuel=_clean(ld.get("fuelType")), body_type=_clean(ld.get("bodyType")),390 exterior_color=_clean(ld.get("color")),391 vin=_clean(ld.get("vehicleIdentificationNumber")),392 stock_number=stock, dealer_name=self.dealer_name, city=self.city,393 images=[img] if isinstance(img, str) else394 [u for u in img if isinstance(u, str)][:MAX_IMAGES],395 )396 else:397 return None398 if not veh.title or _EXCLUDE_RE.search(f"{veh.title} {veh.body_type}"):399 return None400 return veh401