Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/megacentre.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/megacentre.py : connecteur Méga Centre de liquidation91# (megacentredeliquidation.com), place de marché d'occasion du Groupe92# Laplante — Québec, Trois-Rivières, Rimouski, Matane, Mont-Joli, Amqui,93# Rawdon (Lanaudière), etc.94#95# Plateforme : Gatsby (site statique sur Fastly), inventaire EvalAuto.96# Le sitemap (/sitemap-index.xml -> /sitemap-0.xml) recense chaque page97# véhicule /auto-usage/<marque-modele-annee-stock>/. Pour chaque slug, le98# JSON Gatsby /page-data/auto-usage/<slug>/page-data.json expose l'objet99# `usedCar` complet : prix, odomètre, NIV, stock, transmission, rouage,100# carburant, carrosserie, couleurs, moteur, portes, places, options,101# description, photos, CarProof ET la concession réelle du véhicule102# (nameDealer + cityDealer — la ville par véhicule).103#104# Les page-data sont mises en cache BD (clé hebdomadaire, même logique que105# les connecteurs D2C) : seuls les nouveaux véhicules et la revalidation106# hebdomadaire génèrent de vraies requêtes. AUTOKA_MAX_DETAILS (env)107# plafonne les vraies requêtes détail par synchronisation.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import datetime112import html as htmllib113import os114import re115116from ..schema import Vehicle117from .base import BaseConnector118119# pages véhicule : /auto-usage/<slug>-<année>-<stock>/ (un seul segment)120_VEH_URL_RE = re.compile(121 r"^https://www\.megacentredeliquidation\.com/auto-usage/"122 r"([a-z0-9-]+-(?:19|20)\d{2}-[a-z0-9-]+)/$")123124# le groupe liste aussi quelques non-automobiles (Can-Am Ryker, VR…)125_EXCLUDE_RE = re.compile(126 r"can-?am|spyder|ryker|harley|ski-?doo|sea-?doo|polaris|kawasaki|"127 r"gulf ?stream|jayco|keystone|forest river|motoris|roulotte|remorque|"128 r"motorcycle|snowmobile|atv|\brv\b|trailer|motorhome", re.I)129130131def _clean_html(text: str | None) -> str:132 """HTML avec entités (é…) -> texte brut compact."""133 if not text:134 return ""135 out = htmllib.unescape(str(text))136 out = re.sub(r"<[^>]+>", " ", out)137 return re.sub(r"\s{2,}", " ", out).strip()138139140class MegaCentreDeLiquidation(BaseConnector):141 """Méga Centre de liquidation — sitemap + page-data Gatsby (usedCar)."""142143 source_id = "megacentredeliquidation"144 base_url = "https://www.megacentredeliquidation.com"145 dealer_name = "Méga Centre de liquidation"146 request_delay = 1.0147 max_details = 600 # plafond de vraies requêtes par sync148149 # -- sitemap -------------------------------------------------------------150 def _vehicle_slugs(self) -> list[str]:151 index = self.get(f"{self.base_url}/sitemap-index.xml").text152 maps = re.findall(r"<loc>([^<]+)</loc>", index) \153 or [f"{self.base_url}/sitemap-0.xml"]154 slugs: list[str] = []155 for sitemap_url in maps:156 xml = self.get(sitemap_url.strip()).text157 for loc in re.findall(r"<loc>([^<]+)</loc>", xml):158 m = _VEH_URL_RE.match(loc.strip())159 if m:160 slugs.append(m.group(1))161 return sorted(set(slugs))162163 # -- page-data Gatsby -> payload usedCar ----------------------------------164 def _fetch_detail(self, slug: str) -> dict:165 url = f"{self.base_url}/page-data/auto-usage/{slug}/page-data.json"166 try:167 data = self.get(url).json()168 except ValueError:169 return {}170 result = data.get("result") or {}171 used_car = (result.get("data") or {}).get("usedCar")172 if not isinstance(used_car, dict):173 return {}174 used_car.pop("coordinates", None) # gros bloc inutile175 used_car.pop("loanPaiement", None)176 return {"usedCar": used_car,177 "latestModification":178 (result.get("pageContext") or {}).get("latestModification")}179180 # -- contrat ---------------------------------------------------------------181 def fetch(self) -> list[Vehicle]:182 slugs = self._vehicle_slugs()183 week = datetime.date.today().isocalendar()184 cache_key = f"v1:{week.year}w{week.week}" # revalidation hebdomadaire185 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))186187 vehicles: list[Vehicle] = []188 real_fetches = 0189 for slug in slugs:190 def _fetch(s=slug):191 return self._fetch_detail(s)192193 # plafond atteint : ne servir que le cache (fetch réel interdit)194 if real_fetches >= cap:195 from .. import db196 if self._detail_con is None:197 self._detail_con = db.connect()198 data = db.get_cached_detail(self._detail_con, self.source_id,199 slug, cache_key)200 if data is None:201 continue202 else:203 before = self._last_request204 try:205 data = self.detail(slug, cache_key, _fetch)206 except Exception:207 # page disparue (vendu) ou erreur ponctuelle : ne jamais208 # bloquer la source entière209 if self._last_request != before:210 real_fetches += 1211 continue212 if self._last_request != before: # une vraie requête a eu lieu213 real_fetches += 1214 if not data or not data.get("usedCar"):215 continue216 veh = self._to_vehicle(slug, data["usedCar"])217 if veh is not None:218 vehicles.append(veh)219 return vehicles220221 # -- usedCar -> Vehicle ------------------------------------------------------222 def _to_vehicle(self, slug: str, d: dict) -> Vehicle | None:223 make = str(d.get("brand") or "").strip()224 model = str(d.get("labelModel_fr") or d.get("model") or "").strip()225 body = str(d.get("labelBodytype_fr") or d.get("bodytype") or "").strip()226 if _EXCLUDE_RE.search(f"{make} {model} {body}"): # non-automobile227 return None228229 year = d.get("year")230 trim = str(d.get("trim") or "").strip()231 # certains labels de modèle incluent déjà la version (X1 XDRIVE28I)232 title_trim = "" if trim.lower() in model.lower() else trim233 title = " ".join(str(x)234 for x in (make, model, title_trim, year or "") if x)235 if not title:236 return None237238 price = d.get("price")239 try:240 price = float(price) if price else None241 except (TypeError, ValueError):242 price = None243244 km = d.get("odometer")245 try:246 km = float(km) if km not in (None, "") else None247 except (TypeError, ValueError):248 km = None249 unit = str(d.get("odometer_Type") or "km").lower()250 if km is not None and unit.startswith("mi"):251 km = round(km * 1.609344)252253 images = d.get("images") or []254 if isinstance(images, str):255 images = [images]256 images = [u for u in images if isinstance(u, str)]257 if not images and d.get("image"):258 images = [str(d["image"])]259260 features = [f.strip() for f in str(d.get("options") or "").split("|")261 if f.strip()]262263 doors = d.get("doors")264 seats = d.get("passengers")265266 details: dict = {"branch": str(d.get("nameDealer") or "")}267 for src, dst in (("accident", "accidented"),268 ("certified", "certified"),269 ("uniqueOwner", "unique_owner")):270 if d.get(src) is not None:271 details[dst] = bool(d[src])272 if d.get("cityConsumption"):273 details["consumption_city_l_100km"] = d["cityConsumption"]274 if d.get("hightwayConsumption"):275 details["consumption_hwy_l_100km"] = d["hightwayConsumption"]276 if d.get("inventoryID"):277 details["inventory_id"] = str(d["inventoryID"])278279 return Vehicle(280 source=self.source_id,281 external_id=slug,282 url=f"{self.base_url}/auto-usage/{slug}/",283 title=title,284 make=make,285 model=model,286 trim=trim,287 year=int(year) if year else None,288 price=price,289 price_label=f"{price:,.0f} $".replace(",", " ") if price else "",290 mileage_km=km,291 mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",292 transmission=str(d.get("transmission") or ""),293 fuel=str(d.get("labelEngine_fr") or d.get("engine") or ""),294 drivetrain=str(d.get("drivetrain") or ""),295 body_type=body,296 exterior_color=str(d.get("labelColorExt_fr") or ""),297 interior_color=str(d.get("labelColorInt_fr") or ""),298 engine=str(d.get("motor") or ""),299 doors=int(doors) if doors else None,300 seats=int(seats) if seats else None,301 vin=str(d.get("niv") or ""),302 stock_number=str(d.get("stockNO") or ""),303 dealer_name=str(d.get("nameDealer") or "").strip()304 or self.dealer_name,305 city=str(d.get("cityDealer") or "").strip(),306 description=_clean_html(d.get("description"))[:4000],307 features=features[:60],308 details=details,309 images=images[:20],310 carfax_url=str(d.get("carproofURL") or ""),311 )312