Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/headway.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/headway.py : connecteur La Corporation Headway (headwayltee.com)91# Site vitrine Wix (rendu serveur) sans liste d'unités individuelles :92# une annonce par complexe immobilier (Place Prévert à Vanier, Place93# Versant Nord / Place l'Heureux / Domaine Versant Nord à Ste-Foy,94# Complexe Renaissance à Charlesbourg, Thibault et Curé-Pelletier à Lévis).95# Le Domaine Anjou (Montréal) est exclu (hors Québec/Lévis).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import html as htmllib100import re101import unicodedata102103from ..schema import Listing, normalize_unit_type104from .base import BaseConnector105106BASE = "https://www.headwayltee.com"107108# (url de page, [(nom du complexe, secteur, ville), ...])109PAGES: list[tuple[str, list[tuple[str, str, str]]]] = [110 (f"{BASE}/logements-a-louer/appartement-quebec",111 [("Place Prévert", "Vanier", "Québec")]),112 (f"{BASE}/ste-foy",113 [("Place Versant Nord", "Sainte-Foy", "Québec"),114 ("Place l'Heureux", "Sainte-Foy", "Québec"),115 ("Domaine Versant Nord", "Sainte-Foy", "Québec")]),116 (f"{BASE}/logements-a-louer/appartement-charlesbourg",117 [("Complexe Renaissance", "Charlesbourg", "Québec")]),118 (f"{BASE}/logements-a-louer/levis",119 [("Thibault", "Lévis", "Lévis"),120 ("Curé-Pelletier", "Lévis", "Lévis")]),121]122123124def _slug(s: str) -> str:125 s = unicodedata.normalize("NFD", s.lower())126 s = "".join(c for c in s if unicodedata.category(c) != "Mn")127 return re.sub(r"[^a-z0-9]+", "-", s).strip("-")128129130def _wix_image(url: str) -> str:131 """URL wixstatic pleine résolution (sans les transformations /v1/fill/...)."""132 return url.split("/v1/")[0]133134135class HeadwayConnector(BaseConnector):136 source_id = "headway"137 request_delay = 0.6138139 def fetch(self) -> list[Listing]:140 listings: list[Listing] = []141 for url, complexes in PAGES:142 try:143 html = self.get(url).text144 except Exception:145 continue146 try:147 listings.extend(self._parse_page(url, html, complexes))148 except Exception:149 continue150 return listings151152 # -- une page (1 à 3 complexes) ----------------------------------------------153 def _parse_page(self, url: str, html: str,154 complexes: list[tuple[str, str, str]]) -> list[Listing]:155 # segments de texte visibles, avec leur position dans le HTML156 # (les segments contenant « { » sont du CSS/JS inliné par Wix : ignorés)157 segments = [(m.start(), htmllib.unescape(m.group(1)).replace("\xa0", " ").strip())158 for m in re.finditer(r">([^<>]{2,400})<", html)]159 segments = [(p, t) for p, t in segments160 if t and "{" not in t and "}" not in t161 and not t.startswith(("var ", "window.", "/*", "//"))]162163 # images : balises <img alt="Nom du complexe ..."> (wixstatic)164 img_tags = [(m.start(), m.group(0)) for m in re.finditer(r"<img [^>]+>", html)]165166 # occurrences exactes des noms de complexes (titres de sections)167 name_slugs = {_slug(n): n for n, _, _ in complexes}168 name_events: list[tuple[int, str]] = [] # (pos, nom)169 for p, t in segments:170 if _slug(t) in name_slugs:171 name_events.append((p, name_slugs[_slug(t)]))172173 # blocs "Adresse :" (libellé seul) -> associés au titre précédent le plus174 # proche ; les pages à complexe unique prennent le premier bloc trouvé.175 # nom -> (adresse, types, téléphone du bureau de location)176 info_blocks: dict[str, tuple[str, list[str], str]] = {}177 for i, (p, t) in enumerate(segments):178 if not re.match(r"^Adresse\s*:?\s*$", t):179 continue180 parts: list[str] = []181 unit_types: list[str] = []182 phone = ""183 after_phone_label = False184 for _, t2 in segments[i + 1:i + 40]:185 if re.search(r"Heures d'ouverture", t2, re.I):186 break187 if re.match(r"^Num[ée]ro de t[ée]l[ée]phone", t2, re.I):188 after_phone_label = True189 continue190 if after_phone_label and not phone:191 pm = re.search(r"\b(\d{3}-\d{3}-\d{4})\b", t2)192 if pm:193 phone = pm.group(1)194 continue195 if re.fullmatch(r"\d\s*(?:½|1/2)(?:\s*pi[èe]ces?)?|\d\s*pi[èe]ces", t2):196 nt = normalize_unit_type(t2) or t2197 if nt not in unit_types:198 unit_types.append(nt)199 elif len(parts) < 3 and not re.search(200 r"Composition|Logements disponibles|sous-sol|Étage", t2, re.I):201 parts.append(t2)202 address = ", ".join(parts).strip(" ,")203 if "saint-sacrement" in address.lower(): # siège social, pas un immeuble204 continue205 owner = None206 for np, n in name_events:207 if np < p:208 owner = n209 if owner is None and len(complexes) == 1:210 owner = complexes[0][0]211 if owner and owner not in info_blocks:212 info_blocks[owner] = (address, unit_types, phone)213214 # position de la section détaillée de chaque complexe (dernière215 # occurrence exacte du nom, sinon premier segment qui le contient)216 section_pos: dict[str, int | None] = {}217 for name, _, _ in complexes:218 name_flat = _slug(name)219 name_pos = None220 for p, n in name_events:221 if n == name:222 name_pos = p223 if name_pos is None:224 for p, t in segments:225 if name_flat in _slug(t):226 name_pos = p227 break228 section_pos[name] = name_pos229230 results = []231 for name, sector, city in complexes:232 name_flat = _slug(name)233 name_pos = section_pos[name]234 # fin de la section = début de la section détaillée suivante235 starts = sorted(p for p in section_pos.values()236 if p is not None and name_pos is not None237 and p > name_pos)238 section_end = starts[0] if starts else len(html)239240 # images dont l'attribut alt commence par le nom du complexe241 images: list[str] = []242 for _, tag in img_tags:243 alt_m = re.search(r'alt="([^"]*)"', tag)244 if not alt_m:245 continue246 alt = htmllib.unescape(alt_m.group(1))247 if not _slug(alt).startswith(name_flat):248 continue249 src_m = re.search(r'src="(https://static\.wixstatic\.com/media/[^"]+)"', tag)250 if src_m:251 u = _wix_image(src_m.group(1))252 if u not in images:253 images.append(u)254255 # description = premier long paragraphe de la section du complexe256 description = ""257 if name_pos is not None:258 for p, t in segments:259 if name_pos < p < section_end and len(t) > 120 \260 and not t.startswith("*") and "veuillez svp" not in t:261 description = t262 break263264 address, unit_types, phone = info_blocks.get(name, ("", [], ""))265266 # services disponibles (liste de la section du complexe)267 start = name_pos if name_pos is not None else 0268 amenities = self._collect_list(269 segments, start, section_end,270 r"^services disponibles",271 r"^(à moins de|pourquoi|n'h[ée]sitez|si vous|acc[èe]s facile"272 r"|gr[âa]ce [àa]|press to zoom|contactez|\d/\d)")273274 # commerces/services « à moins de 5 minutes à pied » -> description275 proximity = self._collect_list(276 segments, start, section_end,277 r"^([àa] moins de 5 minutes|acc[èe]s facile)",278 r"^(press to zoom|n'h[ée]sitez|gr[âa]ce [àa]|pourquoi"279 r"|contactez|la corporation|\d/\d)")280281 if unit_types:282 comp = "Composition de l'immeuble : " + ", ".join(unit_types) + "."283 description = (description + " " + comp).strip() if description else comp284 if proximity:285 prox = "À moins de 5 minutes à pied : " + ", ".join(proximity) + "."286 description = (description + " " + prox).strip() if description else prox287288 details: dict = {}289 if phone:290 details["contact"] = {"phone": phone}291292 results.append(Listing(293 source=self.source_id,294 external_id=_slug(name),295 url=url,296 title=name,297 address=address,298 sector=sector,299 city=city,300 unit_type=unit_types[0] if len(unit_types) == 1 else "",301 availability="Sur demande (contacter l'agent de location)",302 description=description[:800],303 amenities=amenities,304 details=details,305 images=images[:20],306 ))307 return results308309 # -- liste à puces après un libellé (bornée à la section du complexe) --------310 @staticmethod311 def _collect_list(segments: list[tuple[int, str]], start: int, end: int,312 head_re: str, break_re: str,313 max_len: int = 110) -> list[str]:314 head_rx = re.compile(head_re, re.I)315 break_rx = re.compile(break_re, re.I)316 items: list[str] = []317 for i, (p, t) in enumerate(segments):318 if not (start <= p < end) or not head_rx.match(t.lower()):319 continue320 for p2, t2 in segments[i + 1:i + 30]:321 if p2 >= end or break_rx.match(t2.lower()):322 break323 # phrases d'introduction / libellés : ignorés, pas des items324 if not (3 <= len(t2) <= max_len) or t2.endswith(":") \325 or re.search(r"appelez-nous|t[ée]l[ée]phoner", t2, re.I):326 continue327 if t2 not in items:328 items.append(t2)329 break330 return items331