Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/lafrance_mathieu.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/lafrance_mathieu.py : connecteur Lafrance & Mathieu91# (lafrance-mathieu.com — Québec, Lévis, Val-Bélair, Beauport, etc.)92# Page liste /louer-appartement-quebec (+ filtres ?boroughs=N), une annonce93# par immeuble. La page détail /logement/<id> expose : adresse complète avec94# code postal, lat/lng (script JSON building-coordinates), commodités et95# caractéristiques (p.attribute-description : chat accepté, balcon, entrées96# laveuse-sécheuse/lave-vaisselle…), unités individuelles (numéro, étage,97# disponibilité, prix), année de construction, téléphone de l'immeuble.98# Fiches visitées via self.detail() (cache BD, max max_details/sync).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import json104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, infer_city, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://lafrance-mathieu.com"112LIST_URL = f"{BASE}/louer-appartement-quebec"113114_IMG_RE = re.compile(115 r'https://gilm-site-vitrine-production\.s3\.amazonaws\.com/'116 r'media/real_estate/[^"\s\)]+\.(?:jpg|jpeg|png|webp)')117_POSTAL_RE = re.compile(r"^[A-Z]\d[A-Z]\s?\d[A-Z]\d$")118_PHONE_RE = re.compile(r"\b\d{3}[-. ]\d{3}[-. ]\d{4}\b")119120121class _DetailBudget(Exception):122 """Budget de fiches détail atteint pour cette synchronisation."""123124125class LafranceMathieuConnector(BaseConnector):126 source_id = "lafrance_mathieu"127 max_details = 150 # nouvelles fiches détail max par synchronisation128129 # -- fiche immeuble ---------------------------------------------------------130 def _fetch_detail(self, url: str) -> dict:131 """Page /logement/<id> -> payload JSON-sérialisable (cache BD)."""132 html = self.get(url).text133 soup = BeautifulSoup(html, "html.parser")134 payload: dict = {}135136 # photos de l'immeuble (bucket S3)137 payload["images"] = list(dict.fromkeys(_IMG_RE.findall(html)))138139 # lat/lng structurés : <script id="building-coordinates">[{"loc": …}]140 sc = soup.find("script", id="building-coordinates")141 if sc and sc.string:142 try:143 coords = json.loads(sc.string)144 loc = (coords[0] or {}).get("loc") if coords else None145 if loc and len(loc) == 2:146 payload["lat"] = float(loc[0])147 payload["lng"] = float(loc[1])148 except (ValueError, TypeError, AttributeError, IndexError):149 pass150151 # adresse complète (bloc « À propos de l'immeuble » > Adresse)152 strong = soup.find("strong", string=re.compile(r"^\s*Adresse\s*$"))153 if strong:154 bloc = strong.find_parent("div")155 lignes = []156 for p in bloc.find_all("p") if bloc else []:157 t = " ".join(p.get_text(" ", strip=True).split())158 if not t or t == "Adresse":159 continue160 t = re.sub(r"[()]", "", t)161 lignes.append(t)162 if lignes:163 payload["address"] = ", ".join(lignes)164165 # « Plus d'informations » : étages / unités / année de construction166 for sub in soup.select("p.subtext"):167 label = sub.get_text(" ", strip=True).lower()168 val_el = sub.find_next_sibling("p")169 val = val_el.get_text(" ", strip=True) if val_el else ""170 if "année de construction" in label and val.isdigit():171 payload["construction_year"] = int(val)172 elif "nombre total" in label and val:173 payload["total_units"] = val174 elif "nombre d" in label and val:175 payload["building_floors"] = val176177 # commodités + caractéristiques (immeuble, unité, accès et services)178 amenities: list[str] = []179 for p in soup.select("p.attribute-description"):180 label = " ".join(p.get_text(" ", strip=True).split())181 if label and label not in amenities:182 amenities.append(label)183 payload["amenities"] = amenities184185 # unités individuelles : numéro (· étage), disponibilité, prix186 unites: list[dict] = []187 vus: set[tuple] = set()188 for hdr in soup.find_all("p", class_="small-header"):189 if hdr.get_text(strip=True).lower() != "unité":190 continue191 row = hdr.find_parent("div", class_="row")192 if row is None:193 continue194 textes = [" ".join(p.get_text(" ", strip=True).split())195 for p in row.find_all("p")]196 unite = {}197 for i, t in enumerate(textes):198 low = t.lower()199 if low == "unité" and i + 1 < len(textes):200 unite["numero"] = textes[i + 1]201 elif low == "disponibilité" and i + 1 < len(textes):202 unite["dispo"] = textes[i + 1]203 elif low == "à partir de" and i + 1 < len(textes):204 unite["prix"] = textes[i + 1]205 cle = tuple(sorted(unite.items()))206 if unite.get("numero") and cle not in vus: # modal = doublon207 vus.add(cle)208 unites.append(unite)209 payload["unites"] = unites210211 # téléphone spécifique à l'immeuble (panneau « S'informer »)212 panel = soup.select_one(".inquire-step-1")213 if panel:214 m = _PHONE_RE.search(panel.get_text(" ", strip=True))215 if m:216 payload["phone"] = m.group(0).replace(".", "-").replace(" ", "-")217218 return payload219220 def _enrich(self, lst: Listing) -> None:221 """Complète l'annonce avec la fiche immeuble (via cache self.detail)."""222 key = hashlib.sha1(223 f"{lst.price_label}|{lst.availability}|{'|'.join(lst.amenities)}"224 .encode("utf-8")).hexdigest()225226 def fetch_fn():227 if self._detail_fetches >= self.max_details:228 raise _DetailBudget()229 self._detail_fetches += 1230 return self._fetch_detail(lst.url)231232 try:233 payload = self.detail(lst.external_id, key, fetch_fn)234 except _DetailBudget:235 return236 if not payload:237 return238239 if payload.get("images"):240 lst.images = payload["images"]241 if payload.get("address"):242 lst.address = payload["address"]243 if payload.get("lat") is not None and payload.get("lng") is not None:244 lst.lat, lst.lng = payload["lat"], payload["lng"]245 if payload.get("amenities"):246 # la carte liste n'a que 3-4 icônes ; la fiche est complète247 lst.amenities = payload["amenities"]248 if payload.get("construction_year"):249 lst.details["construction_year"] = payload["construction_year"]250 if payload.get("phone"):251 lst.details.setdefault("contact", {})["phone"] = payload["phone"]252253 # animaux : items structurés « Chat accepté » / « Chien accepté »254 amen_txt = " | ".join(payload.get("amenities", [])).lower()255 chat = "chat accepté" in amen_txt or "chats acceptés" in amen_txt256 chien = "chien accepté" in amen_txt or "chiens acceptés" in amen_txt257 if "animaux acceptés" in amen_txt or (chat and chien):258 lst.pets = "oui"259 elif chat or chien:260 lst.pets = "conditions" # une seule espèce acceptée261262 # description : infos immeuble + liste des unités disponibles263 desc_parts: list[str] = []264 infos = []265 if payload.get("construction_year"):266 infos.append(f"construit en {payload['construction_year']}")267 if payload.get("total_units"):268 infos.append(payload["total_units"])269 if infos:270 desc_parts.append("Immeuble " + ", ".join(infos))271 for u in payload.get("unites", []):272 ligne = f"Unité {u.get('numero', '?')}"273 if u.get("dispo"):274 ligne += f" — disponibilité : {u['dispo']}"275 if u.get("prix"):276 ligne += f" — à partir de {u['prix']}"277 desc_parts.append(ligne)278 if desc_parts:279 lst.description = " | ".join(desc_parts)[:600]280281 # disponibilité de secours : première unité listée282 if not lst.availability:283 for u in payload.get("unites", []):284 if u.get("dispo"):285 lst.availability = u["dispo"]286 break287288 # -- contrat ---------------------------------------------------------------289 def fetch(self) -> list[Listing]:290 # 1) Découvrir tous les filtres d'arrondissement sur la page principale291 html = self.get(LIST_URL).text292 boroughs = sorted(set(re.findall(r"\?boroughs=(\d+)", html)))293 pages = [html] + [294 self.get(f"{LIST_URL}/?boroughs={b}").text for b in boroughs295 ]296297 # 2) Extraire toutes les cartes (dédupliquées par id)298 listings: dict[str, Listing] = {}299 for page in pages:300 soup = BeautifulSoup(page, "html.parser")301 for card in soup.select('a[href^="/logement/"]'):302 m = re.match(r"/logement/(\d+)", card.get("href", ""))303 if not m:304 continue305 ext_id = m.group(1)306 if ext_id in listings:307 continue308 borough_el = card.select_one(".apartment-borough")309 sector = ""310 if borough_el:311 # "Appartements · Beauport" -> "Beauport"312 sector = borough_el.get_text(" ", strip=True).split("·")[-1].strip()313 addr_el = card.select_one(".apartment-address")314 infos_el = card.select_one(".apartment-infos")315 avail_el = card.select_one(".apartment-availability")316 infos = infos_el.get_text(" ", strip=True) if infos_el else ""317 amenities = [img.get("alt", "").strip()318 for img in card.select("img[alt]")319 if img.get("alt") and img.get("alt") not in320 ("unit image", "")]321 address = addr_el.get_text(strip=True) if addr_el else ""322 listings[ext_id] = Listing(323 source=self.source_id,324 external_id=ext_id,325 url=f"{BASE}/logement/{ext_id}",326 title=address or f"Logement {ext_id}",327 address=address,328 sector=sector,329 city=infer_city(sector),330 unit_type=normalize_unit_type(infos),331 price=parse_price(infos),332 price_label=infos,333 availability=avail_el.get_text(strip=True) if avail_el else "",334 amenities=amenities,335 )336337 # 3) Fiche immeuble : adresse complète, lat/lng, commodités, unités…338 # via self.detail() (seules les fiches nouvelles/modifiées sont339 # réellement visitées, max self.max_details par synchronisation)340 self._detail_fetches = 0341 for lst in listings.values():342 try:343 self._enrich(lst)344 except Exception:345 continue346347 return list(listings.values())348