Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/yannicklaberge.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/yannicklaberge.py : Automobiles Yannick Laberge (Beauport) —91# WordPress sur la plateforme AMVOQ (thème « theme_central », inventaire92# autousagee.ca, images image.autousagee.ca). API REST verrouillée (401).93#94# Stratégie : le sitemap Yoast `/vehicules-sitemap.xml` recense les annonces95# (/vehicule-usage/<slug>/<id>/). Chaque page détail expose un JSON-LD96# schema.org @type Vehicle : prix, VIN, km, transmission, carburant,97# couleur intérieure, description. Galerie complétée par les URLs98# image.autousagee.ca de la page. Pages détail en cache BD (clé hebdo).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import datetime103import json104import os105import re106107from ..schema import Vehicle108from .base import BaseConnector109110_VEH_URL_RE = re.compile(r"/vehicule-usage/[^/]+/(\d+)/?$")111112_LD_RE = re.compile(113 r'<script type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', re.S)114115_IMG_RE = re.compile(r'https://image\.autousagee\.ca/[^"\'\\\s)]+\.jpe?g')116117118class YannickLaberge(BaseConnector):119 source_id = "automobilesyannicklaberge"120 base_url = "https://www.automobilesyannicklaberge.com"121 dealer_name = "Automobiles Yannick Laberge"122 city = "Beauport"123 request_delay: float = 1.0124 max_details = 200125126 # -- sitemap ----------------------------------------------------------------127 def _vehicle_urls(self) -> list[str]:128 xml = self.get(f"{self.base_url}/vehicules-sitemap.xml").text129 return [loc.strip() for loc in re.findall(r"<loc>([^<]+)</loc>", xml)130 if _VEH_URL_RE.search(loc.strip())]131132 # -- page détail -> JSON-LD Vehicle + galerie ---------------------------------133 def _fetch_detail(self, url: str) -> dict:134 html = self.get(url).text135 for block in _LD_RE.findall(html):136 try:137 data = json.loads(block.strip())138 except ValueError:139 continue140 nodes = data if isinstance(data, list) else [data]141 for node in nodes:142 types = node.get("@type")143 types = types if isinstance(types, list) else [types]144 if "Vehicle" in types or "Car" in types:145 seen: set[str] = set()146 node["_gallery"] = [147 u for u in _IMG_RE.findall(html)148 if not (u in seen or seen.add(u))][:20]149 return node150 return {}151152 # -- contrat -----------------------------------------------------------------153 def fetch(self) -> list[Vehicle]:154 urls = self._vehicle_urls()155 week = datetime.date.today().isocalendar()156 cache_key = f"v1:{week.year}w{week.week}"157 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))158159 vehicles: list[Vehicle] = []160 real_fetches = 0161 for url in urls:162 ext_id = _VEH_URL_RE.search(url).group(1)163164 def _fetch(u=url):165 return self._fetch_detail(u)166167 if real_fetches >= cap: # plafond : cache seulement168 from .. import db169 if self._detail_con is None:170 self._detail_con = db.connect()171 data = db.get_cached_detail(self._detail_con, self.source_id,172 ext_id, cache_key)173 if data is None:174 continue175 else:176 before = self._last_request177 data = self.detail(ext_id, cache_key, _fetch)178 if self._last_request != before:179 real_fetches += 1180 if not data:181 continue182 veh = self._to_vehicle(ext_id, url, data)183 if veh is not None:184 vehicles.append(veh)185 return vehicles186187 def _to_vehicle(self, ext_id: str, url: str, d: dict) -> Vehicle | None:188 title = " ".join(str(d.get("name") or "").split())189 if not title:190 return None191192 offers = d.get("offers") or {}193 price = None194 try:195 p = float(offers.get("price"))196 price = p if p > 0 else None197 except (TypeError, ValueError):198 pass199200 odo = d.get("mileageFromOdometer") or {}201 km = odo.get("value") if isinstance(odo, dict) else odo202 try:203 km = float(km)204 km = km if km > 0 else None205 except (TypeError, ValueError):206 km = None207208 brand = d.get("brand") or {}209 make = brand.get("name") if isinstance(brand, dict) else str(brand)210211 year = None212 try:213 year = int(str(d.get("productionDate"))[:4])214 except (TypeError, ValueError):215 pass216217 try:218 doors = int(str(d.get("numberOfDoors")))219 except (TypeError, ValueError):220 doors = None221222 images = d.get("_gallery") or []223 if not images and isinstance(d.get("image"), str):224 images = [d["image"]]225226 return Vehicle(227 source=self.source_id,228 external_id=ext_id,229 url=url,230 title=title,231 make=str(make or ""),232 year=year,233 price=price,234 price_label=(f"{price:,.0f} $".replace(",", " ") if price else ""),235 mileage_km=km,236 mileage_label=(f"{km:,.0f} km".replace(",", " ") if km else ""),237 transmission=str(d.get("vehicleTransmission") or ""),238 fuel=str(d.get("fuelType") or ""),239 interior_color=str(d.get("vehicleInteriorColor") or ""),240 doors=doors,241 vin=str(d.get("vehicleIdentificationNumber") or ""),242 dealer_name=self.dealer_name,243 city=self.city,244 description=" ".join(str(d.get("description") or "").split())[:4000],245 images=images,246 )247