Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/medway.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# 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/medway.py : connecteur Groupe Medway (condosmedway.ca)91# Condos locatifs neufs multi-villes : Rivière-du-Loup, Lévis (Saint-Nicolas,92# Lauzon, Rucher), Québec (boul. Laurier, Charest, Wilfrid-Hamel), Pont-Rouge,93# La Malbaie, Saint-Raphaël. WordPress (thème custom « turbutheme »), tout94# rendu serveur. Répertoire /condos-a-louer/ : cartes projet (nom, adresse95# civique avec ville, nombre d'unités). Chaque page projet /projet/<slug>/96# embarque les unités sous DEUX gabarits selon le projet :97# 1. span JSON `condosParEtageJson` (Rive, Edmond, Nico, Anastasie…) —98# unités par étage : id, prix, type « 3 ½ / 4 ½ bureau », superficie,99# disponibilité oui/non + « Prochainement » avec date, fiche /condo/… ;100# 2. tableau JS inline `units = [[…]]` (sélecteur d'étages : Kali, Wil,101# Alto) — number, state (Available/Reserved/Sold), price, typology102# (« 4etdemiB », « StudioA »), superficies, date, plan.103# On ne retient que les unités disponibles (maintenant ou prochainement ;104# Reserved/Sold exclues) — le prix de chaque unité vient de ces données (les105# fiches /condo/ n'affichent pas le prix). robots.txt WP standard.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import html as htmllib110import json111import re112113from bs4 import BeautifulSoup114115from ..schema import Listing, normalize_unit_type116from .base import BaseConnector117118BASE = "https://condosmedway.ca"119LIST_URL = f"{BASE}/condos-a-louer/"120121# « 35 rue Saint-Louis, Rivière-du-Loup, QC • 154 unités » -> adresse + ville122_UNITS_SUFFIX = re.compile(r"[••]\s*\d+\s*unités?", re.I)123_JSON_RE = re.compile(124 r'id="condosParEtageJson"[^>]*>\s*(\{.*?\})\s*</span>', re.S)125# gabarit « sélecteur d'étages » : tableau JS inline (une liste par étage)126_UNITS_RE = re.compile(r"units\s*=\s*(\[\[.*?\]\])\s*;?\n", re.S)127_TYPOLOGY_RE = re.compile(r"(\d)\s*etdemi", re.I)128129# médias de la page projet : les photos (galerie, aires communes) sont130# chargées en différé (lazysizes) -> data-src / data-srcset via le CDN131# assetcdn.net, en plus des src classiques132_PAGE_IMG_RE = re.compile(133 r'(?:data-src|data-srcset|src)="([^"\s]*?/wp-content/uploads/'134 r'[^"\s?]*?\.(?:jpe?g|webp|png))', re.I)135# images techniques à écarter de la galerie (plans, sélecteur d'étage, UI)136_IMG_SKIP_RE = re.compile(r"(?:etage|plan|selecteur|logo|icon|favicon|"137 r"hamburger|menu|arrow|fleche)", re.I)138_SIZE_SUFFIX_RE = re.compile(r"-\d+x\d+$")139# paragraphes de la page projet hors description (mise en garde légale,140# prise de rendez-vous, formulaires)141_PARA_SKIP_RE = re.compile(r"(?:titre indicatif|représentations artistiques|"142 r"plage horaire|rendez-vous|formulaire|"143 r"sujets? à modification)", re.I)144145146class MedwayConnector(BaseConnector):147 source_id = "medway"148 request_delay = 0.6149150 def fetch(self) -> list[Listing]:151 html = self.get(LIST_URL).text152 soup = BeautifulSoup(html, "html.parser")153154 listings: dict[str, Listing] = {}155 seen_projects: set[str] = set()156 for card in soup.select("div.condo-item"):157 try:158 self._parse_project(card, seen_projects, listings)159 except Exception:160 continue161 return list(listings.values())162163 # -- carte projet (répertoire /condos-a-louer/) ---------------------------------164 def _parse_project(self, card, seen: set[str],165 listings: dict[str, Listing]) -> None:166 link = card.select_one('a[href*="/projet/"]')167 name_el = card.select_one("h2")168 if not link or not name_el:169 return170 m = re.search(r"/projet/([^/?#]+)", link["href"])171 if not m or m.group(1) in seen:172 return173 slug = m.group(1)174 seen.add(slug)175 project = name_el.get_text(strip=True)176177 # adresse de la carte : « 35 rue Saint-Louis, Rivière-du-Loup, QC • 154 unités »178 addr_el = name_el.find_next(179 "div", class_=lambda c: c and "flex-col" in c)180 raw = addr_el.get_text(" ", strip=True) if addr_el else ""181 raw = _UNITS_SUFFIX.sub("", htmllib.unescape(raw)).strip(" ••")182 address = re.sub(r"\s+", " ", raw).strip().rstrip(",")183 # ville = dernier segment non vide une fois la province « QC » retirée184 # (« …, Québec, QC » -> Québec ; « …, La Malbaie QC » -> La Malbaie)185 city = ""186 parts = [p.strip() for p in address.split(",") if p.strip()]187 for p in reversed(parts[1:]):188 cand = re.sub(r"\bQC\s*$", "", p).strip().rstrip(",")189 if cand and not re.match(r"^G\d[A-Z]", cand):190 city = cand191 break192193 # page projet : JSON des unités par étage (?t=r = volet résidentiel)194 page = self.get(f"{BASE}/projet/{slug}/?t=r").text195 page_url = f"{BASE}/projet/{slug}/?t=r"196 # galerie + description du PROJET (la page est déjà téléchargée :197 # aucun trafic de plus) — communes à toutes les unités du projet198 gallery, description = self._project_media(page)199 mj = _JSON_RE.search(page)200 if mj:201 data = json.loads(mj.group(1))202 for floor in data.values():203 for unit_slug, u in (floor.get("condos") or {}).items():204 if not isinstance(u, dict) or unit_slug in listings:205 continue206 dispo = (u.get("disponibilite") or "").lower() == "oui"207 prochaine = (u.get("disponibilite_prochaine") or "").lower() == "oui"208 if not (dispo or prochaine):209 continue210 self._add_unit(listings, unit_slug, u, project, address,211 city, gallery, description)212 return213214 # gabarit « sélecteur d'étages » (Kali, Wil, Alto) : units = [[…]]215 mu = _UNITS_RE.search(page)216 if not mu:217 return # page marketing sans sélecteur (ex. 3000 Laurier) : rien218 for floor in json.loads(mu.group(1)):219 for u in floor:220 if not isinstance(u, dict) or u.get("state") != "Available":221 continue # Reserved / Sold : non disponibles222 self._add_selector_unit(listings, u, slug, page_url,223 project, address, city,224 gallery, description)225226 # -- médias de la page projet ------------------------------------------------227 @staticmethod228 def _project_media(page: str) -> tuple[list[str], str]:229 """(galerie, description) de la page projet.230231 Galerie : photos réelles du projet dans l'ordre du document (lazysizes :232 data-src/data-srcset), plans d'étage et images d'interface exclus,233 dédoublonnées par nom de fichier (variantes redimensionnées/-WxH et234 doublons .jpg/.png comptent pour une seule photo). Description :235 paragraphes de présentation du projet, texte propre.236 """237 gallery: list[str] = []238 seen: set[str] = set()239 for url in _PAGE_IMG_RE.findall(page):240 fn = url.rsplit("/", 1)[-1]241 stem = _SIZE_SUFFIX_RE.sub("", fn.rsplit(".", 1)[0])242 if _IMG_SKIP_RE.search(fn) or stem in seen:243 continue244 seen.add(stem)245 gallery.append(htmllib.unescape(url))246247 soup = BeautifulSoup(page, "html.parser")248 paras: list[str] = []249 for p in soup.find_all("p"):250 t = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()251 if len(t) < 100 or _PARA_SKIP_RE.search(t) or t in paras:252 continue253 paras.append(t)254 description = "\n\n".join(paras)[:3500]255 return gallery[:24], description256257 # -- unité (entrée du JSON condosParEtageJson) -----------------------------------258 def _add_unit(self, listings: dict[str, Listing], unit_slug: str, u: dict,259 project: str, address: str, city: str,260 gallery: list[str] | None = None,261 description: str = "") -> None:262 title = (u.get("nom-unite") or "").strip() or unit_slug263 url = (u.get("single_projet_url") or "").replace("\\/", "/") \264 or f"{BASE}/condo/{unit_slug}/"265266 # disponibilité brute : « Maintenant » / « Prochainement » (+ date libre)267 availability = (u.get("disponibilite_libelle") or "").strip()268 date_txt = (u.get("disponibilite_date") or "").strip()269 if date_txt:270 availability = f"{availability} — {date_txt}".strip(" —")271272 price = None273 raw_price = str(u.get("prix") or "").strip()274 if re.fullmatch(r"\d+(?:[.,]\d+)?", raw_price):275 price = float(raw_price.replace(",", "."))276277 area = None278 raw_area = str(u.get("superficie_pieds") or "").strip()279 if re.fullmatch(r"\d+(?:[.,]\d+)?", raw_area):280 area = float(raw_area.replace(",", "."))281282 # galerie du projet d'abord (photos réelles), plan de l'unité en fin283 images: list[str] = list(gallery or [])284 plan = (u.get("plan_url") or "").replace("\\/", "/")285 if plan.startswith("http") and plan not in images:286 images.append(plan)287288 amenities: list[str] = []289 finition = (u.get("finition") or "").strip()290 if finition and not finition.lower().startswith("non-attribu"):291 amenities.append(f"Finition : {finition}")292293 details: dict = {}294 tour = (u.get("visite_virtuelle_url") or "").replace("\\/", "/").strip()295 if tour.startswith("http"):296 details["virtual_tour"] = tour297298 listings[unit_slug] = Listing(299 source=self.source_id,300 external_id=unit_slug,301 url=url,302 title=title,303 address=address,304 sector=project,305 city=city,306 unit_type=normalize_unit_type((u.get("type") or "").strip()),307 price=price,308 price_label=f"{raw_price} $" if price is not None else "",309 availability=availability,310 area_sqft=area,311 description=description,312 amenities=amenities,313 details=details,314 images=images,315 )316317 # -- unité (gabarit sélecteur d'étages : Kali, Wil, Alto) ---------------------------318 def _add_selector_unit(self, listings: dict[str, Listing], u: dict,319 project_slug: str, page_url: str, project: str,320 address: str, city: str,321 gallery: list[str] | None = None,322 description: str = "") -> None:323 uid = str(u.get("id") or "").strip()324 number = (u.get("number") or "").strip() # « Unité 410 »325 if not uid:326 return327 ext_id = f"{project_slug}-{uid}" # id BD WordPress : stable328 if ext_id in listings:329 return330331 # type structuré : typology « 4etdemiB » / « StudioA » -> 4½ / Studio332 typology = (u.get("typology") or "").strip()333 unit_type = ""334 m = _TYPOLOGY_RE.search(typology)335 if m:336 unit_type = normalize_unit_type(f"{m.group(1)} ½")337 elif typology.lower().startswith("studio"):338 unit_type = "Studio"339340 # disponibilité affichée : légende « Disponible » (+ date si annoncée)341 availability = "Disponible"342 date_txt = (u.get("available_date") or "").strip()343 if date_txt:344 availability += f" — {date_txt}"345346 price = None347 raw = u.get("price")348 if isinstance(raw, (int, float)) and raw > 0:349 price = float(raw)350351 area = None352 ia = u.get("indoor_area")353 if isinstance(ia, (int, float)) and ia > 0:354 area = float(ia)355356 amenities: list[str] = []357 ba = u.get("balcony_area")358 if isinstance(ba, (int, float)) and ba > 0:359 amenities.append(f"Balcon {ba:g} pi²")360361 # galerie du projet d'abord (photos réelles), plan de l'unité en fin362 images: list[str] = list(gallery or [])363 plan = (u.get("plan_img_src") or "").replace("\\/", "/")364 if plan.startswith("http") and plan not in images:365 images.append(plan)366367 # certaines unités de ce gabarit ont leur propre fiche + visites 360368 unit_url = (u.get("url") or "").replace("\\/", "/").strip()369 details: dict = {}370 for k in ("virtual_tour", "virtual_tour2"):371 tour = (u.get(k) or "").replace("\\/", "/").strip()372 if tour.startswith("http"):373 details.setdefault("virtual_tour", tour)374 break375376 # description de l'unité si fournie, sinon celle du projet377 desc = re.sub(r"<[^>]+>", " ", u.get("description") or "").strip()378 desc = htmllib.unescape(re.sub(r"\s+", " ", desc))379 if description:380 desc = f"{desc}\n\n{description}".strip() if desc else description381382 listings[ext_id] = Listing(383 source=self.source_id,384 external_id=ext_id,385 url=unit_url if unit_url.startswith("http") else page_url,386 title=f"{project} — {number}".strip(" —") or ext_id,387 address=address,388 sector=project,389 city=city,390 unit_type=unit_type,391 price=price,392 price_label=f"{price:g} $" if price is not None else "",393 availability=availability,394 area_sqft=area,395 description=desc,396 amenities=amenities,397 details=details,398 images=images,399 )400