SPB Git

Repository Public

normalize.py 21.7 KB 570 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/normalize.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# normalize.py : normalisation des champs véhicule — prix, kilométrage, année,91#                marque/modèle, transmission, carburant, motricité, carrosserie,92#                ville -> région administrative.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import re97import unicodedata9899__all__ = [100    "strip_accents", "parse_price", "price_is_from", "parse_mileage",101    "parse_year", "normalize_make", "split_title", "normalize_transmission",102    "normalize_fuel", "normalize_drivetrain", "normalize_body", "infer_region",103    "city_gps", "MAKES",104]105106107def strip_accents(text: str) -> str:108    return "".join(c for c in unicodedata.normalize("NFD", text)109                   if unicodedata.category(c) != "Mn")110111112# ---------------------------------------------------------------------------113# Prix et kilométrage114# ---------------------------------------------------------------------------115116_PRICE_RE = re.compile(r"(\d{1,3}(?:[  ,.]\d{3})+|\d{3,6})(?:[,.](\d{2}))?\s*\$")117_PRICE_BARE_RE = re.compile(r"\$\s*(\d{1,3}(?:[  ,.]\d{3})+|\d{3,6})")118119120def parse_price(label: str | None) -> float | None:121    """« 21 495 $ », « $21,495 », « 21495$ » -> 21495.0 (None si absent/0)."""122    if not label:123        return None124    m = _PRICE_RE.search(label) or _PRICE_BARE_RE.search(label)125    if not m:126        return None127    raw = re.sub(r"[  ,.]", "", m.group(1))128    try:129        value = float(raw)130    except ValueError:131        return None132    # bornes de vraisemblance pour une auto usagée133    if value < 300 or value > 500_000:134        return None135    return value136137138def price_is_from(label: str) -> bool:139    return bool(re.search(r"à partir|a partir|starting|from", label, re.I))140141142_KM_RE = re.compile(r"(\d{1,3}(?:[  ,.]\d{3})+|\d+)\s*km", re.I)143144145def parse_mileage(label: str | None) -> float | None:146    """« 45 678 km », « 45,678 KM » -> 45678.0."""147    if not label:148        return None149    m = _KM_RE.search(label)150    if not m:151        return None152    raw = re.sub(r"[  ,.]", "", m.group(1))153    try:154        value = float(raw)155    except ValueError:156        return None157    if value < 0 or value > 900_000:158        return None159    return value160161162_YEAR_RE = re.compile(r"\b(19[89]\d|20[0-3]\d)\b")163164165def parse_year(text: str | None) -> int | None:166    if not text:167        return None168    m = _YEAR_RE.search(text)169    return int(m.group(1)) if m else None170171172# ---------------------------------------------------------------------------173# Marques (canoniques) — clé = version sans accents/majuscules/espaces174# ---------------------------------------------------------------------------175176MAKES = [177    "Acura", "Alfa Romeo", "Aston Martin", "Audi", "Bentley", "BMW", "Buick",178    "Cadillac", "Chevrolet", "Chrysler", "Dodge", "Ferrari", "Fiat", "Fisker",179    "Ford", "Genesis", "GMC", "Honda", "Hummer", "Hyundai", "Infiniti",180    "Jaguar", "Jeep", "Kia", "Lamborghini", "Land Rover", "Lexus", "Lincoln",181    "Lotus", "Maserati", "Mazda", "McLaren", "Mercedes-Benz", "Mercury",182    "MINI", "Mitsubishi", "Nissan", "Oldsmobile", "Plymouth", "Polestar",183    "Pontiac", "Porsche", "RAM", "Rivian", "Rolls-Royce", "Saab", "Saturn",184    "Scion", "Smart", "Subaru", "Suzuki", "Tesla", "Toyota", "VinFast",185    "Volkswagen", "Volvo",186]187188_MAKE_ALIASES = {189    "mercedes": "Mercedes-Benz", "mercedesbenz": "Mercedes-Benz",190    "mercedesamg": "Mercedes-Benz", "vw": "Volkswagen", "chevy": "Chevrolet",191    "landrover": "Land Rover", "rangerover": "Land Rover", "mini": "MINI",192    "ram": "RAM", "gmc": "GMC", "bmw": "BMW", "alfa": "Alfa Romeo",193    "alfaromeo": "Alfa Romeo", "rollsroyce": "Rolls-Royce", "vinfast": "VinFast",194}195196_MAKE_LOOKUP = {strip_accents(m).lower().replace(" ", "").replace("-", ""): m197                for m in MAKES}198_MAKE_LOOKUP.update(_MAKE_ALIASES)199200# marques MOTO/SCOOTER (verticale moto — connectors/moto_dealers.py) :201# ajoutées au lookup de normalize_make SEULEMENT (pas à MAKES, pour ne pas202# influencer split_title côté autos). Sans elles, le repli .title() casserait203# les sigles : « KTM » → « Ktm », « CFMOTO » → « Cfmoto », etc.204_MOTO_MAKE_LOOKUP = {205    "harleydavidson": "Harley-Davidson", "harley": "Harley-Davidson",206    "indianmotorcycle": "Indian Motorcycle", "indian": "Indian Motorcycle",207    "ktm": "KTM", "brp": "BRP", "canam": "Can-Am",208    "cfmoto": "CFMOTO", "gasgas": "GASGAS", "kymco": "KYMCO",209    "mvagusta": "MV Agusta", "motoguzzi": "Moto Guzzi",210    "royalenfield": "Royal Enfield", "victorymotorcycles": "Victory",211    "victory": "Victory", "ssr": "SSR", "surron": "Sur-Ron",212}213_MAKE_LOOKUP.update(_MOTO_MAKE_LOOKUP)214215216def normalize_make(raw: str | None) -> str:217    if not raw:218        return ""219    key = strip_accents(raw.strip()).lower().replace(" ", "").replace("-", "")220    return _MAKE_LOOKUP.get(key, raw.strip().title() if raw.strip() else "")221222223# marques triées par longueur décroissante pour matcher « Land Rover » avant « Rover »224_MAKES_BY_LEN = sorted(MAKES + ["Mercedes"], key=len, reverse=True)225226227def split_title(title: str) -> tuple[int | None, str, str]:228    """« Toyota RAV4 2019 XLE AWD » ou « 2019 Toyota RAV4 » ->229    (année, marque, modèle+version). Champs vides si non détectés."""230    if not title:231        return None, "", ""232    year = parse_year(title)233    text = _YEAR_RE.sub(" ", title)234    flat = strip_accents(text).lower()235    for make in _MAKES_BY_LEN:236        mk = strip_accents(make).lower()237        idx = flat.find(mk)238        if idx >= 0:239            before = flat[idx - 1] if idx > 0 else " "240            after_i = idx + len(mk)241            after = flat[after_i] if after_i < len(flat) else " "242            if not before.isalnum() and not after.isalnum():243                model = text[after_i:].strip(" -–|,·")244                model = re.sub(r"\s{2,}", " ", model).strip()245                return year, normalize_make(make), model246    return year, "", text.strip()247248249# ---------------------------------------------------------------------------250# Transmission, carburant, motricité, carrosserie251# ---------------------------------------------------------------------------252253def normalize_transmission(raw: str | None) -> str:254    if not raw:255        return ""256    t = strip_accents(raw).lower()257    if "cvt" in t or "variation continue" in t:258        return "Automatique"          # CVT présentée comme automatique259    if "man" in t:260        return "Manuelle"261    if "auto" in t or "tiptronic" in t or "dsg" in t or "pdk" in t:262        return "Automatique"          # « Automatique 6 vitesses » = automatique263    if re.search(r"\b[56]\s?(vit|spd|speed)", t):264        return "Manuelle"             # « 6 vitesses » seul = boîte manuelle265    return ""266267268def normalize_fuel(raw: str | None) -> str:269    if not raw:270        return ""271    t = strip_accents(raw).lower()272    if "rechargeable" in t or "plug" in t or "phev" in t:273        return "Hybride rechargeable"274    if "hybrid" in t or "hybride" in t:275        return "Hybride"276    if "electr" in t or "ev" == t.strip() or "electric" in t:277        return "Électrique"278    if "diesel" in t or "tdi" in t:279        return "Diesel"280    if "essence" in t or "gas" in t or "petrol" in t or "sans plomb" in t:281        return "Essence"282    return ""283284285def normalize_drivetrain(raw: str | None) -> str:286    if not raw:287        return ""288    t = strip_accents(raw).lower()289    if "awd" in t or "4wd" in t or "4x4" in t or "integrale" in t or "all" in t \290            or "quattro" in t or "xdrive" in t or "4matic" in t or "4motion" in t:291        return "Intégrale / 4x4"292    if "rwd" in t or "propulsion" in t or "arriere" in t or "rear" in t:293        return "Propulsion"294    if "fwd" in t or "traction" in t or "avant" in t or "front" in t or "2wd" in t:295        return "Traction"296    return ""297298299# jetons STRICTS repérables dans un titre/une version (pas de faux positifs)300_DRIVE_TOKEN_RE = re.compile(301    r"\b(awd|4wd|4x4|4rm|quattro|xdrive|4matic|4motion|sh-awd|e-four|"302    r"traction integrale|integrale|awc)\b", re.I)303_RWD_TOKEN_RE = re.compile(r"\b(rwd|propulsion|sdrive)\b", re.I)304_FWD_TOKEN_RE = re.compile(r"\b(fwd|2rm|traction avant)\b", re.I)305306307def infer_drivetrain_from_text(text: str | None) -> str:308    """Motricité déduite des jetons explicites du titre/version (repli)."""309    if not text:310        return ""311    flat = strip_accents(text)312    if _DRIVE_TOKEN_RE.search(flat):313        return "Intégrale / 4x4"314    if _RWD_TOKEN_RE.search(flat):315        return "Propulsion"316    if _FWD_TOKEN_RE.search(flat):317        return "Traction"318    return ""319320321_FUEL_HR_RE = re.compile(r"\b(phev|plug-?in|hybride?\s+rechargeable)\b", re.I)322_FUEL_HYB_RE = re.compile(r"\b(hybride?|hybrid)\b", re.I)323_FUEL_EV_RE = re.compile(324    r"\b(electrique|electric|ev|bev|e-tron|ioniq \d|kona electric|"325    r"bolt|leaf|model [3sxy]|id\.?4)\b", re.I)326_FUEL_DIESEL_RE = re.compile(r"\b(diesel|tdi|duramax|cummins|ecodiesel)\b", re.I)327328329def infer_fuel_from_text(text: str | None) -> str:330    """Carburant déduit des jetons explicites du titre/version (repli).331332    Volontairement conservateur : ne regarde jamais la description333    (« sièges électriques » n'est pas un véhicule électrique).334    """335    if not text:336        return ""337    flat = strip_accents(text)338    if _FUEL_HR_RE.search(flat):339        return "Hybride rechargeable"340    if _FUEL_HYB_RE.search(flat):341        return "Hybride"342    if _FUEL_EV_RE.search(flat):343        return "Électrique"344    if _FUEL_DIESEL_RE.search(flat):345        return "Diesel"346    return ""347348349_BODY_MAP = [350    (("vus", "suv", "utilitaire", "crossover", "multisegment"), "VUS"),351    (("camionnette", "camion", "pickup", "pick-up", "truck", "cabine"), "Camionnette"),352    (("fourgonnette", "minivan", "mini-fourgonnette", "van", "fourgon"), "Fourgonnette"),353    (("cabriolet", "convertible", "decapotable"), "Cabriolet"),354    (("coupe",), "Coupé"),355    (("hayon", "hatchback", "a hayon", "5 portes"), "Hayon"),356    (("familiale", "wagon", "break"), "Familiale"),357    (("berline", "sedan", "4 portes"), "Berline"),358]359360361def normalize_body(raw: str | None) -> str:362    if not raw:363        return ""364    t = strip_accents(raw).lower()365    for keys, canon in _BODY_MAP:366        if any(k in t for k in keys):367            return canon368    return ""369370371# ---------------------------------------------------------------------------372# Ville -> région administrative du Québec373# ---------------------------------------------------------------------------374375_REGIONS: dict[str, tuple[str, ...]] = {376    "Capitale-Nationale": (377        "quebec", "ste-foy", "sainte-foy", "val-belair", "beauport", "charlesbourg",378        "loretteville", "l'ancienne-lorette", "ancienne-lorette", "donnacona",379        "cap-sante", "pont-rouge", "saint-augustin", "st-augustin", "baie-saint-paul",380        "la malbaie", "portneuf", "saint-raymond", "boischatel", "vanier",381    ),382    "Chaudière-Appalaches": (383        "levis", "saint-nicolas", "st-nicolas", "charny", "saint-romuald",384        "st-romuald", "saint-georges", "st-georges", "thetford", "montmagny",385        "sainte-marie", "ste-marie", "beauce", "saint-joseph", "lac-etchemin",386        "bernieres", "breakeyville", "laurier-station",387    ),388    "Montréal": (389        "montreal", "saint-leonard", "st-leonard", "anjou", "lasalle", "verdun",390        "dorval", "pointe-claire", "kirkland", "montreal-nord", "montreal-est",391        "ahuntsic", "villeray", "rosemont", "hochelaga", "lachine", "pierrefonds",392    ),393    "Laval": ("laval", "chomedey", "vimont", "duvernay", "sainte-rose", "ste-rose"),394    "Montérégie": (395        "longueuil", "brossard", "saint-hubert", "st-hubert", "boucherville",396        "chateauguay", "granby", "saint-hyacinthe", "st-hyacinthe", "sorel",397        "valleyfield", "salaberry", "vaudreuil", "saint-jean-sur-richelieu",398        "st-jean-sur-richelieu", "chambly", "beloeil", "la prairie", "candiac",399        "saint-constant", "st-constant", "varennes", "cowansville", "magog",400        "sainte-julie", "ste-julie", "mont-saint-hilaire", "acton vale",401        "carignan", "ile-perrot", "l'ile-perrot", "saint-basile", "st-basile",402        "marieville", "mont-saint-gregoire", "napierville", "saint-remi",403    ),404    "Laurentides": (405        "saint-jerome", "st-jerome", "blainville", "boisbriand", "mirabel",406        "saint-eustache", "st-eustache", "sainte-therese", "ste-therese",407        "lachute", "mont-tremblant", "sainte-agathe", "ste-agathe", "saint-sauveur",408        "st-sauveur", "rosemere", "deux-montagnes", "mont-laurier",409    ),410    "Lanaudière": (411        "joliette", "repentigny", "terrebonne", "mascouche", "l'assomption",412        "assomption", "rawdon", "berthierville", "lavaltrie", "saint-lin",413        "st-lin", "charlemagne",414    ),415    "Estrie": (416        "sherbrooke", "rock forest", "fleurimont", "coaticook", "windsor",417        "east angus", "lac-megantic", "asbestos", "val-des-sources", "bromont",418    ),419    "Mauricie": (420        "trois-rivieres", "shawinigan", "grand-mere", "louiseville", "nicolet",421        "la tuque", "cap-de-la-madeleine",422    ),423    "Centre-du-Québec": (424        "drummondville", "victoriaville", "plessisville", "becancour",425        "warwick", "princeville",426    ),427    "Saguenay–Lac-Saint-Jean": (428        "saguenay", "chicoutimi", "jonquiere", "alma", "roberval", "dolbeau",429        "saint-felicien", "st-felicien", "la baie",430    ),431    "Bas-Saint-Laurent": (432        "rimouski", "riviere-du-loup", "matane", "mont-joli", "amqui",433        "la pocatiere", "temiscouata", "trois-pistoles",434    ),435    "Gaspésie–Îles-de-la-Madeleine": (436        "gaspe", "caplan", "bonaventure", "carleton", "chandler", "new richmond",437        "sainte-anne-des-monts", "ste-anne-des-monts",438    ),439    "Côte-Nord": (440        "baie-comeau", "sept-iles", "port-cartier", "forestville", "havre-saint-pierre",441    ),442    "Abitibi-Témiscamingue": (443        "rouyn-noranda", "rouyn", "val-d'or", "val-dor", "amos", "la sarre",444        "ville-marie", "malartic", "senneterre",445    ),446    "Outaouais": (447        "gatineau", "hull", "aylmer", "buckingham", "maniwaki", "papineauville",448    ),449}450451_CITY_TO_REGION = {city: region for region, cities in _REGIONS.items()452                   for city in cities}453454455def infer_region(city: str | None) -> str:456    if not city:457        return ""458    key = strip_accents(city.strip()).lower()459    if key in _CITY_TO_REGION:460        return _CITY_TO_REGION[key]461    for c, region in _CITY_TO_REGION.items():462        if c in key:463            return region464    return ""465466467# ---------------------------------------------------------------------------468# Ville -> coordonnées GPS (recherche par rayon)469#470# Table statique data/villes_gps.json : ville normalisée -> [lat, lng]471# (centre-ville approximatif — la précision « ville » suffit pour un rayon).472# ---------------------------------------------------------------------------473474_VILLES_GPS: dict[str, tuple[float, float]] | None = None475476477def _load_villes_gps() -> dict[str, tuple[float, float]]:478    global _VILLES_GPS479    if _VILLES_GPS is None:480        import json481        from pathlib import Path482        path = Path(__file__).resolve().parent.parent / "data" / "villes_gps.json"483        table: dict[str, tuple[float, float]] = {}484        try:485            for name, coords in json.loads(path.read_text()).items():486                if isinstance(coords, (list, tuple)) and len(coords) == 2:487                    table[name] = (float(coords[0]), float(coords[1]))488        except (OSError, ValueError):489            pass490        _VILLES_GPS = table491    return _VILLES_GPS492493494def _gps_key(city: str) -> str:495    """Clé de recherche : minuscules, sans accents, st-/ste- développés."""496    key = strip_accents(str(city)).lower().replace("’", "'").strip()497    key = re.sub(r"\bst-", "saint-", key)498    key = re.sub(r"\bste-", "sainte-", key)499    return re.sub(r"\s{2,}", " ", key)500501502def city_gps(city: str | None) -> tuple[float, float] | None:503    """Coordonnées (lat, lng) du centre-ville pour une ville du Québec.504505    Correspondance exacte d'abord, puis par mot entier (« Blainville506    Signature » -> blainville) — jamais par sous-chaîne nue (« Laval »507    ne matche pas « Lavaltrie »).508    """509    if not city:510        return None511    table = _load_villes_gps()512    key = _gps_key(city)513    hit = table.get(key)514    if hit:515        return hit516    for name in sorted(table, key=len, reverse=True):517        if re.search(rf"(?<![\w-]){re.escape(name)}(?![\w-])", key):518            return table[name]519    return None520521522# ---------------------------------------------------------------------------523# GPS -> ville connue la plus proche (repli pour les sources qui ne524# fournissent QUE les coordonnées du vendeur, ex. le portail Otogo).525# Nom d'affichage : restauré avec accents depuis data/sources.json quand une526# source connue est dans la même ville, sinon clé de villes_gps.json en527# casse de titre.528# ---------------------------------------------------------------------------529530_CITY_DISPLAY: dict[str, str] | None = None531532533def _load_city_display() -> dict[str, str]:534    global _CITY_DISPLAY535    if _CITY_DISPLAY is None:536        import json537        from pathlib import Path538        table: dict[str, str] = {}539        path = Path(__file__).resolve().parent.parent / "data" / "sources.json"540        try:541            for s in json.loads(path.read_text(encoding="utf-8"))["sources"]:542                city = (s.get("city") or "").strip()543                if city:544                    table.setdefault(_gps_key(city), city)545        except (OSError, ValueError, KeyError):546            pass547        _CITY_DISPLAY = table548    return _CITY_DISPLAY549550551def nearest_city(lat: float | None, lng: float | None,552                 max_km: float = 40.0) -> str:553    """Ville du Québec (data/villes_gps.json) la plus proche du point donné.554555    Approximation équirectangulaire (suffisante à l'échelle du Québec) ;556    chaîne vide si aucune ville connue à moins de `max_km` km.557    """558    if lat is None or lng is None:559        return ""560    import math561    coslat = math.cos(math.radians(lat))562    best, best_d2 = "", float("inf")563    for name, (clat, clng) in _load_villes_gps().items():564        d2 = (clat - lat) ** 2 + ((clng - lng) * coslat) ** 2565        if d2 < best_d2:566            best, best_d2 = name, d2567    if not best or math.sqrt(best_d2) * 111.0 > max_km:568        return ""569    return _load_city_display().get(best) or best.title()570
Files main
Menu

Theme