SPB Git

Repository Public

schema.py 10.1 KB 232 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/schema.py10# Description      : Schéma standard d'une propriété à vendre et normalisation11#                    des champs.12# Module           : immoka13# Repository       : https://git.spboucher.ai/immo-ka14# Created          : 2026-08-1215# Last Modified    : 2026-08-2716#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author           : Simon-Pierre Boucher22# Position         : Professor of Finance23# Institution      : Université du Québec en Outaouais (UQO)24# Department       : Département des sciences administratives25# Organization     : SP Boucher26#27# Website          : https://spboucher.ai28# Git              : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General          : info@spboucher.ai35# Professional     : contact@spboucher.ai36# Direct           : simon@spboucher.ai37# Research         : research@spboucher.ai38# Development      : dev@spboucher.ai39# Support          : support@spboucher.ai40# Security/Admin   : admin@spboucher.ai41# Notifications    : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification   : Public68# Distribution     : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License          : None specified (no license file in this repository)82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889# -----------------------------------------------------------------------------90# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)91# Auteur : Simon-Pierre Boucher — contact@spboucher.ai92# schema.py : modèle de données standardisé (PropertyListing)93# -----------------------------------------------------------------------------94"""Schéma standard d'une propriété à vendre et normalisation des champs.9596Chaque connecteur, peu importe l'agence source (RE/MAX, Sutton, Via Capitale…),97doit produire des objets `PropertyListing` conformes à ce schéma. La méthode98`finalize()` applique ensuite la couche de normalisation commune99(immoka/normalize.py) : prix, type de propriété canonique, superficies en pi²,100chambres/salles de bains… — les connecteurs restent simples et remplissent101les champs bruts.102"""103from __future__ import annotations104105import hashlib106import json107from dataclasses import dataclass, field, asdict108109from .normalize import (110    clean_address,111    clean_description,112    clean_title,113    extract_bedrooms_bathrooms,114    normalize_property_type,115    parse_area_sqft,116    parse_int,117    parse_lot_sqft,118    parse_price,119    parse_year,120    price_is_from,121    strip_accents,122)123124__all__ = ["PropertyListing"]125126127@dataclass128class PropertyListing:129    """Propriété à vendre standardisée Immo-Ka."""130131    source: str                       # id de l'agence (voir data/sources.json)132    external_id: str                  # identifiant chez la source (souvent le n° Centris/MLS)133    url: str                          # page de la propriété chez la source134    title: str = ""                   # ex. "Maison à étages à vendre — Lévis"135    address: str = ""                 # adresse civique136    sector: str = ""                  # quartier/arrondissement137    city: str = ""                    # Québec, Lévis, Montréal…138    region: str = ""                  # région administrative (Capitale-Nationale…)139    property_type: str = ""           # Maison, Condo, Duplex, Terrain… (canonique)140    price: float | None = None        # prix demandé ($ CAD)141    price_label: str = ""             # texte original (ex. "459 000 $ +tx")142    bedrooms: int | None = None       # chambres143    bathrooms: int | None = None      # salles de bains144    powder_rooms: int | None = None   # salles d'eau145    area_sqft: float | None = None    # superficie habitable (pi²)146    lot_sqft: float | None = None     # superficie du terrain (pi²)147    year_built: int | None = None148    mls: str = ""                     # numéro Centris/MLS si affiché par la source149    status: str = "a-vendre"          # a-vendre | vendu | conditionnel150    broker_name: str = ""             # courtier inscripteur151    broker_phone: str = ""152    agency: str = ""                  # sous-agence / bureau (ex. « Royal LePage Altitude »,153                                      #   « Groupe Sutton - Synergie ») — affichage des154                                      #   Sources par sous-agence155    description: str = ""156    features: list[str] = field(default_factory=list)  # caractéristiques (texte source)157    details: dict = field(default_factory=dict)        # champs structurés (JSON)158    images: list[str] = field(default_factory=list)    # URLs absolues159    lat: float | None = None160    lng: float | None = None161162    @property163    def uid(self) -> str:164        return f"{self.source}:{self.external_id}"165166    def content_hash(self) -> str:167        """Hash du contenu pour la détection de changements (pseudo-webhook)."""168        payload = asdict(self)169        blob = json.dumps(payload, sort_keys=True, ensure_ascii=False)170        return hashlib.sha256(blob.encode("utf-8")).hexdigest()171172    def finalize(self) -> "PropertyListing":173        """Applique la normalisation commune. Appelé par le pipeline d'ingestion.174175        Idempotent ; ne remplace jamais une valeur explicite du connecteur.176        """177        self.title = clean_title(self.title)178        self.address = clean_address(self.address)179        self.city = (self.city or "").strip()180        self.property_type = normalize_property_type(self.property_type)181        self.description = clean_description(self.description)182183        # galerie : URLs valides seulement, placeholders retirés, doublons184        # (même photo en deux tailles) dédupliqués — voir immoka/imgaudit.py185        from .imgaudit import clean_gallery186        self.images = clean_gallery(self.images)187188        if self.price is None:189            self.price = parse_price(self.price_label)190        if self.price_label and price_is_from(self.price_label):191            self.details.setdefault("price_from", True)192193        # promotion details -> colonnes : les champs structurés de la fiche194        # (tableau Centris) priment sur l'extraction de texte libre ci-dessous195        if not self.property_type:196            for k in ("Type de propriété", "Genre de propriété"):197                if self.details.get(k):198                    self.property_type = normalize_property_type(str(self.details[k]))199                    break200        if self.year_built is None and self.details.get("Année de construction"):201            self.year_built = parse_year(self.details["Année de construction"])202        if self.area_sqft is None and self.details.get("Superficie habitable"):203            self.area_sqft = parse_area_sqft(str(self.details["Superficie habitable"]))204        if self.lot_sqft is None and self.details.get("Superficie du terrain"):205            self.lot_sqft = parse_lot_sqft(str(self.details["Superficie du terrain"]))206207        texte = " ".join(filter(None, (self.title, self.description,208                                       " ".join(self.features))))209        if self.bedrooms is None or self.bathrooms is None:210            beds, baths = extract_bedrooms_bathrooms(texte)211            if self.bedrooms is None:212                self.bedrooms = beds213            if self.bathrooms is None:214                self.bathrooms = baths215        if self.area_sqft is None:216            self.area_sqft = parse_area_sqft(texte)217        if self.lot_sqft is None and "terrain" in strip_accents(texte.lower()):218            self.lot_sqft = parse_lot_sqft(texte)219        self.year_built = parse_int(self.year_built)220221        # sous-agence : à défaut, on retombe sur le courtier/agence inscripteur222        if not self.agency:223            self.agency = self.broker_name224225        # coordonnées fournies par la source : rejeter tout point hors du226        # territoire couvert — Québec + Ontario (lat/lng inversés, 0/0, coquilles)227        if self.lat is not None and self.lng is not None:228            if not (41.6 <= self.lat <= 63.0 and -95.5 <= self.lng <= -56.0):229                self.lat = self.lng = None230231        return self232
Files main
Menu

Theme