SPB Git

Repository Public

desmeules.py 14.1 KB 339 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/connectors/desmeules.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/desmeules.py : connecteur Desmeules Chrysler (desmeules.ca),91#   gros concessionnaire Chrysler/Dodge/Jeep/RAM de Laval — ~220 véhicules92#   d'occasion.93#94#   Plateforme : ColdFusion maison + inventaire AutoJini (photos95#   images.autojini.net). La page occasion expose un flux RSS complet :96#   /fr/vehicules-doccasion/?fuseaction=inventory.feedRSS&ajaxCall=197#   -> un <item> par véhicule : titre (année marque modèle + prix), lien98#   détail (…-v<id>.html), no de stock, VIN, photo, longue description.99#100#   La page détail complète : kilométrage (detailsMileageData), moteur,101#   transmission/entraînement (microdata) et galerie photos. Elle porte aussi102#   la liste d'équipements AutoJini (« Équipement standard », divs .column :103#   h3 catégorie + ul d'items) dont la section « Transmission & Moteur »104#   contient le carburant (« Essence », « Plug-in électric / gas »…) et la105#   motricité (« Traction Intégrale », « Quatre roues motrices »…), ainsi106#   qu'une boîte « Catégorie » (Car/VUS/SUV/Truck) pour la carrosserie.107#   Ces pages sont mises en cache BD à vie (clé stable — les specs ne108#   changent pas ; le prix frais vient du RSS). AUTOKA_MAX_DETAILS (env)109#   plafonne les vraies requêtes détail par synchronisation.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import html as htmllib114import os115import re116117from ..schema import (Vehicle, normalize_body, normalize_drivetrain,118                      normalize_fuel, strip_accents)119from .base import BaseConnector120121_ITEM_RE = re.compile(r"<item>(.*?)</item>", re.S)122_TITLE_RE = re.compile(r"<title>\s*<!\[CDATA\[(.*?)\]\]>", re.S)123_LINK_RE = re.compile(r'href="(https?://[^"]+-v(\d+)\.html)"')124_STOCK_RE = re.compile(r"Stock #:\s*([^<]+)</div>")125_VIN_RE = re.compile(r"VIN #:\s*([^<]+)</div>")126_IMG_RE = re.compile(r'img[^>]*src="([^"]+)"')127_PRICE_RE = re.compile(r"-\s*\$([\d,]+)\s*$")128129# page détail (la transmission/couleur vient de la meta description :130# « … - Engine: V8 4.0L Cylinder Engine - Color : . - Transmission: Automatique »)131_KM_RE = re.compile(r'detailsMileageData">\s*([\d,\s]+)\s*km', re.I)132_ENGINE_RE = re.compile(r"Moteur:\s*</div>\s*<div[^>]*>\s*([^<]+)", re.S)133_TRANS_RE = re.compile(r"Transmission:\s*([A-Za-zÀ-ÿ][A-Za-zÀ-ÿ ]*)")134_DRIVE_RE = re.compile(r"Entra[îi]nement\s*:\s*<span>\s*([^<]+)", re.I)135_COLOR_RE = re.compile(r"Color\s*:\s*([A-Za-zÀ-ÿ][^.<\"]*)[.<\"]")136_GALLERY_RE = re.compile(137    r'https?://images\.autojini\.[a-z]+/[^"\s\\<>]+?\.jpg(?!/)', re.I)138139# liste d'équipements AutoJini : divs .column (h3 catégorie + ul d'items)140_FEATURE_SECTION_RE = re.compile(141    r'<div class="column[^"]*">\s*<h3>([^<]+)</h3>\s*<ul>(.*?)</ul>', re.S)142_LI_RE = re.compile(r"<li>(.*?)</li>", re.S)143# boîte « Catégorie » (Car / VUS / SUV / Truck…) -> carrosserie144_CATEGORY_RE = re.compile(145    r'colorBoxHead">\s*Cat(?:é|&eacute;)gorie\s*</div>'146    r'.*?colorBoxText">(.*?)</div>', re.S)147148_EXCLUDE_RE = re.compile(149    r"moto(?:cyclette|neige|marine)?\b|\bvtt\b|scooter|spyder|ryker|"150    r"can-?am|ski-?doo|sea-?doo|roulotte|remorque|\bvr\b|campeur", re.I)151152153def _clean(text) -> str:154    if not text:155        return ""156    out = htmllib.unescape(str(text))157    out = re.sub(r"<[^>]+>", " ", out)158    return re.sub(r"\s+", " ", out).strip()159160161# clé de cache détail stable (bump si le parsing change)162# v3 : + équipements, carburant/motricité (Transmission & Moteur), carrosserie163_DETAIL_KEY = "v3"164165166class DesmeulesChrysler(BaseConnector):167    """Desmeules Chrysler — flux RSS inventaire + pages détail (km, specs)."""168169    source_id = "desmeules"170    base_url = "https://www.desmeules.ca"171    dealer_name = "Desmeules Chrysler"172    city = "Laval"173    request_delay = 1.0174    max_details = 300                  # plafond de vraies requêtes par sync175176    # -- flux RSS ----------------------------------------------------------------177    def _rss_items(self) -> list[dict]:178        xml = self.get(179            f"{self.base_url}/fr/vehicules-doccasion/"180            "?fuseaction=inventory.feedRSS&ajaxCall=1").text181        items: list[dict] = []182        for chunk in _ITEM_RE.findall(xml):183            link = _LINK_RE.search(chunk)184            if not link:185                continue186            entry: dict = {"url": link.group(1).replace("http://", "https://"),187                           "id": link.group(2)}188            m = _TITLE_RE.search(chunk)189            title = _clean(m.group(1)) if m else ""190            m = _PRICE_RE.search(title)191            if m:192                entry["price"] = float(m.group(1).replace(",", ""))193                title = title[:m.start()].strip()194            title = re.sub(r"^For Sale\s+", "", title, flags=re.I)195            entry["title"] = title196            m = _STOCK_RE.search(chunk)197            if m:198                entry["stock"] = _clean(m.group(1))199            m = _VIN_RE.search(chunk)200            if m:201                entry["vin"] = _clean(m.group(1))202            m = _IMG_RE.search(chunk)203            if m:204                entry["photo"] = m.group(1).split("/Resize")[0]205            # description longue : le 2e bloc CDATA de la description206            blocks = re.findall(r"<!\[CDATA\[(.*?)\]\]>", chunk, re.S)207            if len(blocks) >= 3:208                entry["description"] = _clean(blocks[2])[:4000]209            items.append(entry)210        return items211212    # -- page détail -> payload ---------------------------------------------------213    def _fetch_detail(self, url: str) -> dict:214        html = self.get(url).text215        payload: dict = {}216        m = _KM_RE.search(html)217        if m:218            payload["km"] = float(re.sub(r"[^\d]", "", m.group(1)))219        m = _ENGINE_RE.search(html)220        if m:221            payload["engine"] = _clean(m.group(1))222        m = _TRANS_RE.search(html)223        if m:224            payload["transmission"] = _clean(m.group(1))225        m = _DRIVE_RE.search(html)226        if m:227            payload["drivetrain"] = _clean(m.group(1))228        m = _COLOR_RE.search(html)229        if m:230            payload["color"] = _clean(m.group(1))231232        # boîte « Catégorie » -> carrosserie canonique (Car reste ambigu)233        m = _CATEGORY_RE.search(html)234        if m:235            body = normalize_body(_clean(m.group(1)))236            if body:237                payload["body"] = body238239        # équipements par catégorie ; « Transmission & Moteur » porte le240        # carburant et la motricité, absents partout ailleurs241        features: list[str] = []242        for head, ul in _FEATURE_SECTION_RE.findall(html):243            items = [_clean(li) for li in _LI_RE.findall(ul)]244            items = [it for it in items if it]245            features.extend(items)246            if not strip_accents(head).lower().startswith("transmission"):247                continue248            for it in items:249                if "fuel" not in payload:250                    fuel = normalize_fuel(it)251                    if fuel:252                        payload["fuel"] = fuel253                if "drivetrain" not in payload:254                    low = strip_accents(it).lower()255                    if "quatre roues" in low or "4 roues" in low:256                        payload["drivetrain"] = "Intégrale / 4x4"257                    elif "controle" not in low:   # « Contrôle de traction »258                        drive = normalize_drivetrain(it)259                        if drive:260                            payload["drivetrain"] = drive261        if features:262            payload["features"] = features[:60]263264        images, seen = [], set()265        for u in _GALLERY_RE.findall(html):266            base = u.replace("_x.jpg", ".jpg")267            if base not in seen:268                seen.add(base)269                images.append(base)270        payload["images"] = images[:20]271        return payload272273    # -- contrat ---------------------------------------------------------------274    def fetch(self) -> list[Vehicle]:275        cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))276        vehicles: list[Vehicle] = []277        real_fetches = 0278        for item in self._rss_items():279            if _EXCLUDE_RE.search(item.get("title", "")):280                continue281            detail: dict = {}282            if real_fetches >= cap:            # plafond : cache seulement283                from .. import db284                if self._detail_con is None:285                    self._detail_con = db.connect()286                detail = db.get_cached_detail(self._detail_con, self.source_id,287                                              item["id"], _DETAIL_KEY) or {}288            else:289                def _fetch(u=item["url"]):290                    return self._fetch_detail(u)291                before = self._last_request292                try:293                    detail = self.detail(item["id"], _DETAIL_KEY, _fetch)294                except Exception:295                    detail = {}                # page disparue : données RSS296                if self._last_request != before:297                    real_fetches += 1298            veh = self._to_vehicle(item, detail or {})299            if veh is not None:300                vehicles.append(veh)301        return vehicles302303    # -- item RSS + détail -> Vehicle ----------------------------------------------304    def _to_vehicle(self, item: dict, detail: dict) -> Vehicle | None:305        title = item.get("title") or ""306        if not title:307            return None308309        price = item.get("price")310        km = detail.get("km")311312        images = list(detail.get("images") or [])313        if not images and item.get("photo"):314            images = [item["photo"]]315316        return Vehicle(317            source=self.source_id,318            external_id=item["id"],319            url=item["url"],320            title=title,                       # « 2021 Aston Martin DBX … »321            price=price,322            price_label=f"{price:,.0f} $".replace(",", " ") if price else "",323            mileage_km=km,324            mileage_label=f"{km:,.0f} km".replace(",", " ") if km else "",325            transmission=detail.get("transmission", ""),326            fuel=detail.get("fuel", ""),327            drivetrain=detail.get("drivetrain", ""),328            body_type=detail.get("body", ""),329            exterior_color=detail.get("color", ""),330            engine=detail.get("engine", ""),331            vin=item.get("vin", ""),332            stock_number=item.get("stock", ""),333            dealer_name=self.dealer_name,334            city=self.city,335            description=item.get("description", ""),336            features=list(detail.get("features") or []),337            images=images,338        )339
Files main
Menu

Theme