SPB Git

Repository Public

otogo.py 10.4 KB 263 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/connectors/otogo.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-ka12# Created          : 2026-08-1813# 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/otogo.py : PORTAIL — Otogo.ca (LC Media, 100 % Québec)91#92#   Otogo expose une API JSON publique, sans clé ni rendu JS :93#       GET https://www.otogo.ca/api-search/?latlng=0,0&locale=fr&no_facets=94#           &rpp=100&page=N&status=Usagé,Certifié,Démo[&price=lo-hi]95#   Chaque annonce de la liste est déjà riche : titre/version FR, année,96#   prix, kilométrage, VIN (≈100 %), nom du concessionnaire et surtout le97#   GPS EXACT du vendeur (latitude/longitude) — parfait pour la recherche98#   par rayon et la dédup VIN avec les concessionnaires connectés.99#   (Paramètres découverts dans les bundles Nuxt : constantes c.b du module100#   5731047.js — latlng/locale/rpp/page/price/status/no_facets/no_results.)101#102#   Profondeur : l'API plafonne à ~1 000 résultats par requête (rpp=100 →103#   meta.pages ≤ 10) pour ~24 000 annonces d'occasion. On PARTITIONNE donc104#   par tranches de prix (bissection récursive + tranche ouverte « lo- ») :105#   chaque annonce n'est téléchargée qu'une fois, ~250 requêtes directes106#   par sync complet, zéro crédit d'API de scraping externe.107#108#   Ville : absente de la liste — déduite du GPS exact via nearest_city()109#   (data/villes_gps.json) pour l'affichage et la région administrative.110#   Carburant/boîte : absents de la liste ; repli commun finalize() (jetons111#   du titre/de la version). Page détail : /auto/{slug_fr} (non visitée —112#   économie ; le VIN et le GPS sont déjà dans la liste).113#114#   Plafond : AUTOKA_OTOGO_MAX (défaut 0 = inventaire complet).115# -----------------------------------------------------------------------------116from __future__ import annotations117118import os119import re120121from ..normalize import nearest_city122from ..schema import Vehicle123from .base import BaseConnector124125BASE = "https://www.otogo.ca"126API = BASE + "/api-search/"127128RPP = 100                     # résultats par page (max utile observé)129DEPTH = 1000                  # profondeur max de pagination par requête130STATUS = "Usagé,Certifié,Démo"   # occasion seulement (exclut Neuf)131PRICE_SPLIT_FLOOR = 250       # $ : largeur minimale d'une tranche de prix132133_VIN_RE = re.compile(r"^[A-HJ-NPR-Z0-9]{17}$")134135136def _max_listings() -> int:137    try:138        return max(0, int(os.environ.get("AUTOKA_OTOGO_MAX", "0")))139    except ValueError:140        return 0141142143class OtogoQuebec(BaseConnector):144    """Portail Otogo.ca — inventaire d'occasion des concessionnaires du Québec."""145146    source_id = "otogo"147    request_delay = 0.8148149    def __init__(self) -> None:150        super().__init__()151        self.session.headers.update({152            "Accept": "application/json",153            "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.5",154        })155156    # -- API --------------------------------------------------------------------157158    def _query(self, page: int, lo: int, hi: int | None) -> tuple[dict, list[dict]]:159        """Une page de résultats pour la tranche de prix [lo, hi] (hi=None = ouvert)."""160        params = {161            "latlng": "0,0", "locale": "fr", "no_facets": "",162            "rpp": str(RPP), "status": STATUS,163            "price": f"{lo}-{'' if hi is None else hi}",164        }165        if page > 1:166            params["page"] = str(page)167        data = self.get(API, params=params).json()168        meta = data.get("meta") or {}169        results = ((data.get("data") or {}).get("results")) or []170        return meta, results171172    def _to_vehicle(self, r: dict) -> Vehicle | None:173        ext_id = str(r.get("id") or "")174        slug = r.get("slug_fr") or r.get("slug_en") or ""175        if not ext_id or not slug:176            return None177178        price = r.get("price")179        price = float(price) if price and price >= 500 else None180        mileage = r.get("mileage")181        mileage = float(mileage) if mileage is not None else None182183        try:184            lat = float(r.get("latitude"))185            lng = float(r.get("longitude"))186        except (TypeError, ValueError):187            lat = lng = None188189        vin = (r.get("vin") or "").strip().upper()190        if not _VIN_RE.fullmatch(vin):191            vin = ""192193        details: dict = {}194        if r.get("status_fr"):195            details["otogo_status"] = r["status_fr"]   # Usagé | Certifié | Démo196197        return Vehicle(198            source=self.source_id,199            external_id=ext_id,200            url=f"{BASE}/auto/{slug}",201            kind="auto",202            title=r.get("title_fr") or r.get("title_en") or "",203            trim=(r.get("trim_fr") or r.get("trim_en") or "").strip(" |"),204            year=r.get("year"),205            price=price,206            price_label=(f"{price:,.0f} $".replace(",", " ") if price else ""),207            mileage_km=mileage,208            vin=vin,209            dealer_name=(r.get("dealer_name") or "").strip(),210            city=nearest_city(lat, lng),211            lat=lat,212            lng=lng,213            details=details,214            images=[u for u in [r.get("thumbnail")] if u],215        )216217    # -- contrat -----------------------------------------------------------------218219    def fetch(self) -> list[Vehicle]:220        cap = _max_listings()221        vehicles: dict[str, Vehicle] = {}222        # partition par prix : bissection récursive tant qu'une tranche223        # dépasse la profondeur maximale de l'API (~1 000 annonces)224        stack: list[tuple[int, int | None]] = [(0, 100_000), (100_000, None)]225        while stack:226            if cap and len(vehicles) >= cap:227                break228            lo, hi = stack.pop()229            meta, results = self._query(1, lo, hi)230            total = int(meta.get("total") or 0)231            if total == 0:232                continue233            if total > DEPTH:234                if hi is None:                      # tranche ouverte : décaler235                    stack.append((lo + 100_000, None))236                    stack.append((lo, lo + 100_000))237                    continue238                if hi - lo > PRICE_SPLIT_FLOOR:     # bissection239                    mid = (lo + hi) // 2240                    stack.append((mid, hi))241                    stack.append((lo, mid))242                    continue243                # tranche déjà minimale : on prend ce que la profondeur permet244            for r in results:245                v = self._to_vehicle(r)246                if v:247                    vehicles[v.external_id] = v248            pages = int(meta.get("pages") or 1)249            for page in range(2, pages + 1):250                if cap and len(vehicles) >= cap:251                    break252                try:253                    _, results = self._query(page, lo, hi)254                except Exception:255                    break                            # fin de pagination256                if not results:257                    break258                for r in results:259                    v = self._to_vehicle(r)260                    if v:261                        vehicles[v.external_id] = v262        return list(vehicles.values())263
Files main
Menu

Theme