SPB Git

Repository Public

automobileendirect.py 14.9 KB 362 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/connectors/automobileendirect.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/automobileendirect.py : connecteur Automobile En Direct91#   (automobileendirect.com), grande chaîne d'occasion — Saint-Constant,92#   Laval, Saint-Hubert, Île-Perrot, Québec, Gatineau.93#94#   Stratégie : le site est une SPA React alimentée par une API REST95#   publique non authentifiée : https://api.automobileendirect.com96#     GET /cars?page=N  (en-tête accept-language: fr)97#       -> {"totalResults": ~1725, "results": [22 véhicules]}98#       chaque résultat : vin, slug, année/marque/modèle/version, prix99#       courant + régulier (CAD), km, transmission, carburant, carrosserie,100#       couleur, no de stock, photos, succursale (store.title.fr = ville).101#     GET /cars/detailed/<vin>  (optionnel, mise en cache BD, clé statique :102#       contenu quasi immuable, le prix/km frais viennent de la liste)103#       -> traction, portes, passagers, moteur, couleurs, description,104#          options, anciens propriétaires ET la galerie complète105#          (photos.all ≈ 25 images vs 4 aperçus dans la liste).106#   ~80 requêtes de liste pour tout l'inventaire ; les pages détail sont107#   plafonnées par AUTOKA_MAX_DETAILS (défaut 1200 — API JSON rapide,108#   ~1 s/requête) et complétées aux syncs suivants via le cache BD.109#110#   URL publique d'une fiche : /auto-usage/<slug>/<vin> (route SPA fr).111#   AUTOKA_MAX_PAGES (env) limite le nombre de pages de liste (tests).112# -----------------------------------------------------------------------------113from __future__ import annotations114115import os116import re117118from ..schema import Vehicle119from .base import BaseConnector120121API = "https://api.automobileendirect.com"122SITE = "https://www.automobileendirect.com"123124_PER_PAGE = 22          # taille fixe côté serveur125_AWD_RE = re.compile(r"\b(awd|4wd|4x4|quattro|xdrive|4matic|4motion)\b", re.I)126127# clé de cache détail (v2 : ajout de la galerie photos.all au payload)128_DETAIL_KEY = "v2"129130131def _fr(value) -> str:132    """Champ bilingue {'fr':…,'en':…} ou {'id':…,'title':{…}} -> texte fr."""133    if isinstance(value, dict):134        if "title" in value:135            return _fr(value["title"])136        return str(value.get("fr") or value.get("en") or "").strip()137    return str(value or "").strip()138139140class AutomobileEnDirect(BaseConnector):141    """Automobile En Direct — inventaire complet via l'API REST de la SPA."""142143    source_id = "automobileendirect"144    dealer_name = "Automobile En Direct"145    request_delay = 1.0146    max_pages = 200                  # garde-fou dur (~80 pages réelles)147    max_details = 1200               # plafond de vraies requêtes détail / sync148                                     # (API JSON rapide ; inventaire complet149                                     # enrichi en ≤ 2 syncs, puis cache BD)150151    def __init__(self) -> None:152        super().__init__()153        self.session.headers["accept-language"] = "fr"154155    # -- API ----------------------------------------------------------------156    def _list_page(self, page: int) -> dict:157        return self.get(f"{API}/cars", params={"page": page}).json()158159    def _fetch_detail(self, vin: str) -> dict:160        data = self.get(f"{API}/cars/detailed/{vin}").json()161        # ne garder que les champs utiles (cache BD compact)162        keep = ("traction", "doors", "passengers", "engineDescription",163                "engineSize", "cylinders", "colors", "description",164                "options", "previousOwners", "fuelConsumption")165        out = {k: data[k] for k in keep if data.get(k) is not None}166        # galerie complète (photos.all) — la liste n'a que 4 aperçus167        photos = data.get("photos") or {}168        gallery = [u for u in (photos.get("all") or []) if isinstance(u, str)]169        if gallery:170            out["photos"] = gallery[:30]171        return out172173    # -- contrat --------------------------------------------------------------174    def fetch(self) -> list[Vehicle]:175        page_cap = int(os.environ.get("AUTOKA_MAX_PAGES", self.max_pages))176        detail_cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))177178        rows: list[dict] = []179        seen: set[str] = set()180        page, total = 1, None181        while page <= min(page_cap, self.max_pages):182            data = self._list_page(page)183            results = data.get("results") or []184            if not results:185                break186            total = data.get("totalResults") or total187            for r in results:188                vin = str(r.get("vin") or "").strip()189                if vin and vin not in seen:190                    seen.add(vin)191                    rows.append(r)192            if total is not None and page * _PER_PAGE >= total:193                break194            page += 1195196        vehicles: list[Vehicle] = []197        real_fetches = 0198        for r in rows:199            extra: dict = {}200            vin = str(r["vin"])201            if real_fetches >= detail_cap:202                # budget épuisé : on sert quand même le cache BD existant203                from .. import db204                if self._detail_con is None:205                    self._detail_con = db.connect()206                extra = db.get_cached_detail(self._detail_con, self.source_id,207                                             vin, _DETAIL_KEY) or {}208            else:209                before = self._last_request210                # clé statique : le détail (traction, moteur, options…) ne211                # change pas ; prix/km frais viennent toujours de la liste212                try:213                    extra = self.detail(vin, _DETAIL_KEY,214                                        lambda v=vin: self._fetch_detail(v))215                except Exception:216                    extra = {}   # détail indisponible : données liste suffisent217                if self._last_request != before:218                    real_fetches += 1219            veh = self._to_vehicle(r, extra)220            if veh is not None:221                vehicles.append(veh)222        return vehicles223224    # -- payload API -> Vehicle -------------------------------------------------225    def _to_vehicle(self, r: dict, extra: dict) -> Vehicle | None:226        if r.get("sold") or r.get("hidden") or r.get("removedFromInventory"):227            return None228        vin = str(r.get("vin") or "").strip()229        slug = str(r.get("slug") or "").strip()230        if not vin or not slug:231            return None232233        year = r.get("year")234        make = str(r.get("make") or "").strip()235        model = str(r.get("model") or "").strip()236        trim = str(r.get("trim") or "").strip()237238        prices = r.get("prices") or {}239        price = prices.get("current") or prices.get("regular")240        try:241            price = float(price) if price else None242        except (TypeError, ValueError):243            price = None244245        km = r.get("kilometers")246        try:247            km = float(km) if km not in (None, "") else None248        except (TypeError, ValueError):249            km = None250251        # galerie complète depuis le détail (≈ 25 photos), sinon aperçus liste252        images = [u for u in (extra.get("photos") or []) if isinstance(u, str)]253        if not images:254            photos = r.get("photos") or {}255            images = [u for u in (photos.get("preview") or [])256                      if isinstance(u, str)]257            if not images and photos.get("main"):258                images = [photos["main"]]259260        # traction : page détail si dispo, sinon indice AWD/4x4 dans la version261        drivetrain = _fr(extra.get("traction"))262        if not drivetrain and _AWD_RE.search(trim):263            drivetrain = "Intégrale / 4x4"264265        colors = extra.get("colors") or {}266        interior = _fr(colors.get("interior")) if isinstance(colors, dict) else ""267268        engine = str(extra.get("engineDescription") or "").strip()269        if not engine and extra.get("engineSize"):270            cyl = extra.get("cylinders")271            engine = f"{extra['engineSize']}L" + (f" {cyl} cyl." if cyl else "")272273        description = _fr(extra.get("description")) or _fr(r.get("punchline"))274275        features: list[str] = []276        for opt in extra.get("options") or []:277            label = _fr(opt.get("title") if isinstance(opt, dict) else opt) \278                if isinstance(opt, (dict, str)) else ""279            if label:280                features.append(label)281282        details: dict = {}283        regular = prices.get("regular")284        if regular and price and regular != price:285            details["regular_price"] = regular286        if r.get("electricRange"):287            details["electric_range_km"] = r["electricRange"]288        if extra.get("previousOwners") is not None:289            details["previous_owners"] = extra["previousOwners"]290        if r.get("carfaxAmount") is not None:291            details["carfax_reports"] = r["carfaxAmount"]292293        # historique d'accident (déclaré par l'API) : dommages structurels294        # et total ($) des réparations — signaux clés en auto usagée295        if r.get("structuralDamage"):296            details["structural_damage"] = True297        try:298            total_damage = float(r.get("totalDamage") or 0)299        except (TypeError, ValueError):300            total_damage = 0.0301        if total_damage > 0:302            details["total_damage"] = total_damage303        # date de mise en vente -> jours sur le marché calculables en aval304        if r.get("createdDate"):305            details["listed_at"] = str(r["createdDate"])306        if r.get("promotions"):307            details["promotions"] = r["promotions"]308        if r.get("rabaisRoulezVert"):309            details["rabais_roulez_vert"] = True310        if r.get("thirdChance"):311            details["third_chance"] = True312313        # consommation ville/route (détail — téléchargée/cachée mais jamais314        # écrite auparavant) : L/100 km315        fc = extra.get("fuelConsumption") or {}316        if isinstance(fc, dict):317            if fc.get("city"):318                details["fuel_city_l_100km"] = fc["city"]319            if fc.get("highway"):320                details["fuel_hwy_l_100km"] = fc["highway"]321322        try:323            doors = int(extra["doors"]) if extra.get("doors") else None324        except (TypeError, ValueError):325            doors = None326        try:327            seats = int(extra["passengers"]) if extra.get("passengers") else None328        except (TypeError, ValueError):329            seats = None330331        return Vehicle(332            source=self.source_id,333            external_id=vin,334            url=f"{SITE}/auto-usage/{slug}/{vin}",335            title=" ".join(str(x) for x in (year, make, model) if x),336            make=make,337            model=model,338            trim=trim,339            year=int(year) if year else None,340            price=price,341            price_label=f"{price:,.0f} $".replace(",", " ") if price else "",342            mileage_km=km,343            mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",344            transmission=_fr(r.get("transmission")),345            fuel=_fr(r.get("fuelType")),346            drivetrain=drivetrain,347            body_type=_fr(r.get("body")),348            exterior_color=_fr(r.get("exteriorColor")),349            interior_color=interior,350            engine=engine,351            doors=doors,352            seats=seats,353            vin=vin,354            stock_number=str(r.get("stockNumber") or ""),355            dealer_name=self.dealer_name,356            city=_fr(r.get("store")),357            description=description[:4000],358            features=features[:80],359            details=details,360            images=images[:30],361        )362
Files main
Menu

Theme