Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/autodurocher.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/autodurocher.py : connecteur Entrepôt Auto Durocher91# (autodurocher.com), gros marchand indépendant de Mirabel (~200 véhicules,92# occasion seulement).93#94# Plateforme : WordPress + Elementor + JetEngine (CPT « vehicles »).95# Le sitemap /fr/sitemap_index.xml expose des vehicles-sitemapN.xml qui ne96# recensent QUE l'inventaire courant (/fr/vehicles/<slug>/). Chaque page97# détail embarque un JSON-LD (script class="fute-custom-schema-vehicles",98# Organization -> makesOffer -> itemOffered @type Car) : prix, km,99# transmission, couleur, carrosserie, rouage, année, marque, modèle — et la100# galerie photos (CDN AutoTrader 1s-photomanager). Le no de stock est le101# dernier segment du slug. Le JSON contient des sauts de ligne bruts ->102# json.loads(strict=False).103#104# Pages détail en cache BD (clé hebdomadaire) ; AUTOKA_MAX_DETAILS (env)105# plafonne les vraies requêtes détail par synchronisation.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import datetime110import html as htmllib111import json112import os113import re114115from ..schema import Vehicle116from .base import BaseConnector117118_SITEMAP_RE = re.compile(r"vehicles-sitemap\d+\.xml$")119_VEH_URL_RE = re.compile(r"/fr/vehicles/([a-z0-9-]+)/?$")120_STOCK_RE = re.compile(r"-(?:19|20)\d{2}-([a-z0-9]+)$")121122_SCHEMA_RE = re.compile(123 r'<script type=["\']application/ld\+json["\'][^>]*'124 r'class="fute-custom-schema-vehicles"[^>]*>(.*?)</script>', re.S)125_LD_RE = re.compile(126 r'<script type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', re.S)127_IMG_RE = re.compile(r'https://1s-photomanager[^"\'\s\\<>]+', re.I)128129_FUEL_HINT_RE = re.compile(130 r"(hybride rechargeable|plug-?in|phev|hybride|hybrid|électrique|"131 r"electrique|electric|\bev\b|diesel|tdi)", re.I)132133_EXCLUDE_RE = re.compile(134 r"moto(?:cyclette|neige|marine)?\b|\bvtt\b|scooter|spyder|ryker|"135 r"can-?am|ski-?doo|sea-?doo|roulotte|remorque|\bvr\b|campeur", re.I)136137138def _clean(text) -> str:139 if not text:140 return ""141 out = htmllib.unescape(str(text))142 out = re.sub(r"<[^>]+>", " ", out)143 return re.sub(r"\s+", " ", out).strip()144145146def _num(value):147 try:148 v = float(str(value).replace(",", "").replace(" ", ""))149 except (TypeError, ValueError):150 return None151 return v if v else None152153154class AutoDurocher(BaseConnector):155 """Entrepôt Auto Durocher — sitemaps vehicles + JSON-LD des pages détail."""156157 source_id = "autodurocher"158 base_url = "https://www.autodurocher.com"159 dealer_name = "Entrepôt Auto Durocher"160 city = "Mirabel"161 request_delay = 1.0162 max_details = 300 # plafond de vraies requêtes par sync163164 # -- sitemaps ----------------------------------------------------------------165 def _vehicle_slugs(self) -> list[str]:166 index = self.get(f"{self.base_url}/fr/sitemap_index.xml").text167 maps = [loc.strip() for loc in re.findall(r"<loc>([^<]+)</loc>", index)168 if _SITEMAP_RE.search(loc.strip())]169 slugs: list[str] = []170 for sitemap_url in maps:171 try:172 xml = self.get(sitemap_url).text173 except Exception:174 continue # un sitemap HS ne bloque pas175 for loc in re.findall(r"<loc>([^<]+)</loc>", xml):176 m = _VEH_URL_RE.search(loc.strip())177 if m:178 slugs.append(m.group(1))179 return sorted(set(slugs))180181 # -- page détail -> payload ---------------------------------------------------182 def _fetch_detail(self, url: str) -> dict:183 html = self.get(url).text184 payload: dict = {}185186 blocks = _SCHEMA_RE.findall(html) or _LD_RE.findall(html)187 for block in blocks:188 try:189 data = json.loads(block.strip(), strict=False)190 except ValueError:191 continue192 offer = data.get("makesOffer") or {}193 car = offer.get("itemOffered") or {}194 if not isinstance(car, dict) or car.get("@type") != "Car":195 continue196 spec = offer.get("priceSpecification") or {}197 payload["price"] = spec.get("price")198 payload["car"] = {k: v for k, v in car.items()199 if not str(k).startswith("@")}200 break201202 images, seen = [], set()203 for u in _IMG_RE.findall(html):204 if u not in seen:205 seen.add(u)206 images.append(u)207 payload["images"] = images[:20]208 return payload209210 # -- contrat ---------------------------------------------------------------211 def fetch(self) -> list[Vehicle]:212 slugs = self._vehicle_slugs()213 week = datetime.date.today().isocalendar()214 cache_key = f"v1:{week.year}w{week.week}" # revalidation hebdomadaire215 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))216217 vehicles: list[Vehicle] = []218 real_fetches = 0219 for slug in slugs:220 url = f"{self.base_url}/fr/vehicles/{slug}/"221222 def _fetch(u=url):223 return self._fetch_detail(u)224225 if real_fetches >= cap: # plafond : cache seulement226 from .. import db227 if self._detail_con is None:228 self._detail_con = db.connect()229 data = db.get_cached_detail(self._detail_con, self.source_id,230 slug, cache_key)231 if data is None:232 continue233 else:234 before = self._last_request235 try:236 data = self.detail(slug, cache_key, _fetch)237 except Exception:238 # page disparue (vendu) ou erreur ponctuelle : continuer239 if self._last_request != before:240 real_fetches += 1241 continue242 if self._last_request != before:243 real_fetches += 1244 if not data or not data.get("car"):245 continue246 veh = self._to_vehicle(slug, url, data)247 if veh is not None:248 vehicles.append(veh)249 return vehicles250251 # -- payload -> Vehicle ------------------------------------------------------252 def _to_vehicle(self, slug: str, url: str, d: dict) -> Vehicle | None:253 car = d.get("car") or {}254 make = _clean(car.get("manufacturer") or car.get("brand"))255 model = _clean(car.get("model"))256 name = _clean(str(car.get("name") or "").split("\n")[0])257 if not (make or model or name):258 return None259 body = _clean(car.get("bodyType"))260 if _EXCLUDE_RE.search(f"{make} {model} {body} {name}"):261 return None262263 year = None264 m = re.search(r"(19|20)\d{2}", str(car.get("vehicleModelDate")265 or car.get("modelDate") or ""))266 if m:267 year = int(m.group(0))268269 # « 2018 - Audi A3 » -> titre standard270 title = re.sub(r"^(?:19|20)\d{2}\s*-\s*", "", name)271 title = " ".join(x for x in (title or f"{make} {model}",272 str(year or "")) if x)273274 price = _num(d.get("price"))275 km = _num(car.get("mileageFromOdometer"))276277 stock = ""278 m = _STOCK_RE.search(slug)279 if m:280 stock = m.group(1).upper()281282 engine = ""283 eng = car.get("vehicleEngine")284 if isinstance(eng, dict):285 engine = _clean(eng.get("name"))286287 description = _clean(car.get("description"))[:4000]288 # indice carburant : le NOM seulement (la description parle de289 # « sièges électriques » etc. -> faux positifs)290 fuel = ""291 m = _FUEL_HINT_RE.search(name)292 if m:293 fuel = m.group(1)294295 images = d.get("images") or []296 ld_img = car.get("image")297 if not images and isinstance(ld_img, str):298 images = [ld_img]299300 return Vehicle(301 source=self.source_id,302 external_id=slug,303 url=url,304 title=title,305 make=make,306 model=model,307 year=year,308 price=price,309 price_label=f"{price:,.0f} $".replace(",", " ") if price else "",310 mileage_km=km,311 mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",312 transmission=_clean(car.get("vehicleTransmission")),313 fuel=fuel,314 drivetrain=_clean(car.get("driveWheelConfiguration")),315 body_type=body,316 exterior_color=_clean(car.get("color")),317 engine=engine,318 stock_number=stock,319 dealer_name=self.dealer_name,320 city=self.city,321 description=description,322 images=images,323 )324