SPB Git

Repository Public

classeauto.py 9.9 KB 264 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/connectors/classeauto.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-ka12# Created          : 2026-08-1213# Last Modified    : 2026-09-1314#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/classeauto.py : connecteur Classe Auto (classeauto.ca),91#   marchand d'occasion de l'île de Montréal (boul. Industriel,92#   Montréal-Nord/Anjou) — ~140 véhicules.93#94#   Plateforme : WordPress (thème Astra) + moteur d'inventaire DriveGood95#   (cdn.drivegood.com). Le site expose un export JSON STATIQUE de tout96#   l'inventaire :97#     /wp-content/themes/astra/car_single_page_data/cars_formatted.json98#   — une seule requête pour la liste complète, avec TOUS les champs :99#   prix, km, VIN, stock, transmission, carburant, motricité, carrosserie,100#   couleurs, portes, passagers, moteur, options, photos (cdn.drivegood.com),101#   description. Aucune page détail nécessaire.102#103#   Filtres de sécurité : vehicle_type_id == 1 (automobile), post_status104#   publish/published, condition != NEW, deleted_at vide.105#106#   Anti-bot (2026-09) : SiteGround sgcaptcha challenge (HTTP 202 + meta107#   refresh /.well-known/sgcaptcha/) sur les requêtes datacenter — fetch via108#   get_resilient() qui escalade vers le proxy résidentiel Oxylabs (-cc-CA).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import re113114from ..schema import Vehicle115from .base import BaseConnector116117_JSON_PATH = "/wp-content/themes/astra/car_single_page_data/cars_formatted.json"118119# garde-fou non-automobile (le marchand ne vend que des autos)120_EXCLUDE_RE = re.compile(121    r"motoneige|vtt|moto\b|motomarine|bateau|roulotte|remorque|spyder", re.I)122123124def _s(value) -> str:125    if value is None:126        return ""127    return re.sub(r"\s+", " ", str(value)).strip()128129130def _num(value) -> float | None:131    try:132        f = float(value)133    except (TypeError, ValueError):134        return None135    return f if f > 0 else None136137138def _int(value) -> int | None:139    try:140        return int(str(value))141    except (TypeError, ValueError):142        return None143144145class ClasseAuto(BaseConnector):146    """Classe Auto (Montréal) — inventaire complet en un JSON statique."""147148    source_id = "classeauto"149    base_url = "https://www.classeauto.ca"150    dealer_name = "Classe Auto"151    city = "Montréal"152    request_delay = 1.0153154    def fetch(self) -> list[Vehicle]:155        # sgcaptcha SiteGround actif depuis 2026-09 : le direct sert une page156        # challenge HTTP 202 → get_resilient escalade (Oxylabs -cc-CA passe).157        data = self.get_resilient(self.base_url + _JSON_PATH).json()158        vehicles: list[Vehicle] = []159        for d in data if isinstance(data, list) else []:160            try:161                veh = self._to_vehicle(d)162            except Exception:163                continue                     # enregistrement malformé isolé164            if veh is not None:165                vehicles.append(veh)166        return vehicles167168    def _to_vehicle(self, d: dict) -> Vehicle | None:169        if not isinstance(d, dict):170            return None171        if d.get("vehicle_type_id") not in (1, "1", None):172            return None                      # 1 = automobile173        if _s(d.get("post_status")) not in ("publish", "published", ""):174            return None175        if d.get("deleted_at"):176            return None177        if _s(d.get("condition")).upper() == "NEW":178            return None                      # usagé seulement179180        ext_id = _s(d.get("vid")) or _s(d.get("ID"))181        if not ext_id:182            return None183184        make = _s(d.get("maker")).title()185        model = _s(d.get("model"))186        trim = _s(d.get("car_trim")) or _s(d.get("car_sub_model"))187        year = _int(d.get("car_year"))188        body = _s(d.get("car_body"))189        if _EXCLUDE_RE.search(f"{make} {model} {body}"):190            return None191192        title = " ".join(x for x in (str(year or ""), make, model, trim) if x)193194        price = _num(d.get("car_price"))195        km = _num(d.get("car_mileage"))196        unit = _s(d.get("car_mileage_unit")).upper()197        if km and unit.startswith("MI"):198            km = round(km * 1.609344)199200        slug = _s(d.get("slug"))201        url = (f"{self.base_url}/cars/{slug}/" if slug202               else _s(d.get("guid")) or self.base_url)203204        images = [u.strip() for u in _s(d.get("photos")).split(",")205                  if u.strip().startswith("http")][:20]206207        engine = ""208        size = _s(d.get("car_engine_size"))209        cyl = _s(d.get("car_cylinders"))210        if size:211            engine = f"{size}L" + (f" {cyl} cyl." if cyl else "")212213        features = [f.strip().replace("_", " ")214                    for f in _s(d.get("car_options")).split(",") if f.strip()]215216        details: dict = {}217        if d.get("car_no_accident"):218            details["no_accident"] = True219        if d.get("car_one_owner"):220            details["unique_owner"] = True221        old_price = _num(d.get("car_old_price"))222        if old_price and price and old_price > price:223            details["old_price"] = old_price224225        carfax = _s(d.get("carfax_url")) or _s(d.get("carfax_report"))226        if not carfax:                        # parfois rangé dans admin_note227            m = re.search(r"https?://vhr\.carfax\.ca/\S+",228                          _s(d.get("admin_note")))229            if m:230                carfax = m.group(0)231232        return Vehicle(233            source=self.source_id,234            external_id=ext_id,235            url=url,236            title=title,237            make=make,238            model=model,239            trim=trim,240            year=year,241            price=price,242            price_label=f"{price:,.0f} $".replace(",", " ") if price else "",243            mileage_km=km,244            mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",245            transmission=_s(d.get("car_transmission")),246            fuel=_s(d.get("car_fuel_type")),247            drivetrain=_s(d.get("car_drivetrain")),248            body_type=body,249            exterior_color=_s(d.get("car_exterior_color")).title(),250            interior_color=_s(d.get("car_interrior_color")).title(),251            engine=engine,252            doors=_int(d.get("car_doors_count")),253            seats=_int(d.get("number_of_passengers")),254            vin=_s(d.get("car_vin")).upper(),255            stock_number=_s(d.get("stock")),256            dealer_name=self.dealer_name,257            city=self.city,258            description=_s(d.get("post_content"))[:4000],259            features=features[:60],260            details=details,261            images=images,262            carfax_url=carfax,263        )264
Files main
Menu

Theme