Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/localys.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/localys.py : connecteur Gestion Localys (gestionlocalys.com,91# 240+ unités). Site Next.js rendu serveur : /fr/logements liste les92# logements disponibles (cartes avec adresse, quartier, « 2 ch. · 1 sdb. »93# et prix « 1 500 $ / mois »), chaque fiche /fr/logements/<slug> fournit la94# description (avec **DISPONIBLE …**, sections #### Inclusions/Exclusions),95# les caractéristiques (« 2 ch. 1 sdb. 750 pi² ») et la galerie (photos96# ws.jumptools.com encodées dans /_next/image?url=…). Une annonce par97# logement ; external_id = slug ; fiches via le cache détail (clé = hash du98# texte de la carte).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104import urllib.parse105106from bs4 import BeautifulSoup107108from ..schema import Listing, parse_price109from .base import BaseConnector110111BASE = "https://www.gestionlocalys.com"112LIST_URL = f"{BASE}/fr/logements"113114# « 2558 Rue De Cadillac, Montréal (Mercier/Hochelaga-Maisonneuve), QC, … »115H1_RE = re.compile(116 r"^(?P<street>.+?),\s*(?P<city>[^,(]+?)\s*(?:\((?P<sector>[^)]+)\))?"117 r",\s*QC", re.S)118PRICE_RE = re.compile(r"([\d\s ]+)\$\s*/\s*mois")119CH_RE = re.compile(r"(\d+)\s*ch\.")120SDB_RE = re.compile(r"([\d.]+)\s*sdb\.")121SQFT_RE = re.compile(r"([\d\s ]+)\s*pi²")122NEXT_IMG_RE = re.compile(r'/_next/image\?url=([^&"\']+)')123DISPO_RE = re.compile(r"DISPONIBLE[^*\n]{0,40}", re.I)124125126def _clean_md(t: str) -> str:127 """Retire les marqueurs markdown (** et ####) du texte rendu."""128 return re.sub(r"\s+", " ", t.replace("**", " ").replace("####", " ")129 ).strip()130131132class LocalysConnector(BaseConnector):133 source_id = "localys"134 request_delay = 0.7135136 def fetch(self) -> list[Listing]:137 html = self.get(LIST_URL).text138 soup = BeautifulSoup(html, "html.parser")139140 # cartes : ancêtre du lien qui contient le prix141 cards: dict[str, str] = {} # slug -> texte de la carte142 for a in soup.find_all("a", href=True):143 if "/fr/logements/" not in a["href"]:144 continue145 slug = a["href"].rstrip("/").rsplit("/", 1)[-1]146 if slug in cards and cards[slug]:147 continue148 node, text = a, ""149 for _ in range(6):150 node = node.parent151 if node is None:152 break153 t = re.sub(r"\s+", " ", node.get_text(" ", strip=True))154 if "$" in t:155 text = t156 break157 cards[slug] = text158159 listings: list[Listing] = []160 for slug, card_text in cards.items():161 try:162 key = hashlib.sha1(card_text.encode("utf-8")).hexdigest()163 d = self.detail(slug, key,164 lambda s=slug: self._logement(s))165 lst = self._listing(slug, card_text, d)166 if lst:167 listings.append(lst)168 except Exception:169 continue170 return listings171172 def _logement(self, slug: str) -> dict:173 """Scrape la fiche : h1, description, caractéristiques, photos."""174 out: dict = {"h1": "", "desc": "", "carac": "", "images": []}175 html = self.get(f"{LIST_URL}/{slug}").text176 soup = BeautifulSoup(html, "html.parser")177 for s in soup.find_all("script"):178 s.decompose() # écarter le payload RSC de Next.js179 if soup.h1:180 out["h1"] = soup.h1.get_text(" ", strip=True)181 text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))182 i = text.find("/ mois")183 j = text.find("Caractéristiques")184 if i >= 0 and j > i:185 out["desc"] = text[i + len("/ mois"):j].strip()[:1500]186 if j >= 0:187 out["carac"] = text[j:j + 120]188 images = []189 for enc in NEXT_IMG_RE.findall(html):190 u = urllib.parse.unquote(enc)191 if u.startswith("http") and "jumptools.com" in u \192 and u not in images:193 images.append(u)194 out["images"] = images[:15]195 return out196197 def _listing(self, slug: str, card_text: str, d: dict) -> Listing | None:198 # fiche morte : la source amont (jumptools) renvoie sa page 404199 if "cannot be found" in d.get("desc", ""):200 return None201 h1 = d.get("h1") or ""202 street = city = sector = ""203 m = H1_RE.match(h1)204 if m:205 street = m.group("street").strip()206 city = m.group("city").strip()207 sector = (m.group("sector") or "").strip()208 address = ", ".join(x for x in (street, city) if x)209210 price = None211 pm = PRICE_RE.search(card_text) or PRICE_RE.search(d.get("carac", ""))212 if pm:213 price = parse_price(pm.group(1).strip() + " $")214 bedrooms = bathrooms = None215 blob = f"{card_text} {d.get('carac', '')}"216 bm = CH_RE.search(blob)217 if bm:218 bedrooms = float(bm.group(1))219 sm = SDB_RE.search(blob)220 if sm:221 try:222 bathrooms = float(sm.group(1))223 except ValueError:224 pass225 area = None226 am = SQFT_RE.search(d.get("carac", "")) or SQFT_RE.search(card_text)227 if am:228 try:229 area = float(re.sub(r"[\s ]", "", am.group(1)))230 except ValueError:231 pass232233 desc_raw = d.get("desc", "")234 availability = ""235 dm = DISPO_RE.search(desc_raw)236 if dm:237 availability = _clean_md(dm.group(0)).capitalize()238239 return Listing(240 source=self.source_id,241 external_id=slug,242 url=f"{LIST_URL}/{slug}",243 title=h1.replace(", QC, Canada", "") or slug,244 address=address,245 sector=sector,246 city=city or "Montréal",247 unit_type="",248 bedrooms=bedrooms,249 bathrooms=bathrooms,250 price=price,251 price_label=f"{pm.group(1).strip()} $ / mois" if pm else "",252 availability=availability,253 area_sqft=area,254 description=_clean_md(desc_raw),255 images=d.get("images", []),256 )257