Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/halfred.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-09-1714#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/halfred.py : connecteur Halfred (halfred.ca — Outaouais)91# Application React Router (plateforme Eversa) rendue CÔTÉ SERVEUR. Depuis92# la refonte « Editorial » de ~2026-09-17, toutes les routes portent un93# préfixe de locale (/fr, /en) : la liste est /fr/listings/list, dont le94# HTML contient déjà toutes les cartes (aucun JavaScript requis). Chaque95# carte est un <a data-sentry-component="EditorialListingCard"> :96# - le lien /fr/listings/<slug>/details (ou /fr/listings/project/<uuid>/97# details pour les projets) -> external_id stable, préfixe retiré ;98# - l'adresse civique (h3), le lieu « Secteur · Ville » (p qui suit),99# les SpecItem textuels (chambres, salles de bain, pi²), la pill100# « Disponible le … » et le prix (« À partir de $1,559 », ancien prix101# barré .line-through quand il y a une promotion).102# La fiche /details ajoute la description (RichTextDisplay), la galerie,103# les Walk/Bike Score® et le contact du bureau.104# Elle passe par self.detail(...) (cache BD) avec un plafond par sync : le105# robots.txt du site impose « Crawl-delay: 10 » — request_delay = 10 s.106# Le site est bilingue : en-tête Accept-Language fr-CA pour obtenir le107# français (« 2 chambres », « Disponible maintenant »).108# -----------------------------------------------------------------------------109from __future__ import annotations110111import hashlib112import re113114from bs4 import BeautifulSoup115116from ..schema import (Listing, normalize_unit_type, parse_area_sqft,117 parse_price)118from .base import BaseConnector119120BASE = "https://www.halfred.ca"121LIST_URL = f"{BASE}/fr/listings/list"122123# Villes/secteurs de l'agglomération de Gatineau (fusion 2002) : la ville124# affichée reste « Gatineau », le nom d'origine devient le secteur.125_GATINEAU_KEYS = {126 "gatineau", "hull", "aylmer", "buckingham", "angers", "masson-angers",127 "templeton", "east templeton", "touraine", "pointe-gatineau",128 "old gatineau", "plateau", "mont-bleu", "limbour", "val-tetreau",129 "east buckingham",130}131# libellés de secteur sans valeur informative (numéros, doublon de la ville)132_SECTOR_NOISE = re.compile(r"^(?:\d+|gatineau|quebec|québec)$", re.I)133134135136def _norm(s: str) -> str:137 return re.sub(r"\s+", " ", (s or "").strip()).lower()138139140class HalfredConnector(BaseConnector):141 source_id = "halfred"142 request_delay = 10.0 # robots.txt : Crawl-delay: 10143 max_details = 12 # fiches détail visitées par sync (hors cache)144 max_images = 12145146 def __init__(self) -> None:147 super().__init__()148 # site bilingue : forcer le français (libellés et dates)149 self.session.headers["Accept-Language"] = "fr-CA,fr;q=0.9"150 self._detail_calls = 0 # appels réels (le cache BD ne compte pas)151152 # -- helpers ---------------------------------------------------------------153 @staticmethod154 def _external_id(href: str) -> str:155 """/fr/listings/17-rue-de-liverpool/details -> '17-rue-de-liverpool' ;156 /fr/listings/project/<uuid>/details -> 'project-<uuid>'. Le préfixe157 de locale (/fr, /en) est retiré pour garder les ids historiques."""158 path = re.sub(r"^/(?:fr|en)(?=/)", "", href)159 m = re.match(r"^/listings/project/([0-9a-f-]{8,})/details$", path)160 if m:161 return f"project-{m.group(1)}"162 m = re.match(r"^/listings/([^/]+)/details$", path)163 return m.group(1) if m else ""164165 @staticmethod166 def _city_sector(raw: str) -> tuple[str, str]:167 """« Pointe-Gatineau · Gatineau » -> ('Gatineau', 'Pointe-Gatineau') ;168 « Buckingham · Buckingham » -> ('Gatineau', 'Buckingham') ;169 « Chelsea » -> ('Chelsea', '')."""170 txt = re.sub(r"\s+", " ", (raw or "").strip())171 if "·" in txt:172 sector, _, city = (x.strip() for x in txt.rpartition("·"))173 else:174 # ancien format « Ville (Secteur) »175 m = re.match(r"^(.*?)\s*\(([^)]*)\)\s*$", txt)176 city = (m.group(1) if m else txt).strip()177 sector = (m.group(2) if m else "").strip()178 if _norm(city) in _GATINEAU_KEYS:179 if _norm(city) != "gatineau" and \180 (not sector or _norm(sector) == _norm(city)):181 sector = city182 if not sector or _SECTOR_NOISE.match(sector):183 sector = ""184 return "Gatineau", sector185 if not sector or _norm(sector) == _norm(city):186 sector = ""187 return city, sector188189 @staticmethod190 def _features(card) -> dict:191 """Attributs structurés de la carte : SpecItem textuels (chambres,192 salles de bain, superficie), pill « Disponible… » et bloc prix."""193 out: dict[str, str] = {}194 for feat in card.select("[data-sentry-component='SpecItem']"):195 txt = re.sub(r"\s+", " ", feat.get_text(" ", strip=True)).strip()196 low = _norm(txt)197 if "chambre" in low or "studio" in low or "bedroom" in low:198 out.setdefault("beds", txt)199 elif "bain" in low or "bath" in low:200 out.setdefault("baths", txt)201 elif "pi²" in low or "pi2" in low or "sq" in low:202 out.setdefault("sqft", txt)203 for sp in card.find_all("span"):204 txt = re.sub(r"\s+", " ", sp.get_text(" ", strip=True)).strip()205 if re.match(r"(?i)^(disponible|available)\b", txt):206 out.setdefault("availability", txt)207 break208 line = card.select_one("[data-sentry-component='line']")209 if line and "$" in line.get_text():210 # bloc prix : retirer l'ancien prix barré (promotion)211 clone = BeautifulSoup(str(line), "html.parser")212 for old in clone.select(".line-through"):213 out.setdefault("price_regular",214 re.sub(r"\s+", " ",215 old.get_text(" ", strip=True)))216 old.decompose()217 price = re.sub(218 r"\s+", " ", clone.get_text(" ", strip=True)).strip()219 out["price"] = re.sub(r"\s*/\s*(mois|month)\s*$", "",220 price).strip()221 return out222223 @staticmethod224 def _unit_type(beds: str) -> str:225 """« 2 chambres » -> 4½ ; « studio - 1 chambres » -> Studio ; on retient226 la BORNE BASSE de la fourchette, cohérente avec le prix « à partir227 de » affiché sur la même carte."""228 low = re.split(r"\s*[-–]\s*", beds or "")[0].strip()229 if re.match(r"(?i)^studio", low):230 return "Studio"231 m = re.match(r"^(\d+)", low)232 if m:233 return normalize_unit_type(f"{m.group(1)} chambres")234 return normalize_unit_type(low)235236 @staticmethod237 def _area(sqft_txt: str) -> float | None:238 """« 1200 - 1260 pieds carrés » -> 1200 : borne BASSE de la fourchette239 (le prix de la carte est lui aussi « à partir de »)."""240 m = re.match(r"^\s*([\d\s,]{2,7})\s*[-–]", sqft_txt or "")241 if m:242 try:243 v = float(m.group(1).replace(" ", "").replace(",", ""))244 except ValueError:245 v = 0.0246 if 80 <= v <= 20000:247 return v248 return parse_area_sqft(sqft_txt)249250 def _html(self, url: str) -> str:251 """HTML d'une page : le serveur ne déclare pas de charset (« text/html »252 sans paramètre) — forcer UTF-8, sinon les accents sont mojibake."""253 resp = self.get(url)254 resp.encoding = "utf-8"255 return resp.text256257 def _abs(self, url: str) -> str:258 if not url:259 return ""260 if url.startswith("http"):261 return url262 return BASE + url if url.startswith("/") else f"{BASE}/{url}"263264 # -- fiche détail ----------------------------------------------------------265 def _fetch_detail(self, href: str) -> dict:266 """Description rédigée, galerie, scores de mobilité, contact."""267 payload: dict = {"description": "", "images": [], "contact": {},268 "scores": {}}269 html = self._html(self._abs(href))270 soup = BeautifulSoup(html, "html.parser")271272 rich = soup.select_one("[data-sentry-component='RichTextDisplay']")273 if rich:274 txt = re.sub(r"\n+", " ", rich.get_text("\n", strip=True))275 payload["description"] = re.sub(r"\s{2,}", " ", txt).strip()[:1500]276277 for img in soup.select("img[src*='/storage/v1/']"):278 src = self._abs(img.get("src", ""))279 if "/logo" in src or src in payload["images"]:280 continue281 payload["images"].append(src)282283 text = soup.get_text(" ", strip=True)284 m = re.search(r"([\w.+-]+@halfred\.ca)", text)285 if m:286 payload["contact"]["email"] = m.group(1)287 m = re.search(r"\((\d{3})\)\s*(\d{3})-(\d{4})", text)288 if m:289 payload["contact"]["phone"] = \290 f"{m.group(1)}-{m.group(2)}-{m.group(3)}"291 for label, key in ((r"(?:Walk Score|Score de mobilité)", "walk"),292 (r"(?:Bike Score|Score de vélo)", "bike")):293 m = re.search(rf"{label}\W*(\d{{1,3}})", text)294 if m:295 payload["scores"][key] = int(m.group(1))296 return payload297298 # -- fetch -----------------------------------------------------------------299 def fetch(self) -> list[Listing]:300 soup = BeautifulSoup(self._html(LIST_URL), "html.parser")301 cards = soup.select(302 "a[data-sentry-component='EditorialListingCard']") or \303 soup.select("a[href$='/details']")304305 listings: list[Listing] = []306 seen: set[str] = set()307 details_used = 0308 for card in cards:309 try:310 href = card.get("href", "")311 ext = self._external_id(href)312 if not ext or ext in seen:313 continue314 seen.add(ext)315316 h = card.select_one("h3, h1")317 title = h.get_text(" ", strip=True) if h else ""318 # le lieu « Secteur · Ville » est le <p> qui suit le titre319 loc_p = h.find_next_sibling("p") if h else None320 location = loc_p.get_text(" ", strip=True) if loc_p else ""321 feats = self._features(card)322 city, sector = self._city_sector(location)323 # l'adresse civique n'est publiée que pour les immeubles dont324 # le titre EST l'adresse (les projets portent un nom)325 address = (f"{title}, {city}"326 if re.match(r"^\d", title) and city else "")327328 price_label = feats.get("price", "")329 availability = feats.get("availability", "")330 sqft_txt = feats.get("sqft", "")331 badges = [b.get_text(" ", strip=True)332 for b in card.select("span")333 if b.get_text(strip=True) in334 ("PROMO", "Offre", "Dernières unités", "Nouveau")]335336 image = ""337 img = card.select_one("img[src*='/storage/v1/']")338 if img:339 image = self._abs(img.get("src", ""))340341 # fiche détail (cache BD ; clé = contenu de la carte)342 payload: dict = {}343 key = hashlib.sha1(344 re.sub(r"\s+", " ", card.get_text(" ", strip=True))345 .encode("utf-8")).hexdigest()[:20]346 if details_used < self.max_details:347 try:348 before = self._detail_calls349 payload = self.detail(ext, key,350 lambda h=href: self._detail_wrap(h))351 details_used += self._detail_calls - before352 except Exception:353 payload = {}354355 images = [image] if image else []356 for im in (payload.get("images") or []):357 if im not in images:358 images.append(im)359360 desc_bits = [x for x in [361 feats.get("beds", ""), feats.get("baths", ""),362 sqft_txt, " · ".join(badges),363 (f"Prix régulier {feats['price_regular']}"364 if feats.get("price_regular") else "")] if x]365 description = payload.get("description", "")366 if description:367 desc_bits.insert(0, description)368369 details: dict = {}370 if payload.get("contact"):371 details["contact"] = payload["contact"]372 for k, v in (payload.get("scores") or {}).items():373 details[f"{k}_score"] = v374375 listings.append(Listing(376 source=self.source_id,377 external_id=ext,378 url=self._abs(href),379 title=title,380 address=address,381 sector=sector,382 city=city,383 unit_type=self._unit_type(feats.get("beds", "")),384 price=parse_price(price_label),385 price_label=price_label,386 availability=availability,387 area_sqft=self._area(sqft_txt),388 description=" — ".join(desc_bits)[:1500],389 details=details,390 images=images[: self.max_images],391 ))392 except Exception:393 continue394 return listings395396 def _detail_wrap(self, href: str) -> dict:397 self._detail_calls += 1398 return self._fetch_detail(href)399