Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/ototr.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/ototr.py : OTO Trois-Rivières — WordPress, thème « Motors »91# (stm_vehicles_listing). Pas d'API REST exposée ni de JSON-LD.92#93# Stratégie : le sitemap natif WP `/wp-sitemap-posts-listings-1.xml` recense94# les annonces (/listings/<slug>/). Chaque page détail est parsée en HTML95# (BeautifulSoup) : h1 = titre, .single-regular-price = prix, tableau96# .single-car-data = fiche technique (Odomètre, Carburant, Transmission,97# Propulsion, Carrosserie, Moteur, Couleurs…). Pages détail en cache BD98# (clé hebdomadaire).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import datetime103import os104import re105106from bs4 import BeautifulSoup107108from ..schema import Vehicle109from .base import BaseConnector110111_EXCLUDE_RE = re.compile(112 r"motoneige|vtt|bateau|ponton|motomarine|\bmoto\b|roulotte|remorque|"113 r"campeur|tracteur|souffleuse|scooter|spyder|atv", re.I)114115# vignettes WordPress (-350x205 etc.) à écarter de la galerie116_THUMB_RE = re.compile(r"-\d{2,4}x\d{2,4}\.(?:jpe?g|png|webp)$", re.I)117118# libellés de la fiche technique -> champ Vehicle119_SPEC_FIELDS = {120 "carrosserie": "body_type",121 "carburant": "fuel",122 "transmission": "transmission",123 "propulsion": "drivetrain",124 "moteur": "engine",125 "couleur exterieure": "exterior_color",126 "couleur interieure": "interior_color",127}128129130def _flat(text: str) -> str:131 from ..schema import strip_accents132 return strip_accents(" ".join(text.split())).strip().lower()133134135class OtoTroisRivieres(BaseConnector):136 source_id = "ototroisrivieres"137 base_url = "https://ototroisrivieres.com"138 dealer_name = "OTO Trois-Rivières"139 city = "Trois-Rivières"140 request_delay: float = 1.0141 max_details = 200142143 # -- sitemap ----------------------------------------------------------------144 def _vehicle_urls(self) -> list[str]:145 xml = self.get(f"{self.base_url}/wp-sitemap-posts-listings-1.xml").text146 return [loc.strip() for loc in re.findall(r"<loc>([^<]+)</loc>", xml)147 if "/listings/" in loc]148149 # -- page détail -> payload dict ---------------------------------------------150 def _fetch_detail(self, url: str) -> dict:151 soup = BeautifulSoup(self.get(url).text, "html.parser")152 payload: dict = {"specs": {}}153154 h1 = soup.find("h1")155 if h1:156 payload["title"] = " ".join(h1.get_text(" ", strip=True).split())157158 price_el = soup.select_one(".single-regular-price")159 if price_el:160 payload["price_label"] = price_el.get_text(" ", strip=True)161162 for row in soup.select(".single-car-data tr"):163 label = row.select_one(".t-label")164 value = row.select_one(".t-value")165 if label and value:166 payload["specs"][label.get_text(" ", strip=True)] = \167 value.get_text(" ", strip=True)168169 og_desc = soup.find("meta", attrs={"property": "og:description"})170 if og_desc and og_desc.get("content"):171 payload["description"] = og_desc["content"]172173 seen: set[str] = set()174 images = []175 candidates = [img.get("src") or img.get("data-src") or ""176 for img in soup.find_all("img")]177 candidates += [a.get("href") or "" for a in soup.find_all("a")]178 for src in candidates:179 if "/wp-content/uploads/" not in src or _THUMB_RE.search(src) \180 or not re.search(r"\.(?:jpe?g|png|webp)$", src, re.I):181 continue182 if src not in seen:183 seen.add(src)184 images.append(src)185 payload["images"] = images[:20]186 return payload187188 # -- contrat -----------------------------------------------------------------189 def fetch(self) -> list[Vehicle]:190 urls = self._vehicle_urls()191 week = datetime.date.today().isocalendar()192 cache_key = f"v1:{week.year}w{week.week}"193 cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))194195 vehicles: list[Vehicle] = []196 real_fetches = 0197 for url in urls:198 ext_id = url.rstrip("/").rsplit("/", 1)[-1]199200 def _fetch(u=url):201 return self._fetch_detail(u)202203 if real_fetches >= cap: # plafond : cache seulement204 from .. import db205 if self._detail_con is None:206 self._detail_con = db.connect()207 data = db.get_cached_detail(self._detail_con, self.source_id,208 ext_id, cache_key)209 if data is None:210 continue211 else:212 before = self._last_request213 data = self.detail(ext_id, cache_key, _fetch)214 if self._last_request != before:215 real_fetches += 1216 if not data or not data.get("title"):217 continue218 veh = self._to_vehicle(ext_id, url, data)219 if veh is not None:220 vehicles.append(veh)221 return vehicles222223 def _to_vehicle(self, ext_id: str, url: str, d: dict) -> Vehicle | None:224 title = d.get("title", "")225 if not title or _EXCLUDE_RE.search(title):226 return None227 if re.search(r"vendu", title, re.I): # annonce conservée mais vendue228 return None229 title = re.sub(r"\*+\s*", " ", title).strip()230231 fields = {"body_type": "", "fuel": "", "transmission": "",232 "drivetrain": "", "engine": "", "exterior_color": "",233 "interior_color": ""}234 mileage_label = ""235 details: dict = {}236 for label, value in (d.get("specs") or {}).items():237 key = _flat(label)238 if key.startswith("odom"):239 # le thème affiche « 10500 KMkm » — garder tel quel,240 # parse_mileage s'en accommode241 mileage_label = value242 elif key in _SPEC_FIELDS:243 fields[_SPEC_FIELDS[key]] = value244 else:245 details[label] = value246247 return Vehicle(248 source=self.source_id,249 external_id=ext_id,250 url=url,251 title=title.title() if title.isupper() else title,252 price_label=d.get("price_label", ""),253 mileage_label=mileage_label,254 dealer_name=self.dealer_name,255 city=self.city,256 description=" ".join(str(d.get("description") or "").split())[:4000],257 details=details,258 images=d.get("images") or [],259 **fields,260 )261