Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/huma.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-1814#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/huma.py : connecteur HUMĀ Condos locatifs (humalevis.com)91# Deux phases de 130/132 unités à Lévis (Saint-Romuald). Plans d'étages92# interactifs (<area data-color-scheme="disponible">) -> fiches d'unités93# (type, superficies, date de disponibilité, plan). Les pages de phases94# listent les services/inclusions ET les photos de la phase (aires de vie,95# gym, chambres… — ajoutées à la galerie de chaque unité, la fiche unité96# n'ayant que le plan) ; la page contact donne l'adresse civique de chaque97# phase, le contact et le marqueur GPS. Aucun prix sur le site (confirmé).98# Les href des <area> sont devenus relatifs (« /unites/condo-n-113 »,99# redirigés vers /unite-phase-<n>/…) : gérés, et la phase est déduite de la100# page d'étage d'origine (external_id inchangé : phase-<n>-condo-<numéro>).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, infer_city, normalize_unit_type, parse_area_sqft109from .base import BaseConnector110111BASE = "https://humalevis.com"112SECTOR = "Saint-Romuald"113114# fichiers d'images à ignorer (logos, partenaires)115_SKIP_IMG = re.compile(r"logo|rvb[_-]?huma|ftq|edifia|favicon|icon", re.I)116117118class HumaConnector(BaseConnector):119 source_id = "huma"120 request_delay = 0.5121 max_floor_pages = 24 # garde-fou (2 phases x 10 étages)122123 # -- pages de phase : listes « Services et commodité » + inclusions ----------124 @staticmethod125 def _phase_amenities(html: str) -> list[str]:126 soup = BeautifulSoup(html, "html.parser")127 items: list[str] = []128129 def _lis_after(node) -> list[str]:130 ul = node.find_next("ul") if node else None131 if not ul:132 return []133 return [re.sub(r"\s+", " ", li.get_text(" ", strip=True))134 for li in ul.find_all("li")]135136 for h3 in soup.find_all("h3"):137 if "services et commodit" in h3.get_text(strip=True).lower():138 items.extend(_lis_after(h3))139 break140 for p in soup.find_all("p"):141 label = p.get_text(strip=True).upper()142 if label.startswith("INCLUSIONS MENSUELLES"):143 items.extend(f"Inclus : {t}" for t in _lis_after(p))144 elif label.startswith("OPTIONS OFFERTES"):145 items.extend(f"{t} — en option" for t in _lis_after(p))146 return [t for t in dict.fromkeys(items) if 3 <= len(t) <= 120][:25]147148 # -- page contact : adresse civique par phase, contact, GPS -----------------149 def _contact_info(self) -> tuple[dict[str, str], dict, tuple | None]:150 addresses: dict[str, str] = {}151 contact: dict = {}152 latlng: tuple | None = None153 try:154 html = self.get(f"{BASE}/contactez-nous/").text155 except Exception:156 return addresses, contact, latlng157 soup = BeautifulSoup(html, "html.parser")158 for h4 in soup.find_all("h4"):159 m = re.match(r"HUM[AĀ]\s+phase\s+(I{1,2}|1|2)\b",160 h4.get_text(strip=True), re.I)161 if not m:162 continue163 phase = {"I": "1", "II": "2"}.get(m.group(1).upper(), m.group(1))164 p = h4.find_next("p")165 if p:166 addr = re.sub(r"\s+", " ", p.get_text(", ", strip=True))167 # « 1220, rue de Courchevel » -> « 1220 rue de Courchevel »168 # (la virgule après le n° civique brise le géocodeur en lot)169 addresses[phase] = re.sub(r"^(\d+),\s*", r"\1 ", addr)170 tel = soup.select_one('a[href^="tel:"]')171 if tel:172 contact["phone"] = tel.get_text(strip=True)173 mail = soup.select_one('a[href^="mailto:"]')174 if mail:175 contact["email"] = mail.get_text(strip=True)176 # marqueur Google Maps « HUMĀ condos locatifs » (phase I)177 m = re.search(r'"nom":"HUM[^"]*condos[^"]*","adresse":"[^"]*",\s*'178 r'"latitude":"([\d.\-]+)","longitude":"([\d.\-]+)"', html)179 if m:180 latlng = (float(m.group(1)), float(m.group(2)))181 return addresses, contact, latlng182183 # -- photos de la phase (page /phase-<n>/) : ajoutées à chaque unité --------184 @staticmethod185 def _phase_photos(html: str) -> list[str]:186 photos: list[str] = []187 for u in re.findall(188 rf'(?:src|href|data-src)="({re.escape(BASE)}'189 rf'/wp-content/uploads/[^"]+\.(?:jpg|jpeg|png|webp))"',190 html, re.I):191 u = re.sub(r"-\d{2,4}x\d{2,4}(?=\.\w+$)", "", u)192 if not _SKIP_IMG.search(u) and u not in photos:193 photos.append(u)194 return photos[:10]195196 def fetch(self) -> list[Listing]:197 # 0) Adresses par phase + contact + GPS (page contact)198 addresses, contact, latlng = self._contact_info()199200 # 1) Découvrir les pages d'étages depuis les pages de phases201 floor_urls: list[tuple[str, str]] = [] # (phase, url)202 phase_amenities: dict[str, list[str]] = {}203 phase_photos: dict[str, list[str]] = {}204 phase_blurb: dict[str, str] = {}205 for phase in (1, 2):206 try:207 html = self.get(f"{BASE}/phase-{phase}/").text208 except Exception:209 continue210 phase_amenities[str(phase)] = self._phase_amenities(html)211 phase_photos[str(phase)] = self._phase_photos(html)212 # prose de présentation de la phase (1er paragraphe long)213 psoup = BeautifulSoup(html, "html.parser")214 for p in psoup.find_all("p"):215 t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))216 if 120 < len(t) < 600:217 phase_blurb[str(phase)] = t218 break219 found = sorted(set(re.findall(220 rf'href="({re.escape(BASE)}/phase-{phase}/etage-\d+/?)"',221 html)), key=lambda u: int(re.search(r"etage-(\d+)", u).group(1)))222 floor_urls.extend((str(phase), u) for u in found)223224 # 2) Unités disponibles sur chaque plan d'étage (href absolus OU225 # relatifs — le site est passé à « /unites/condo-n-113 »)226 unit_urls: list[tuple[str, str]] = [] # (phase, url)227 seen_units: set[str] = set()228 for floor_phase, url in floor_urls[:self.max_floor_pages]:229 try:230 html = self.get(url).text231 except Exception:232 continue233 for tag in re.findall(r"<area\b.*?>", html, re.S):234 if 'data-color-scheme="disponible"' not in tag:235 continue236 m = re.search(r'href="(https?://[^"]+|/[^"]+)"', tag)237 if not m:238 continue239 u = m.group(1).rstrip("/")240 if u.startswith("/"):241 u = BASE + u242 if u.startswith(BASE) and u not in seen_units:243 seen_units.add(u)244 unit_urls.append((floor_phase, u))245246 # 3) Fiche de chaque unité disponible247 listings: list[Listing] = []248 for floor_phase, url in unit_urls:249 try:250 resp = self.get(url)251 html = resp.text252 url = str(resp.url).rstrip("/") # après redirection éventuelle253 except Exception:254 continue255 try:256 soup = BeautifulSoup(html, "html.parser")257 text = soup.get_text("\n", strip=True)258259 num_m = re.search(r"N°\s*(\w+)", text)260 unit_no = (num_m.group(1) if num_m261 else url.rstrip("/").split("-")[-1])262 phase_m = re.search(r"unite-phase-(\d)", url)263 phase = phase_m.group(1) if phase_m else floor_phase264265 type_m = re.search(r"TYPE\s+([\w.]+)\s*\|\s*([^\n]+)", text)266 model = type_m.group(1) if type_m else ""267 unit_type = (normalize_unit_type(type_m.group(2))268 if type_m else "")269270 etat_m = re.search(r"ÉTAT\s*\n\s*([^\n]+)", text)271 availability = etat_m.group(1).strip() if etat_m else "Disponible"272 # date de disponibilité affichée sous le titre (div.date-title)273 date_el = soup.select_one(".date-unite .date-title")274 if date_el and date_el.get_text(strip=True):275 availability = date_el.get_text(strip=True).capitalize()276277 floor_m = re.search(r"ÉTAGE\s*\n\s*(\d+)", text)278 area_sqft = None279 desc_parts = []280 for label in ("SUPERFICIE DU LOGEMENT", "SUPERFICIE DU BALCON",281 "SUPERFICIE TOTALE"):282 dm = re.search(rf"{label}\s*\n\s*([^\n]+)", text)283 if dm:284 desc_parts.append(285 f"{label.capitalize().lower().capitalize()} : "286 f"{dm.group(1).strip()}")287 if label == "SUPERFICIE DU LOGEMENT":288 area_sqft = parse_area_sqft(dm.group(1))289 if model:290 desc_parts.insert(0, f"Modèle {model}")291 if floor_m:292 desc_parts.insert(0, f"Étage {floor_m.group(1)}")293294 imgs = re.findall(295 rf'(?:src|href|data-src)="({re.escape(BASE)}'296 rf'/wp-content/uploads/[^"]+\.(?:jpg|jpeg|png|webp))"',297 html, re.I)298 images = [u for u in dict.fromkeys(imgs)299 if not _SKIP_IMG.search(u)][:5]300 # photos de la phase (aires communes, gym, intérieurs types)301 images += [u for u in phase_photos.get(phase, [])302 if u not in images]303 images = images[:15]304305 details: dict = {}306 if contact:307 details["contact"] = dict(contact)308 lat, lng = (latlng if latlng and phase == "1"309 else (None, None))310 listings.append(Listing(311 source=self.source_id,312 external_id=f"phase-{phase}-condo-{unit_no}",313 url=url,314 title=f"HUMĀ phase {phase} — Condo locatif N°{unit_no}"315 f" ({unit_type})",316 address=addresses.get(phase, ""),317 sector=SECTOR,318 city=infer_city(SECTOR),319 unit_type=unit_type,320 price=None, # aucun prix affiché sur le site321 price_label="",322 availability=availability,323 area_sqft=area_sqft,324 description=(" | ".join(desc_parts)325 + ("\nHUMĀ condos locatifs, Saint-Romuald "326 "(Lévis) — "327 + phase_blurb[phase]328 if phase_blurb.get(phase) else "")),329 amenities=list(phase_amenities.get(phase, [])),330 details=details,331 images=images,332 lat=lat,333 lng=lng,334 ))335 except Exception:336 continue337338 return listings339