Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/leprixdugros.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1213# 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# connectors/leprixdugros.py : connecteur Le Prix du Gros (leprixdugros.com),91# groupe Mauricie / Centre-du-Québec (Kia, Nissan, Hyundai, Mazda + méga92# centre d'occasion) — Trois-Rivières, Shawinigan, Donnacona, Lévis,93# Québec, Laval, Sherbrooke, Joliette. INVENTAIRE OCCASION UNIQUEMENT.94#95# Plateforme : WordPress custom (thème Stereodev « lpdg-2022 »). La page96# liste expose un endpoint JSON paginé non documenté (celui du filtre Vue) :97# /inventaire/occasion/?output=json&pg=N -> {items(36/page), total, page}.98# Chaque item : année/marque/modèle/version, km, VIN, prix, rabais, stock,99# photo, permalien. ~37 pages pour ~1 300 véhicules d'occasion.100#101# La page détail (permalien) complète : moteur, rouage, transmission,102# passagers, couleurs, photos ET la concession où se trouve le véhicule103# (bloc « c-single-car-map-location » : nom + ville). Ces pages sont mises104# en cache BD à vie (clé stable — les specs ne changent pas ; le prix et le105# km frais viennent de la liste). AUTOKA_MAX_DETAILS (env) plafonne les106# vraies requêtes détail par sync ; AUTOKA_MAX_PAGES limite la pagination.107#108# NOTE : les pages détail n'ont NI description NI liste d'équipements par109# véhicule (les blocs « cards » sont du boilerplate : inspection 150 points,110# reconditionnement) — rien à extraire de plus que les specs/ville/photos.111# Le site est parfois lent (timeouts ponctuels) : chaque page détail tente112# d'abord un GET direct, puis bascule sur Scrapfly en cas d'échec ; le113# try/except par annonce garantit l'émission avec les données liste.114# Carburant : la source ne l'affiche jamais ; en plus des jetons explicites115# (hybride/EV/diesel), un moteur « N cylindres X.XL » sans indice électrifié116# => Essence (sauf modèles hybrides « sans badge » connus, ex. Prius).117# -----------------------------------------------------------------------------118from __future__ import annotations119120import html as htmllib121import os122import re123124from ..schema import Vehicle125from .base import BaseConnector126127_SPEC_RE = re.compile(128 r'c-single-car-features__list__text">\s*<strong>([^<]+)</strong><br>\s*'129 r"<span>([^<]*)</span>", re.S)130_LOC_NAME_RE = re.compile(131 r'c-single-car-map-location__name">\s*([^<]+?)\s*</span>', re.S)132_LOC_ADDR_RE = re.compile(133 r'c-single-car-map-location__adresse">(.*?)</span>', re.S)134_CITY_RE = re.compile(r"([A-Za-zÀ-ÿ'’ .-]+?)\s*,\s*(?:QC|Québec)\b")135_IMG_RE = re.compile(r'https://images\.leprixdugros\.com/[^"\s\\<>]+')136137_FUEL_HINT_RE = re.compile(138 r"(hybride rechargeable|plug-?in|phev|hybride|hybrid|electrique|"139 r"électrique|electric|\bev\b|diesel|tdi)", re.I)140141# moteur thermique explicite (« 4 cylindres 2.00L ») -> Essence par défaut142_CYL_ENGINE_RE = re.compile(r"\d+\s*cylindres?", re.I)143# modèles électrifiés « sans badge » : ne jamais leur inférer Essence144_ELECTRIFIED_MODELS = {145 "prius", "prius prime", "prius c", "prius v", "ioniq", "niro",146 "insight", "clarity", "volt", "bolt", "bolt euv", "leaf", "c-max",147 "cr-z", "ct 200h", "sienna", "venza", "crown", "sonata hybrid",148}149# camions HD & fourgons souvent diesel SANS mention explicite (ex. Ram 3500150# « 6 cylindres 6.70L » = Cummins diesel) : ne pas inférer Essence151_DIESEL_PRONE_RE = re.compile(152 r"\b(2500|3500|4500|5500|f-?[2-5]50|sprinter|promaster)\b", re.I)153154155def _clean(text: str | None) -> str:156 if not text:157 return ""158 out = htmllib.unescape(str(text))159 out = re.sub(r"<[^>]+>", " ", out)160 return re.sub(r"\s{2,}", " ", out).strip()161162163# clé de cache détail stable (bump si le parsing change)164_DETAIL_KEY = "v2"165166167class LePrixDuGros(BaseConnector):168 """Le Prix du Gros — JSON liste paginé + pages détail (specs, ville)."""169170 source_id = "leprixdugros"171 base_url = "https://www.leprixdugros.com"172 dealer_name = "Le Prix du Gros"173 request_delay = 1.0 # >= 1 s : le site tolère mal davantage174 max_pages = 80 # garde-fou dur (~37 pages réelles)175 max_details = 800 # plafond de vraies requêtes détail / sync176 # (couvre les ~690 véhicules en 1 sync ;177 # cache BD ensuite)178179 # -- liste JSON ----------------------------------------------------------180 def _list_page(self, page: int) -> dict:181 url = (f"{self.base_url}/inventaire/occasion/"182 f"?output=json&pg={page}")183 try:184 return self.get(url).json()185 except ValueError:186 return {}187188 # -- page détail -> payload (specs, concession, photos) -------------------189 def _fetch_detail(self, url: str) -> dict:190 try:191 html = self.get(url).text192 except Exception:193 # site lent / timeout ponctuel : repli Scrapfly (infra distincte)194 html = self.get_scrapfly(url)195 if not html:196 raise197 payload: dict = {"specs": {}, "images": []}198 for name, value in _SPEC_RE.findall(html):199 payload["specs"][_clean(name)] = _clean(value)200 m = _LOC_NAME_RE.search(html)201 if m:202 payload["dealer"] = _clean(m.group(1))203 m = _LOC_ADDR_RE.search(html)204 if m:205 # l'adresse est multi-lignes (<br>) : « 141 Rue Commerciale »,206 # « Donnacona, QC, G3M 1W2 », téléphone — la ville est le début207 # de LA ligne contenant « , QC »208 lines = [_clean(l) for l in re.split(r"<br\s*/?>", m.group(1))]209 lines = [l for l in lines if l]210 payload["address"] = ", ".join(lines[:2])211 for line in lines:212 c = _CITY_RE.match(line)213 if c:214 payload["city"] = c.group(1).strip()215 break216 seen: set[str] = set()217 for u in _IMG_RE.findall(html):218 if "_1000x750" in u and u not in seen:219 seen.add(u)220 payload["images"].append(u)221 if not payload["specs"] and not payload["images"]:222 # page d'erreur / interstitiel : ne pas mettre en cache du vide223 raise RuntimeError(f"page détail LPDG illisible : {url}")224 return payload225226 # -- contrat ---------------------------------------------------------------227 def fetch(self) -> list[Vehicle]:228 page_cap = int(os.environ.get("AUTOKA_MAX_PAGES", self.max_pages))229 detail_cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))230231 items: list[dict] = []232 seen_ids: set[str] = set()233 page, last_page = 1, 1234 while page <= min(last_page, page_cap, self.max_pages):235 data = self._list_page(page)236 batch = data.get("items") or []237 if not batch:238 break239 per_page = int(data.get("perPage") or len(batch) or 36)240 total = int(data.get("total") or 0)241 last_page = max(1, -(-total // max(per_page, 1))) # ceil242 new = 0243 for item in batch:244 ext_id = str(item.get("id") or item.get("stocknumber") or "")245 if ext_id and ext_id not in seen_ids:246 seen_ids.add(ext_id)247 items.append(item)248 new += 1249 if new == 0:250 break251 page += 1252253 vehicles: list[Vehicle] = []254 real_fetches = 0255 for item in items:256 detail: dict = {}257 url = str(item.get("permalink") or "")258 ext_id = str(item.get("id") or item.get("stocknumber") or "")259 if url:260 def _fetch(u=url):261 return self._fetch_detail(u)262263 # clé stable : specs figées ; prix/km frais via la liste264 if real_fetches >= detail_cap:265 from .. import db266 if self._detail_con is None:267 self._detail_con = db.connect()268 detail = db.get_cached_detail(self._detail_con,269 self.source_id,270 ext_id, _DETAIL_KEY) or {}271 else:272 before = self._last_request273 try:274 detail = self.detail(ext_id, _DETAIL_KEY, _fetch)275 except Exception:276 # page détail disparue ou timeout ponctuel : le277 # véhicule est quand même émis avec les données liste278 detail = {}279 if self._last_request != before:280 real_fetches += 1281 veh = self._to_vehicle(item, detail or {})282 if veh is not None:283 vehicles.append(veh)284 return vehicles285286 # -- item liste + détail -> Vehicle ------------------------------------------287 def _to_vehicle(self, item: dict, detail: dict) -> Vehicle | None:288 inventory = str(item.get("inventory") or "used").lower()289 if inventory == "new": # occasion seulement290 return None291292 ext_id = str(item.get("id") or item.get("stocknumber") or "")293 url = str(item.get("permalink") or "")294 if not ext_id or not url:295 return None296297 make = str(item.get("make") or "").strip()298 model = str(item.get("model") or "").strip()299 trim = _clean(item.get("trim"))300 year = item.get("year")301 title = _clean(item.get("title"))302 title = re.sub(r"\s+d[’']occasion à vendre\s*$", "", title, flags=re.I) \303 or " ".join(str(x) for x in (make, model, trim, year or "") if x)304305 price = item.get("price")306 try:307 price = float(price) if price else None308 except (TypeError, ValueError):309 price = None310311 km = item.get("kms")312 try:313 km = float(km) if km not in (None, "") else None314 except (TypeError, ValueError):315 km = None316317 specs = detail.get("specs") or {}318 engine = specs.get("Moteur", "")319 seats = None320 m = re.search(r"\d+", specs.get("Passagers", ""))321 if m:322 seats = int(m.group(0))323324 # carburant : déduit du titre/version/moteur (non affiché ailleurs)325 fuel = ""326 m = _FUEL_HINT_RE.search(f"{title} {trim} {engine}")327 if m:328 fuel = m.group(1)329 elif (_CYL_ENGINE_RE.search(engine)330 and model.lower() not in _ELECTRIFIED_MODELS331 and not _DIESEL_PRONE_RE.search(f"{title} {model} {trim}")):332 # moteur « N cylindres X.XL » sans aucun indice électrifié/diesel333 fuel = "Essence"334335 images = list(detail.get("images") or [])336 if not images and item.get("photo"):337 images = [str(item["photo"])]338339 details: dict = {"inventory_type": inventory}340341 # rabais : numérique > 0 seulement (« 0 » chaîne = pas de rabais) ;342 # prix régulier reconstitué = prix affiché + rabais343 try:344 rebate = float(item.get("rebate") or 0)345 except (TypeError, ValueError):346 rebate = 0.0347 if rebate > 0:348 details["rebate"] = rebate349 if price:350 details["regular_price"] = price + rebate351352 if str(item.get("is_certified") or "0") not in ("0", "", "None"):353 details["certified"] = True354 if str(item.get("econoplus") or "0") not in ("0", "", "None", "False"):355 details["econoplus"] = True356357 # mensualités du JSON liste : `payments` (bloc financement) et358 # `weekly` ($/semaine). Garde-fous : payments souvent vide, weekly359 # à 9999999 (sentinelle « non calculé ») — n'écrire que du réel.360 if item.get("payments") not in (None, "", 0, "0", [], {}):361 details["payments"] = item["payments"]362 try:363 weekly = float(item.get("weekly") or 0)364 except (TypeError, ValueError):365 weekly = 0.0366 if 0 < weekly < 5000: # sentinelle 9999999 exclue367 details["weekly_payment"] = weekly368 if specs.get("Cabine"):369 details["cab"] = specs["Cabine"]370 if detail.get("address"):371 details["branch_address"] = detail["address"]372 if detail.get("dealer"):373 details["branch"] = detail["dealer"]374375 return Vehicle(376 source=self.source_id,377 external_id=ext_id,378 url=url,379 title=title,380 make=make,381 model=model,382 trim=trim,383 year=int(year) if year else None,384 price=price,385 price_label=f"{price:,.0f} $".replace(",", " ") if price else "",386 mileage_km=km,387 mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",388 transmission=specs.get("Transmission", ""),389 fuel=fuel,390 drivetrain=specs.get("Rouage", ""),391 body_type="", # non exposé par la source392 exterior_color=specs.get("Couleur extérieure", ""),393 interior_color=specs.get("Couleur intérieure", ""),394 engine=engine,395 seats=seats,396 vin=str(item.get("vin") or ""),397 stock_number=str(item.get("stocknumber") or ""),398 dealer_name=detail.get("dealer") or self.dealer_name,399 city=detail.get("city", ""),400 details=details,401 images=images[:20],402 )403