Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/nomade.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-10-1514#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/nomade.py : connecteur Nomade Gestion Immobilière91# (nomadegestion.com — 16+ immeubles à Québec : Beauport, Charlesbourg,92# Val-Bélair, Lebourgneuf… dont Le Melozio, L'Astral, Le Nordet ph. 1-2 et93# Le Bélair qui ont leurs microsites). Refonte 2026-10 : le PDF mensuel94# (« Liste de prix et disponibilités », /s/*.pdf découvert sur la home95# Squarespace, parsé avec pdfplumber) a été remplacé par une mini-app96# rendue serveur sur liste.nomadegestion.com (embarquée en iframe depuis97# /liste-location). La page expose des <section class="building-section">98# (h2 nom, .owner-addr, .owner-link URL immeuble, data-photos UUIDs →99# /photo/<uuid>/image) et des <article class="unit"> avec data-type,100# data-rent (en cents), data-avail ("now" ou date ISO), .unit-meta (étage)101# et badges aria-label (inclusions). Le téléphone du concierge est derrière102# un POST /visit-phone avec jeton anti-bot + pot de miel : on n'y touche pas.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import html as _html107import re108109from ..schema import Listing, normalize_unit_type, strip_accents110from .base import BaseConnector111112BASE = "https://nomadegestion.com"113LISTE = "https://liste.nomadegestion.com"114LISTE_URL = f"{LISTE}/"115116SECTION_RE = re.compile(117 r'<section class="building-section"[^>]*>.*?'118 r'(?=<section\b|</main|</body|$)', re.S)119NO_AVAIL_RE = re.compile(r'<section class="no-availability"', re.S)120H2_RE = re.compile(r"<h2[^>]*>(.*?)</h2>", re.S)121ADDR_RE = re.compile(r'<p class="owner-addr"[^>]*>(.*?)</p>', re.S)122OWNER_LINK_RE = re.compile(r'class="owner-link"\s+href="([^"]+)"')123PHOTOS_RE = re.compile(r'data-photos="([^"]*)"')124TOTAL_RE = re.compile(r'data-total="(\d+)"')125UNIT_RE = re.compile(r'<article class="unit"([^>]*)>(.*?)</article>', re.S)126ATTR_RE = re.compile(r'data-(type|rent|avail)="([^"]*)"')127META_RE = re.compile(r'<span class="unit-meta">([^<]*)</span>')128RENT_LABEL_RE = re.compile(r'<div class="unit-rent">([^<]*)</div>')129AVAIL_LABEL_RE = re.compile(r'<span class="avail[^"]*"[^>]*>([^<]*)</span>')130INCL_RE = re.compile(r'<ul class="incl">(.*?)</ul>', re.S)131BADGE_RE = re.compile(r'aria-label="([^"]+)"')132FLOOR_NUM_RE = re.compile(r"^(\d+)")133134# immeubles connus (mot-clé du nom/adresse -> métadonnées stables) :135# adresse complète, secteur (si connu avec certitude), page de l'annonce136BUILDINGS = {137 "astral": {"slug": "astral", "name": "L'Astral",138 "address": "2500, rue de Beaubassin, Québec",139 "sector": "Beauport", "url": "https://www.lastral.ca"},140 "lajeunesse": {"slug": "nordet1", "name": "Le Nordet — Phase 1",141 "address": "2430, rue Gabriel-Lajeunesse, Québec",142 "sector": "Beauport",143 "url": "https://www.lenordet.com"},144 "cajuns": {"slug": "nordet2", "name": "Le Nordet — Phase 2",145 "address": "2500, rue des Cajuns, Québec",146 "sector": "Beauport", "url": "https://www.lenordet.com"},147 "pie xi": {"slug": "belair", "name": "Le Bélair",148 "address": "1200, boulevard Pie-XI Sud, Québec",149 "sector": "Val-Bélair", "url": "https://www.lebelair.ca"},150 "melozio": {"slug": "melozio", "name": "Le Melozio",151 "address": "4020, rue Adrien-Pouliot, Québec",152 "sector": "", "url": "https://www.melozio.ca"},153 "gros-pin": {"slug": "grospin", "name": "4155, rue de Gros-Pin",154 "address": "4155, rue de Gros-Pin, Québec",155 "sector": "Charlesbourg", "url": f"{BASE}/grospin"},156 "griffon": {"slug": "griffon", "name": "6395-6425, rue du Griffon",157 "address": "6395-6425, rue du Griffon, Québec",158 "sector": "", "url": f"{BASE}/griffon"},159 "belanger": {"slug": "belanger", "name": "445, avenue Bélanger",160 "address": "445, avenue Bélanger, Québec",161 "sector": "", "url": f"{BASE}/belanger"},162 "6311": {"slug": "6311", "name": "6311, avenue du Costebelle",163 "address": "6311, avenue du Costebelle, Québec",164 "sector": "", "url": f"{BASE}/6311"},165 "6315": {"slug": "6315", "name": "6315, avenue du Costebelle",166 "address": "6315, avenue du Costebelle, Québec",167 "sector": "", "url": f"{BASE}/6315"},168 "chutes": {"slug": "deschutes", "name": "Boul. des Chutes",169 "address": "1114-1140, boulevard des Chutes, Québec",170 "sector": "Beauport", "url": f"{BASE}/dc1"},171 "chapelier": {"slug": "mariechap", "name": "Marie-Chapelier",172 "address": "281-340, rue Marie-Chapelier, Québec",173 "sector": "", "url": f"{BASE}/mariechap"},174 "garnier": {"slug": "fgarnier", "name": "Françoise-Garnier",175 "address": "155-267, rue Françoise-Garnier, Québec",176 "sector": "Beauport", "url": f"{BASE}/fgarnier"},177 "louis xiv": {"slug": "edith", "name": "Boul. Louis-XIV et rue Édith",178 "address": "Boul. Louis-XIV et rue Édith, Québec",179 "sector": "Charlesbourg", "url": f"{BASE}/edith"},180}181182183def _flat(fragment: str) -> str:184 text = _html.unescape(fragment)185 text = re.sub(r"<[^>]+>", " ", text)186 return re.sub(r"[\s ]+", " ", text).strip()187188189class NomadeConnector(BaseConnector):190 source_id = "nomade"191 request_delay = 0.6192 max_images = 20193194 def fetch(self) -> list[Listing]:195 html = self.get(LISTE_URL).text196197 sections = SECTION_RE.findall(html)198 if not sections and not NO_AVAIL_RE.search(html):199 # gabarit remanié ≠ vrai zéro (pattern sotramont) : jamais de200 # zéro silencieux quand les sections d'immeubles ont disparu.201 raise RuntimeError(202 "nomade: aucune <section class=\"building-section\"> ni "203 f"section no-availability sur {LISTE_URL} — gabarit modifié ?")204205 listings: list[Listing] = []206 seen: dict[str, int] = {}207 announced = 0208209 for sec in sections:210 hm = H2_RE.search(sec)211 am = ADDR_RE.search(sec)212 name = _flat(hm.group(1)) if hm else ""213 addr = _flat(am.group(1)) if am else ""214 tm = TOTAL_RE.search(sec)215 announced += int(tm.group(1)) if tm else 0216217 # métadonnées connues de l'immeuble (slug/adresse/secteur stables)218 key = strip_accents(f"{name} {addr}".lower())219 building = None220 for kw, meta in BUILDINGS.items():221 if strip_accents(kw) in key:222 building = dict(meta)223 break224 if building is None: # immeuble inconnu : repli générique225 building = {"slug": re.sub(r"[^a-z0-9]+", "-",226 strip_accents(name.lower()))227 .strip("-") or "immeuble",228 "name": name,229 "address": addr or f"{name}, Québec",230 "sector": "", "url": f"{BASE}/liste-location"}231 lm = OWNER_LINK_RE.search(sec)232 if lm:233 building["url"] = lm.group(1)234235 pm = PHOTOS_RE.search(sec)236 images = [f"{LISTE}/photo/{u}/image"237 for u in (pm.group(1).split(",") if pm else []) if u]238239 for attrs, body in UNIT_RE.findall(sec):240 lst = self._unit_listing(building, dict(ATTR_RE.findall(attrs)),241 body, images, seen)242 if lst is not None:243 listings.append(lst)244245 if not listings and announced > 0:246 raise RuntimeError(247 "nomade: aucune unité parsée alors que les sections "248 f"annoncent {announced} logement(s) — parsing cassé ?")249 return listings250251 # -- carte d'unité (data-type / data-rent en cents / data-avail) ------------------252 def _unit_listing(self, building: dict, attrs: dict, body: str,253 images: list[str], seen: dict[str, int]) -> Listing | None:254 unit_type = normalize_unit_type(attrs.get("type", ""))255 if not unit_type:256 return None257258 try:259 price = int(attrs["rent"]) / 100.0260 except (KeyError, ValueError):261 return None262 if not 300 <= price <= 20000:263 return None264265 mm = META_RE.search(body)266 meta = _flat(mm.group(1)) if mm else ""267 fm = FLOOR_NUM_RE.match(meta)268 floor = fm.group(1) if fm else ("1" if "rez" in meta.lower() else "")269270 rm = RENT_LABEL_RE.search(body)271 price_label = _flat(rm.group(1)) if rm else f"{int(price)} $ / mois"272 avm = AVAIL_LABEL_RE.search(body)273 availability = _flat(avm.group(1)) if avm else ""274 avail_date = attrs.get("avail", "") or None # "now" ou ISO275276 amenities: list[str] = []277 im = INCL_RE.search(body)278 if im:279 amenities = [_html.unescape(b) for b in BADGE_RE.findall(im.group(1))]280281 base_id = re.sub(r"[^\w.\-]", "",282 f"{building['slug']}-{unit_type.replace('½', '.5')}"283 f"-{floor or 'x'}")284 seen[base_id] = seen.get(base_id, 0) + 1285 ext_id = base_id if seen[base_id] == 1 else f"{base_id}-{seen[base_id]}"286287 lst = Listing(288 source=self.source_id,289 external_id=ext_id,290 url=building["url"],291 title=f"{unit_type} — {building['name']}",292 address=building["address"],293 sector=building.get("sector", ""),294 city="Québec",295 unit_type=unit_type,296 price=price,297 price_label=price_label,298 availability=availability,299 availability_date=avail_date,300 description=f"Étage(s) : {floor}" if floor else meta,301 amenities=list(amenities),302 images=images[: self.max_images],303 )304 if floor:305 lst.amenities = lst.amenities + [f"Étage : {floor}"]306 return lst307