SPB Git

Repository Public

schema.py 9.9 KB 241 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/schema.py10# Description      : Schéma standard d'une annonce de véhicule usagé.11# Module           : autoka12# Repository       : https://git.spboucher.ai/auto-ka13# Created          : 2026-08-1214# Last Modified    : 2026-08-1815#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : None specified (no license file in this repository)81# Maintainer       : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# -----------------------------------------------------------------------------89# Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# schema.py : modèle de données standardisé (Vehicle) + normalisation centrale92# -----------------------------------------------------------------------------93"""Schéma standard d'une annonce de véhicule usagé.9495Chaque connecteur, peu importe le site source, produit des objets `Vehicle`96conformes à ce schéma. `finalize()` applique la couche de normalisation97commune (autoka/normalize.py) : prix, kilométrage, année/marque/modèle98déduits du titre, transmission/carburant/carrosserie canoniques, région99administrative — les connecteurs restent simples et remplissent le brut.100"""101from __future__ import annotations102103import hashlib104import json105from dataclasses import dataclass, field, asdict106107from .normalize import (  # ré-exportés pour les connecteurs108    city_gps,109    infer_region,110    normalize_body,111    normalize_drivetrain,112    normalize_fuel,113    normalize_make,114    normalize_transmission,115    parse_mileage,116    parse_price,117    parse_year,118    price_is_from,119    split_title,120    strip_accents,121)122123__all__ = [124    "Vehicle", "parse_price", "parse_mileage", "parse_year", "split_title",125    "normalize_make", "normalize_transmission", "normalize_fuel",126    "normalize_drivetrain", "normalize_body", "infer_region", "strip_accents",127    "city_gps",128]129130131@dataclass132class Vehicle:133    """Annonce de véhicule usagé standardisée Auto-Ka."""134135    source: str                      # id de la source (voir data/sources.json)136    external_id: str                 # identifiant chez la source (stock, VIN, slug)137    url: str                         # page de l'annonce chez le concessionnaire138    kind: str = "auto"               # verticale : auto | moto | scooter139    title: str = ""                  # ex. "Toyota RAV4 XLE 2019"140    make: str = ""                   # Toyota, Honda, ...141    model: str = ""                  # RAV4, Civic, ...142    trim: str = ""                   # XLE AWD, Sport, ...143    year: int | None = None144    price: float | None = None       # $ CAD affiché145    price_label: str = ""            # texte original (ex. "21 495 $ + tx")146    mileage_km: float | None = None147    mileage_label: str = ""          # texte original (ex. "45 678 km")148    transmission: str = ""           # Automatique | Manuelle149    fuel: str = ""                   # Essence | Diesel | Hybride | Hybride rechargeable | Électrique150    drivetrain: str = ""             # Traction | Propulsion | Intégrale / 4x4151    body_type: str = ""              # VUS | Berline | Camionnette | ...152    exterior_color: str = ""153    interior_color: str = ""154    engine: str = ""                 # ex. "2.5L 4 cyl."155    doors: int | None = None156    seats: int | None = None157    vin: str = ""158    stock_number: str = ""159    dealer_name: str = ""            # nom d'affichage du commerce160    city: str = ""                   # ville du concessionnaire161    region: str = ""                 # région administrative (déduite de city)162    lat: float | None = None         # GPS du concessionnaire (déduit de city —163    lng: float | None = None         #   data/villes_gps.json ; rayon de recherche)164    description: str = ""165    features: list[str] = field(default_factory=list)   # équipements (texte source)166    details: dict = field(default_factory=dict)         # champs structurés (JSON)167    images: list[str] = field(default_factory=list)     # URLs absolues168    carfax_url: str = ""169170    @property171    def uid(self) -> str:172        return f"{self.source}:{self.external_id}"173174    def content_hash(self) -> str:175        """Hash du contenu pour la détection de changements (pseudo-webhook)."""176        payload = asdict(self)177        blob = json.dumps(payload, sort_keys=True, ensure_ascii=False)178        return hashlib.sha256(blob.encode("utf-8")).hexdigest()179180    def finalize(self) -> "Vehicle":181        """Applique la normalisation commune. Appelé par le pipeline d'ingestion.182183        Idempotent ; ne remplace jamais une valeur explicite du connecteur.184        """185        self.title = " ".join((self.title or "").split())186187        # année / marque / modèle déduits du titre si absents188        t_year, t_make, t_model = split_title(self.title)189        if self.year is None:190            self.year = t_year191        if not self.make:192            self.make = t_make193        if not self.model and t_model:194            # retirer la version du modèle déduit si elle duplique trim195            self.model = t_model.split("  ")[0]196        self.make = normalize_make(self.make)197        self.model = " ".join(self.model.split())198199        if self.price is None:200            self.price = parse_price(self.price_label)201        if self.mileage_km is None:202            self.mileage_km = parse_mileage(self.mileage_label or self.description)203204        self.transmission = normalize_transmission(self.transmission) or self.transmission205        self.fuel = normalize_fuel(self.fuel) or self.fuel206        self.drivetrain = normalize_drivetrain(self.drivetrain) or self.drivetrain207        self.body_type = normalize_body(self.body_type) or self.body_type208209        # replis conservateurs depuis le titre/la version quand la source210        # n'expose pas le champ (jetons explicites seulement : AWD, PHEV…)211        badge = f"{self.title} {self.trim}"212        if not self.drivetrain:213            from .normalize import infer_drivetrain_from_text214            self.drivetrain = infer_drivetrain_from_text(badge)215        if not self.fuel:216            from .normalize import infer_fuel_from_text217            self.fuel = infer_fuel_from_text(badge)218219        if not self.region:220            self.region = infer_region(self.city)221222        # géolocalisation du concessionnaire (précision « ville » — suffit223        # pour la recherche par rayon) si le connecteur ne l'a pas fournie224        if self.lat is None or self.lng is None:225            gps = city_gps(self.city)226            if gps:227                self.lat, self.lng = gps228229        if self.price_label and price_is_from(self.price_label):230            self.details["price_from"] = True231232        # année plausible seulement233        if self.year is not None and not (1980 <= self.year <= 2027):234            self.year = None235236        # dédoublonner les images en préservant l'ordre237        seen: set[str] = set()238        self.images = [u for u in self.images239                       if u and not (u in seen or seen.add(u))]240        return self241
Files main
Menu

Theme