Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/schema.py10# Description : Schéma standard d'une annonce (Listing) et normalisation11# des champs.12# Module : louka13# Repository : https://git.spboucher.ai/lou-ka14# Created : 2026-08-0615# 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# Lou-Ka — Agrégateur de logements à louer (province de Québec)91# Auteur : Simon-Pierre Boucher — contact@spboucher.ai92# schema.py : modèle de données standardisé (Listing) + enrichissement central93# -----------------------------------------------------------------------------94"""Schéma standard d'une annonce (Listing) et normalisation des champs.9596Chaque connecteur, peu importe le site source, doit produire des objets97`Listing` conformes à ce schéma. La méthode `finalize()` applique ensuite98la couche de normalisation commune (louka/normalize.py) : dates ISO,99superficie en pi², commodités canoniques, prix… — les connecteurs peuvent100donc rester simples et remplir les champs bruts.101"""102from __future__ import annotations103104import hashlib105import json106from dataclasses import dataclass, field, asdict107108from .normalize import ( # ré-exportés pour les connecteurs existants109 bedrooms_from_unit_type,110 clean_address,111 clean_city,112 clean_sector,113 coerce_count,114 extract_details,115 merge_details,116 normalize_unit_type,117 parse_area_sqft,118 parse_availability_date,119 parse_bathrooms,120 parse_bedrooms,121 parse_price,122 price_is_from,123 strip_accents,124)125126__all__ = [127 "Listing", "infer_city", "normalize_unit_type", "parse_price",128 "parse_availability_date", "parse_area_sqft", "clean_address",129 "strip_accents",130]131132133@dataclass134class Listing:135 """Annonce standardisée Lou-Ka."""136137 source: str # id de la source (voir data/sources.json)138 external_id: str # identifiant chez la source139 url: str # page de l'annonce chez la source140 title: str = "" # ex. "555, avenue du Fleuve"141 address: str = "" # adresse civique142 sector: str = "" # quartier/arrondissement (ex. Beauport)143 city: str = "" # Québec, Lévis, ...144 province: str = "QC" # "QC" | "ON" (expansion Ontario 2026-08)145 unit_type: str = "" # 1½ … 5½, 6½+, Studio, Loft, Chambre…146 bedrooms: float | None = None # chambres fermées (convention QC : 4½ = 2)147 bathrooms: float | None = None # salles de bain (1.5 = salle d'eau en plus)148 price: float | None = None # loyer mensuel ($ CAD), le plus bas si "à partir de"149 price_label: str = "" # texte original (ex. "à partir de 799$")150 availability: str = "" # texte original (ex. "Libre immédiatement")151 availability_date: str | None = None # ISO "2026-07-01", "now", ou None152 area_sqft: float | None = None # superficie en pi²153 pets: str | None = None # "oui" | "non" | "conditions" | None154 furnished: bool | None = None # meublé (None = inconnu)155 description: str = ""156 digest: dict | None = None # description structurée (louka/textmine.py)157 amenities: list[str] = field(default_factory=list) # texte source, pour affichage158 details: dict = field(default_factory=dict) # champs structurés (JSON)159 images: list[str] = field(default_factory=list) # URLs absolues160 lat: float | None = None161 lng: float | None = None162163 @property164 def uid(self) -> str:165 return f"{self.source}:{self.external_id}"166167 def content_hash(self) -> str:168 """Hash du contenu pour la détection de changements (pseudo-webhook)."""169 payload = asdict(self)170 blob = json.dumps(payload, sort_keys=True, ensure_ascii=False)171 return hashlib.sha256(blob.encode("utf-8")).hexdigest()172173 def finalize(self) -> "Listing":174 """Applique la normalisation commune. Appelé par le pipeline d'ingestion.175176 Idempotent ; ne remplace jamais une valeur explicite du connecteur.177 """178 import html as _html179 self.title = _html.unescape(self.title).strip()180 self.address = clean_address(_html.unescape(self.address))181 self.sector = clean_sector(self.sector)182 self.city = clean_city(self.city)183 self.unit_type = normalize_unit_type(self.unit_type)184185 if self.price is None:186 self.price = parse_price(self.price_label)187 if self.availability_date is None:188 self.availability_date = parse_availability_date(self.availability)189 if self.area_sqft is None:190 for texte in (self.description, " ".join(self.amenities), self.title):191 self.area_sqft = parse_area_sqft(texte)192 if self.area_sqft is not None:193 break194195 # coordonnées fournies par la source : rejeter tout point hors du196 # territoire couvert (lat/lng inversés, 0/0, coquilles) — le géocodeur197 # prendra le relais sur l'adresse plutôt que d'afficher un point au198 # Kazakhstan. QC : 44.5–63°N / -80–-56°E ; ON (expansion 2026-08) :199 # 41.6°N (Windsor/Pelée) à 56.9°N, -95.2°E (Kenora) à -74.3°E.200 if self.lat is not None and self.lng is not None:201 prov = (self.province or "QC").upper()202 if prov == "ON":203 ok = 41.6 <= self.lat <= 56.9 and -95.3 <= self.lng <= -74.3204 else:205 ok = 44.5 <= self.lat <= 63.0 and -80.0 <= self.lng <= -56.0206 if not ok:207 self.lat = self.lng = None208209 derived = extract_details(self.amenities, self.description, self.title)210 if self.price_label and price_is_from(self.price_label):211 derived["price_from"] = True212 self.details = merge_details(self.details, derived)213214 # chambres / salles de bain : valeur explicite du connecteur d'abord,215 # puis champs structurés de details, puis type d'unité (n½ -> n-2),216 # puis extraction texte — jamais de valeur inventée (None = inconnu)217 if self.bedrooms is None:218 for k in ("bedrooms", "Chambres", "Chambre(s)"):219 self.bedrooms = coerce_count(self.details.get(k))220 if self.bedrooms is not None:221 break222 if self.bedrooms is None:223 self.bedrooms = bedrooms_from_unit_type(self.unit_type)224 if self.bedrooms is None:225 self.bedrooms = parse_bedrooms(self.title, " | ".join(self.amenities),226 self.description)227 if self.bathrooms is None:228 for k in ("bathrooms", "Salles de bain", "Salle de bain",229 "Salle(s) de bain"):230 self.bathrooms = coerce_count(self.details.get(k))231 if self.bathrooms is not None:232 break233 if self.bathrooms is None:234 self.bathrooms = parse_bathrooms(" | ".join(self.amenities),235 self.description)236237 # description structurée (nettoyage + extraction + sections)238 if self.digest is None and self.description:239 try:240 from .textmine import analyser241 self.digest = analyser(self.description, price=self.price,242 sector=self.sector, city=self.city)243 except ImportError:244 pass # module absent : la fiche affichera le texte brut245246 if self.pets is None:247 self.pets = self.details.get("pets")248 else:249 self.details["pets"] = self.pets250 if self.furnished is None:251 furn = self.details.get("furnished")252 self.furnished = furn if isinstance(furn, bool) else None253 else:254 self.details["furnished"] = self.furnished255 return self256257258# ---------------------------------------------------------------------------259# Secteur -> ville (agglomération Québec / Lévis)260# ---------------------------------------------------------------------------261262_LEVIS_SECTORS = {263 "levis", "saint-romuald", "st-romuald", "charny", "saint-nicolas",264 "st-nicolas", "saint-david", "st-david", "desjardins", "saint-redempteur",265 "st-redempteur", "breakeyville", "saint-jean-chrysostome", "st-jean-chrysostome",266 "pintendre", "saint-etienne", "vieux-levis",267}268269270def infer_city(sector: str, default: str = "Québec") -> str:271 key = strip_accents((sector or "").strip().lower())272 if key in _LEVIS_SECTORS or "levis" in key:273 return "Lévis"274 return default275