Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/hapopex.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/hapopex.py : HAPOPEX (hapopex.org) — OBNL d'habitation montréalais91# (parcs à Montréal-Nord, Lachine, Côte-des-Neiges…), page « Logements à92# louer » avec une carte par parc d'habitation.93# Techno : Wix rendu côté serveur. ⚠️ Les slugs des fiches sont trompeurs94# (copy-of-industriel-1-… = fiche ARCHEVÊQUE, etc.) : on apparie carte ->95# fiche PAR POSITION dans le document, jamais par le slug. La fiche fournit96# le quartier et les « Types d'unités » (pas de prix ni d'adresse civique).97# Granularité : PARC D'HABITATION (une annonce par parc).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import html as _html103import re104105import requests106107from .base import BaseConnector108from ..schema import Listing, strip_accents109110BASE = "https://www.hapopex.org"111LIST_URL = f"{BASE}/logements-a-louer"112113# ancre « En savoir plus » de chaque carte (ordre du document)114_CARD_RE = re.compile(115 r'<a[^>]+href="(https://www\.hapopex\.org/[^"]+)"[^>]*>'116 r'(?:(?!</a>).)*?En savoir plus')117# dans le texte qui précède l'ancre : « Nom | Quartier X | N logements »118_CARD_TXT_RE = re.compile(119 r'([^|]{2,60})\|\s*\|(?:Quartier)?\s*([^|]{2,40})\|\s*(\d+)\s*logements?\s*\|?\s*$')120_IMG_RE = re.compile(r'<img[^>]+src="(https://static\.wixstatic\.com/media/[^"]+)"')121_TYPES_RE = re.compile(r"Types d'unités\s*:?\s*\|?([^|]*(?:\|[^|]*){0,6})")122_TYPE_TOKEN_RE = re.compile(r'\d\s*½|\bstudio\b', re.I)123124125def _slug(name: str) -> str:126 s = strip_accents(name.lower())127 return re.sub(r"[^a-z0-9]+", "-", s).strip("-")128129130def _to_text(seg: str) -> str:131 txt = _html.unescape(re.sub(r"<[^>]+>", "|", seg))132 return re.sub(r"\|+", "|", txt)133134135class HapopexConnector(BaseConnector):136 """HAPOPEX — une annonce par parc d'habitation (Montréal)."""137138 source_id = "hapopex"139 request_delay = 0.8140141 def _fiche(self, url: str) -> dict:142 """Fiche du parc : types d'unités + photos (JSON-sérialisable)."""143 h = re.sub(r"\s+", " ", self.get(url).text)144 h = re.sub(r"<script.*?</script>", "", h)145 txt = _to_text(h)146 types: list[str] = []147 m = _TYPES_RE.search(txt)148 if m:149 for tok in _TYPE_TOKEN_RE.findall(m.group(1)):150 t = re.sub(r"[\s ]+", "", tok)151 t = "Studio" if t.lower() == "studio" else t152 if t not in types:153 types.append(t)154 images = []155 for u in _IMG_RE.findall(h):156 if u not in images:157 images.append(u)158 return {"types": types, "images": images[:15]}159160 def fetch(self) -> list[Listing]:161 page = re.sub(r"\s+", " ", self.get(LIST_URL).text)162 out: list[Listing] = []163 seen: set[str] = set()164 for m in _CARD_RE.finditer(page):165 fiche_url = m.group(1)166 pre = page[max(0, m.start() - 3500):m.start()]167 tm = _CARD_TXT_RE.search(_to_text(pre).rstrip())168 if not tm:169 continue170 name = tm.group(1).strip().strip("").strip()171 sector = tm.group(2).replace("Quartier", "").strip()172 count = tm.group(3)173 if not name:174 continue175 ext_id = _slug(name) # nom du parc (stable)176 if ext_id in seen:177 continue178 seen.add(ext_id)179180 imgs = _IMG_RE.findall(pre)[-1:] # vignette de la carte181182 key = hashlib.sha256(f"{name}|{sector}|{count}".encode()183 ).hexdigest()[:16]184 try:185 det = self.detail(ext_id, key,186 lambda u=fiche_url: self._fiche(u))187 except requests.RequestException:188 det = {}189 types = det.get("types") or []190 for u in det.get("images") or []:191 if u not in imgs:192 imgs.append(u)193194 desc = (f"Parc d'habitation {name} de HAPOPEX (OBNL) — "195 f"{count} logements, quartier {sector}, Montréal.")196 if types:197 desc += " Types d'unités : " + ", ".join(types) + "."198 desc += " Prix et disponibilités : communiquez avec l'organisme."199200 out.append(Listing(201 source=self.source_id,202 external_id=ext_id,203 url=fiche_url,204 title=f"HAPOPEX — {name} ({sector})",205 sector=sector,206 city="Montréal",207 unit_type=types[0] if len(types) == 1 else "",208 availability="Communiquez avec nous",209 description=desc,210 amenities=([f"Types d'unités : {', '.join(types)}"]211 if types else []),212 details={"unit_types": types, "unit_count": int(count)},213 images=imgs[:20],214 ))215 return out216