Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/firma.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/firma.py : connecteur Groupe Firma (groupefirma.ca)91# Condos locatifs en Montérégie / banlieue sud-ouest de Montréal92# (Salaberry-de-Valleyfield, Saint-Zotique, Sainte-Barbe, L'Île-Perrot...).93# Découverte des immeubles via l'API REST WordPress (post type "housing"),94# puis parsing des fiches /logement/<slug>/ : unités <li id="unit-NNN">95# avec type, disponibilité, étage, superficie, commodités (icônes bjm-active)96# et images (plan + galerie de l'unité). Le prix est présent dans un97# commentaire HTML "<!-- - 1380$ / mois -->" (souvent vide).98# Lachute (Laurentides, hors Grand Montréal) est exclue.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import html as htmllib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price, strip_accents108from .base import BaseConnector109110BASE = "https://groupefirma.ca"111API_URL = f"{BASE}/wp-json/wp/v2/housing?per_page=100"112113# Municipalités admissibles (Montérégie sud-ouest / Grand Montréal).114_ALLOWED_CITY_KEYS = (115 "valleyfield", "saint-zotique", "st-zotique", "sainte-barbe", "ste-barbe",116 "saint-louis-de-gonzague", "st-louis-de-gonzague", "ile-perrot",117 "saint-timothee", "st-timothee", "les-coteaux", "coteau-du-lac",118 "vaudreuil", "pincourt", "beauharnois", "chateauguay",119)120121# Normalisation des noms de villes rencontrés dans les adresses.122_CITY_CANON = {123 "valleyfield": "Salaberry-de-Valleyfield",124 "salaberry-de-valleyfield": "Salaberry-de-Valleyfield",125 "saint-zotique": "Saint-Zotique",126 "st-zotique": "Saint-Zotique",127 "ste-barbe": "Sainte-Barbe",128 "sainte-barbe": "Sainte-Barbe",129 "st-louis-de-gonzague": "Saint-Louis-de-Gonzague",130 "saint-louis-de-gonzague": "Saint-Louis-de-Gonzague",131 "st-timothee": "Saint-Timothée",132 "saint-timothee": "Saint-Timothée",133 "l'ile-perrot": "L'Île-Perrot",134 "lile-perrot": "L'Île-Perrot",135 "ile-perrot": "L'Île-Perrot",136}137138_PRICE_COMMENT_RE = re.compile(r"<!--\s*-?\s*([\d\s,.]*)\$\s*/\s*mois\s*-->")139_IMG_RE = re.compile(r"\.(?:jpg|jpeg|png|webp)(?:$|\?)", re.I)140_ICON_RE = re.compile(r"-ico\.|icon|logo|favicon", re.I)141142143def _canon_city(raw: str) -> str:144 key = strip_accents(raw.strip().lower()).replace("’", "'")145 key = re.sub(r"\s+qc\.?$", "", key).strip(" ,")146 return _CITY_CANON.get(key, raw.strip(" ,"))147148149def _city_allowed(raw: str) -> bool:150 key = strip_accents(raw.strip().lower()).replace(" ", "-").replace("’", "'")151 return any(tok in key for tok in _ALLOWED_CITY_KEYS)152153154class FirmaConnector(BaseConnector):155 source_id = "firma"156 request_delay = 0.6157 max_buildings = 40 # garde-fou de crawl158159 def fetch(self) -> list[Listing]:160 listings: list[Listing] = []161 try:162 buildings = self.get(API_URL).json()163 except Exception:164 return listings165 if not isinstance(buildings, list):166 return listings167168 for i, b in enumerate(buildings):169 if i >= self.max_buildings:170 break171 try:172 listings.extend(self._parse_building(b))173 except Exception:174 continue175 return listings176177 # -- une fiche d'immeuble --------------------------------------------------178 def _parse_building(self, b: dict) -> list[Listing]:179 slug = b.get("slug") or ""180 url = b.get("link") or f"{BASE}/logement/{slug}/"181 name = htmllib.unescape((b.get("title") or {}).get("rendered") or slug)182 name = re.sub(r"\s+", " ", name).strip()183184 html = self.get(url).text185 soup = BeautifulSoup(html, "html.parser")186187 # Bloc d'en-tête : nom + adresse civique de l'immeuble188 address = ""189 addr_el = soup.select_one(".bjm-singlehousing-details-bluebox-address")190 if addr_el:191 address = addr_el.get_text(" ", strip=True)192 city_raw = address.split(",")[-1].strip() if "," in address else ""193 if not city_raw or not _city_allowed(city_raw):194 return [] # hors Grand Montréal (ex. Lachute)195 city = _canon_city(city_raw)196197 desc_el = soup.select_one(".bjm-singlehousing-details-description")198 description = (desc_el.get_text(" ", strip=True)[:600] if desc_el else "")199200 # Commodités de l'immeuble (icônes actives du bloc de détails)201 building_amenities: list[str] = []202 for item in soup.select(".bjm-singlehousing-details-icons-item"):203 img = item.select_one("img.bjm-active")204 if img:205 label = item.get_text(" ", strip=True)206 if label:207 building_amenities.append(label)208209 # Images de secours : galerie « photos du projet »210 fallback_imgs = self._section_images(soup.find(id="bjm-singlehousing-photos"))211212 results: list[Listing] = []213 for li in soup.select('li[id^="unit-"]'):214 lst = self._parse_unit(li, slug, url, name, address, city,215 description, building_amenities,216 fallback_imgs)217 if lst:218 results.append(lst)219 return results220221 # -- une unité (li id="unit-NNN") -----------------------------------------222 def _parse_unit(self, li, slug: str, url: str, name: str, address: str,223 city: str, description: str, building_amenities: list[str],224 fallback_imgs: list[str]) -> Listing | None:225 unit_no = (li.get("id") or "").replace("unit-", "").strip()226 if not unit_no:227 return None228229 num_el = li.select_one(".bjm-unit-number")230 label = num_el.get_text(strip=True).lstrip("#") if num_el else unit_no231232 h3 = li.find("h3")233 type_raw = h3.get_text(" ", strip=True) if h3 else ""234 unit_type = normalize_unit_type(type_raw)235236 # Prix : masqué dans un commentaire HTML "<!-- - 1380$ / mois -->"237 price = None238 price_label = ""239 m = _PRICE_COMMENT_RE.search(str(li))240 if m and re.search(r"\d", m.group(1)):241 price_label = f"{m.group(1).strip()}$ / mois"242 price = parse_price(price_label)243244 # Disponibilité : badge + date du bloc de texte245 avail_el = li.select_one(".bjm-det-label")246 availability = avail_el.get_text(" ", strip=True) if avail_el else ""247 details_txt = li.get_text(" ", strip=True)248 dm = re.search(r"Disponibilit[ée]\s*:\s*([\d/]+)", details_txt)249 if dm:250 availability = (f"{availability} ({dm.group(1)})"251 if availability else dm.group(1))252253 # Champs structurés de la fiche d'unité : étage, superficies (pi²)254 details: dict = {}255 area_sqft = None256 extras = []257 fm = re.search(r"[ÉE]tage\s*:\s*([^\s].{0,30}?)(?:\s{2,}|Superficie)",258 details_txt)259 if fm:260 floor_txt = fm.group(1).strip()261 extras.append(f"Étage : {floor_txt}")262 if floor_txt.isdigit() and 0 < int(floor_txt) <= 60:263 details["floor"] = int(floor_txt)264 sm = re.search(r"Superficie\s*:\s*(\d[\d\s.,]*)", details_txt)265 if sm:266 extras.append(f"Superficie : {sm.group(1).strip()} pi²")267 try:268 v = float(sm.group(1).strip().replace(" ", "")269 .replace(",", "."))270 if 80 <= v <= 20000:271 # explicite : sinon le parsing générique prendrait le min272 # avec la superficie du balcon ci-dessous273 area_sqft = v274 except ValueError:275 pass276 bm = re.search(r"Superficie du balcon\s*:\s*(\d[\d\s.,]*)", details_txt)277 if bm:278 extras.append(f"Superficie du balcon : {bm.group(1).strip()} pi²")279 unit_desc = " | ".join(extras)280 full_desc = " — ".join(p for p in (unit_desc, description) if p)[:600]281282 # Commodités de l'unité : icônes actives seulement283 amenities = [img.get("alt", "").strip()284 for img in li.select("img.bjm-active[alt]")285 if img.get("alt", "").strip()]286 amenities = list(dict.fromkeys(amenities + building_amenities))287288 # Images : plan + galerie propres à l'unité, sinon photos du projet289 images = self._section_images(li)290 if not images:291 images = fallback_imgs292293 return Listing(294 source=self.source_id,295 external_id=f"{slug}-{unit_no}",296 url=url,297 title=f"{name} — {unit_type or 'unité'} #{label}".strip(),298 address=address,299 sector="",300 city=city,301 unit_type=unit_type,302 price=price,303 price_label=price_label,304 availability=availability,305 area_sqft=area_sqft,306 description=full_desc,307 amenities=amenities,308 details=details,309 images=images,310 )311312 # -- images d'une section (liens lightbox + <img>) -------------------------313 @staticmethod314 def _section_images(node) -> list[str]:315 if node is None:316 return []317 urls: list[str] = []318 for a in node.select("a[href]"):319 href = a.get("href") or ""320 if _IMG_RE.search(href):321 urls.append(href)322 for img in node.select("img[src]"):323 src = img.get("src") or ""324 if _IMG_RE.search(src) and "uploads" in src:325 urls.append(src)326 out: list[str] = []327 for u in urls:328 if not u.startswith("http"):329 u = BASE + u330 if not _ICON_RE.search(u):331 out.append(u)332 return list(dict.fromkeys(out))[:25]333