Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gbd.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/gbd.py : connecteur GBD Location (gbdlocation.com) — promoteur-91# locateur des Basses-Laurentides : Escapade (3045 chemin d'Oka) et92# Centrocité (2969-3019 boul. des Promenades) à Sainte-Marthe-sur-le-Lac,93# Triplex rue André (3159-3163), East River/Albatros (710-740 rue des94# Hérons, Saint-Eustache), Quartier Urbain (rue de la Salamandre,95# Deux-Montagnes). Site statique (HTML latin-1 rendu serveur) : l'accueil96# liste les pages /projets-locatifs/… ; chaque page projet publie97# « VILLE : … », « Nombre de Chambres : … », « Nombre de pièces : n ½ »,98# « Emplacement(s) : <adresses> » et les caractéristiques (li sans lien).99# Certaines pages historiques (Hudson River, La Vallée) sont mortes mais100# répondent 200 : détectées par l'absence de « VILLE : ». Aucun prix101# publié (jamais inventé). Granularité TYPOLOGIE par projet.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing110from .base import BaseConnector111112BASE = "https://www.gbdlocation.com"113114CITY_RE = re.compile(r"VILLE\s*:\s*([\wÀ-ÿ' -]{3,40}?)\s+Immeubles?\b", re.I)115BEDS_RE = re.compile(r"Nombre de [Cc]hambres\s*:\s*([\d, ]+(?:ou\s*\d+)?)")116TYPES_RE = re.compile(r"Nombre de pièces\s*:\s*((?:\d\s*½\s*(?:et\s*)?)+)", re.I)117TYPE_TOKEN_RE = re.compile(r"(\d)\s*½")118ADDR_RE = re.compile(r"Emplacements?\s*:\s*([^\n]{5,90}?)\s*"119 r"(?=(?:Situé|Projet|Les\s|À proximité|$))", re.I)120FLOORS_RE = re.compile(r"Immeubles?\s*:\s*(\d)\s*étages?", re.I)121122# graphies abrégées du site -> toponymes officiels123CITY_MAP = {124 "St-Eustache": "Saint-Eustache",125 "Ste-Marthe-sur-le-Lac": "Sainte-Marthe-sur-le-Lac",126}127128129class GbdConnector(BaseConnector):130 source_id = "gbd"131 request_delay = 0.8132133 def fetch(self) -> list[Listing]:134 listings: list[Listing] = []135 try:136 # HTML encodé latin-1 : bs4 détecte l'encodage depuis les octets137 home = BeautifulSoup(self.get(BASE + "/").content, "html.parser")138 except Exception:139 return listings140 paths: list[str] = []141 for a in home.select('a[href*="/projets-locatifs/"], '142 'a[href*="/locations-maisons"]'):143 href = (a.get("href") or "").split("#")[0]144 if href.startswith("/") and href.count("/") >= 2 \145 and href not in paths:146 paths.append(href)147 for path in paths:148 try:149 listings.extend(self._project(path))150 except Exception:151 continue # une page cassée ne bloque pas152 return listings153154 # -- page projet : ville, typologies, adresse, caractéristiques ------------155 def _project(self, path: str) -> list[Listing]:156 url = BASE + path157 soup = BeautifulSoup(self.get(url).content, "html.parser")158 text = soup.get_text(" ", strip=True)159 cm = CITY_RE.search(text)160 if cm is None:161 return [] # page morte (« Page d'erreur »)162 city = cm.group(1).strip()163 city = CITY_MAP.get(city, city)164165 h1 = soup.select_one("h1")166 name = h1.get_text(" ", strip=True) if h1 else path.strip("/")167 slug = path.rstrip("/").rsplit("/", 1)[-1]168169 tm = TYPES_RE.search(text)170 types = [f"{n}½" for n in TYPE_TOKEN_RE.findall(tm.group(1))] \171 if tm else []172 if not types:173 return []174175 beds_by_type: dict[str, float] = {}176 bm = BEDS_RE.search(text)177 if bm:178 nums = [float(n) for n in re.findall(r"\d+", bm.group(1))]179 if len(nums) == len(types): # « 2 ou 3 » -> 4½=2ch, 5½=3ch180 beds_by_type = dict(zip(types, nums))181 elif len(nums) == 1:182 beds_by_type = {t: nums[0] for t in types}183184 address = ""185 am = ADDR_RE.search(text)186 if am:187 address = am.group(1).strip(" ,.")188189 desc = ""190 for p in soup.select("p"):191 t = p.get_text(" ", strip=True)192 if len(t) > 80 and not t.startswith("*"):193 desc = t194 break195196 # caractéristiques : les <li> sans lien (les <li> de navigation en ont)197 amenities = []198 for li in soup.select("li"):199 if li.find("a") is None:200 t = li.get_text(" ", strip=True)201 if 8 < len(t) < 120 and t not in amenities:202 amenities.append(t)203204 images = []205 for img in soup.select("img"):206 src = img.get("src") or img.get("data-src") or ""207 if src.startswith("/images/") and re.search(r"\.(?:jpe?g|png|webp)$",208 src, re.I):209 full = BASE + src210 if full not in images and not re.search(r"logo|plan", full, re.I):211 images.append(full)212213 details: dict = {"building": name}214 fm = FLOORS_RE.search(text)215 if fm:216 details["floors"] = fm.group(1)217218 # une annonce par typologie (aucun prix publié par GBD)219 out: list[Listing] = []220 for ut in types:221 out.append(Listing(222 source=self.source_id,223 external_id=f"{slug}-{ut.replace('½', '.5')}",224 url=url,225 title=f"{name} — {ut}",226 address=address,227 city=city,228 unit_type=ut,229 bedrooms=beds_by_type.get(ut),230 price=None,231 price_label="",232 availability="Sur demande",233 description=desc[:2000],234 amenities=list(amenities),235 details=dict(details),236 images=images[:15],237 ))238 return out239