Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/qresidential.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/qresidential.py : connecteur Q Residential (qresidential.ca)91# Gestionnaire ontarien (~7 000 unités — Toronto, St. Catharines, Hamilton,92# Oshawa/GTA, Brampton, Barrie). « Corporate site » Yardi RentCafe derrière93# un Cloudflare STRICT (curl direct = 403) : tout passe par Scrapfly ASP94# (self.get_scrapfly, asp=true, SANS render_js — le contenu est rendu95# serveur, vérifié sur la recherche et les fiches).96# Contrairement à killam.py (même famille RentCafe), il n'y a PAS de blob97# #available_prop : la page /searchlisting.aspx rend 25 cartes propriétés98# côté serveur (nom, adresse, ville, province, vignette, URL de fiche).99# La fiche propriété fournit un JSON-LD ApartmentComplex (description,100# adresse postale, GPS, commodités, téléphone) et un tableau « Floor Plans »101# (tbody.floorplan-details : nom, Bed/Bath, pi², loyer — souvent « Call for102# pricing » —, disponibilité). Une annonce PAR PLAN D'ÉTAGE quand au moins103# un plan affiche un prix ; sinon repli « une annonce par propriété » sans104# prix (rien d'inventé). Fiches visitées via le cache BD self.detail(),105# clé datée du jour : au plus UNE visite Scrapfly par propriété par jour,106# peu importe le nombre de synchronisations.107#108# Expansion Ontario — GATÉE par LOUKA_ONTARIO=1 : sans la variable, le109# connecteur est `disabled` et exclu du registre (zéro impact prod QC).110# -----------------------------------------------------------------------------111from __future__ import annotations112113import datetime as _dt114import json115import os116import re117118from bs4 import BeautifulSoup119120from ..schema import Listing, normalize_unit_type, parse_price121from .base import BaseConnector122123BASE = "https://www.qresidential.ca"124SEARCH_PAGE = f"{BASE}/searchlisting.aspx"125126# Gate expansion Ontario : le connecteur reste hors registre tant que la127# variable d'environnement LOUKA_ONTARIO=1 n'est pas posée.128_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"129130# cellules du tableau plans d'étage : « Bed/Bath Studio / 1 », « 2 / 1.5 »131_BEDBATH_RE = re.compile(132 r"Bed/Bath\s+(Studio|\d+)\s*/\s*([\d.]+)", re.I)133_SQFT_RE = re.compile(r"([\d,]+)\s*Sq\.?\s*Ft", re.I)134# identifiant stable du plan d'étage (carrousel photo du plan)135_FPID_RE = re.compile(r"fp-myCarousel(\d+)")136137138class QResidentialConnector(BaseConnector):139 source_id = "qresidential"140 request_delay = 1.5 # Cloudflare strict : Scrapfly ASP, rester poli141 disabled = not _ONTARIO # gate expansion Ontario (LOUKA_ONTARIO=1)142 max_properties = 35 # garde-fou (25 propriétés aujourd'hui)143 max_images = 15144145 def fetch(self) -> list[Listing]:146 page = self.get_scrapfly(SEARCH_PAGE, asp=True, render_js=False)147 if not page:148 raise RuntimeError("Q Residential : Scrapfly ASP n'a pas "149 "retourné la page de recherche")150 soup = BeautifulSoup(page, "html.parser")151152 cards = soup.select("div.searchResult")153 listings: list[Listing] = []154 count = 0155 seen: set[str] = set()156 for card in cards:157 try:158 a = card.select_one("a.propertyUrl")159 if a is None:160 continue161 url = (a.get("href") or "").strip()162 if not url or url in seen:163 continue164 seen.add(url)165 # résidentiel longue durée seulement (structure « Apartment »)166 st = card.select_one(".structure-type")167 if st and st.get_text(" ", strip=True) and \168 "apartment" not in st.get_text(" ", strip=True).lower():169 continue170 state = card.select_one(".propertyState")171 if state and state.get_text(strip=True).upper() != "ON":172 continue173 if count >= self.max_properties:174 break175 count += 1176 listings.extend(self._property_listings(card, url))177 except Exception:178 continue179 return listings180181 # -- annonces d'une propriété (une par plan d'étage tarifé, repli) ----------182 def _property_listings(self, card, url: str) -> list[Listing]:183 # identifiant : slug de la fiche (« queenston-manor »)184 slug = url.rstrip("/").split("/")[-2] if url.endswith("default.aspx") \185 else re.sub(r"[^a-z0-9-]", "", url.rstrip("/").split("/")[-1])186 a = card.select_one("a.propertyUrl")187 name = a.get_text(" ", strip=True)188 city = (card.select_one(".propertyCity") or a) \189 .get_text(" ", strip=True) if card.select_one(".propertyCity") \190 else ""191 # adresse complète de la carte (« 382 Queenston Street St. Catharines192 # ON L2P 3V5 ») — on la reconstruit avec des virgules193 street = ""194 spans = card.select(".propertyAddress")195 if spans:196 street = spans[-1].get_text(" ", strip=True)197 postal = ""198 m = re.search(r"[A-Z]\d[A-Z]\s?\d[A-Z]\d",199 card.get_text(" ", strip=True))200 if m:201 postal = m.group(0)202 address = ", ".join(x for x in (street, city) if x)203 if address:204 address += f", ON {postal}".rstrip()205206 thumb = ""207 img = card.select_one("img.propertyThumb")208 if img is not None:209 thumb = (img.get("src") or "").strip()210211 # fiche propriété via le cache BD — clé datée : au plus une visite212 # Scrapfly par propriété par jour (les prix « Call for pricing »213 # changent rarement, et jamais entre deux syncs du même jour)214 feed_key = f"{_dt.date.today().isoformat()}|{name}|{thumb}"215 d = self.detail(slug, feed_key, lambda: self._fetch_detail(url))216217 desc = d.get("description") or ""218 amenities = d.get("amenities") or []219 images = [u for u in ([thumb] + (d.get("images") or [])) if u]220 lat, lng = d.get("lat"), d.get("lng")221 details: dict = {}222 if d.get("phone"):223 details["contact"] = {"phone": d["phone"]}224225 common = dict(226 source=self.source_id, url=url, address=address, city=city,227 province="ON", description=desc, amenities=amenities[:25],228 images=images[: self.max_images], lat=lat, lng=lng,229 )230231 # une annonce par plan d'étage TARIFÉ (prix affiché) ; les plans232 # « Call for pricing » ne deviennent pas des annonces individuelles233 out: list[Listing] = []234 priced = [fp for fp in d.get("floorplans") or []235 if fp.get("price") is not None]236 for fp in priced:237 beds = fp.get("beds")238 price = fp["price"]239 out.append(Listing(240 external_id=f"{slug}-{fp['fpid']}",241 title=f"{name} — {fp['name']}" if fp.get("name") else name,242 unit_type=("Studio" if beds == 0 else normalize_unit_type(243 f"{int(beds)} chambres") if beds is not None else ""),244 bedrooms=beds,245 bathrooms=fp.get("baths"),246 price=price,247 price_label=f"À partir de {price:.0f} $ /mois",248 availability=fp.get("avail") or "",249 area_sqft=fp.get("sqft"),250 details=dict(details),251 **common,252 ))253 if out:254 return out255256 # repli : une annonce par propriété — gamme de types connue seulement257 # via les plans d'étage non tarifés ; aucun prix inventé258 fps = d.get("floorplans") or []259 beds_set = {fp.get("beds") for fp in fps if fp.get("beds") is not None}260 unit_type = ""261 if len(beds_set) == 1:262 b = beds_set.pop()263 unit_type = "Studio" if b == 0 else normalize_unit_type(264 f"{int(b)} chambres")265 return [Listing(266 external_id=slug,267 title=name,268 unit_type=unit_type,269 availability="Sur demande (contacter la gestion)" if fps else "",270 details=details,271 **common,272 )]273274 # -- fiche propriété : JSON-LD + tableau plans d'étage ----------------------275 def _fetch_detail(self, url: str) -> dict:276 out: dict = {"description": "", "amenities": [], "images": [],277 "floorplans": [], "lat": None, "lng": None, "phone": ""}278 page = self.get_scrapfly(url, asp=True, render_js=False)279 if not page:280 return out281 soup = BeautifulSoup(page, "html.parser")282283 # JSON-LD ApartmentComplex : description, GPS, commodités, téléphone284 for tag in soup.find_all("script", type="application/ld+json"):285 try:286 ld = json.loads(tag.string or "")287 except (TypeError, ValueError):288 continue289 if not isinstance(ld, dict) or \290 ld.get("@type") != "ApartmentComplex":291 continue292 out["description"] = BeautifulSoup(293 ld.get("description") or "", "html.parser"294 ).get_text(" ", strip=True)[:600]295 geo = ld.get("geo") or {}296 try:297 out["lat"] = float(geo.get("latitude"))298 out["lng"] = float(geo.get("longitude"))299 except (TypeError, ValueError):300 pass301 out["phone"] = ((ld.get("address") or {})302 .get("telephone") or "").strip()303 ams = []304 for af in ld.get("amenityFeature") or []:305 t = (af.get("name") or "").strip() if isinstance(af, dict) \306 else ""307 if t and t not in ams:308 ams.append(t)309 out["amenities"] = ams[:25]310 break311312 # visuels de la fiche (bannière dmslivecafe) — HORS plans d'étage/logos313 images: list[str] = []314 for img in soup.find_all("img"):315 src = (img.get("src") or "").strip()316 if "cdngeneralcf.rentcafe.com/dmslivecafe" not in src:317 continue318 if re.search(r"logo|icon|floor\s?plan|FloorPlan", src, re.I):319 continue320 if img.find_parent(class_=re.compile("floorplan")):321 continue322 if src not in images:323 images.append(src)324 out["images"] = images[: self.max_images]325326 # tableau plans d'étage : une ligne par variation (nom, Bed/Bath,327 # pi² éventuel, loyer, disponibilité)328 seen: set[str] = set()329 for tr in soup.select("tbody.floorplan-details tr"):330 txt = tr.get_text(" ", strip=True)331 if "Bed/Bath" not in txt:332 continue333 mid = _FPID_RE.search(str(tr))334 name_td = tr.find(string=re.compile(r"Floor Plan\s"))335 name = ""336 if name_td:337 name = re.sub(r"^Floor Plan\s+", "",338 str(name_td).strip()).strip()339 fpid = mid.group(1) if mid else \340 re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")341 if not fpid or fpid in seen:342 continue343 seen.add(fpid)344 mbb = _BEDBATH_RE.search(txt)345 beds = baths = None346 if mbb:347 beds = 0.0 if mbb.group(1).lower() == "studio" \348 else float(mbb.group(1))349 try:350 baths = float(mbb.group(2))351 except ValueError:352 baths = None353 msq = _SQFT_RE.search(txt)354 sqft = float(msq.group(1).replace(",", "")) if msq else None355 # loyer : montant affiché seulement (« Call for pricing » -> None)356 price = None357 mrent = re.search(r"Rent\s+([^D]*?)(?:Deposit|$)", txt)358 if mrent:359 price = parse_price(mrent.group(1))360 avail = ""361 mav = re.search(r"Deposit\s*(.*?)(?:Read More|$)", txt)362 if mav:363 avail = mav.group(1).strip()364 if avail.lower() in ("contact us", ""):365 avail = ""366 out["floorplans"].append({367 "fpid": fpid,368 "name": name,369 "beds": beds,370 "baths": baths,371 "sqft": sqft if sqft and 80 <= sqft <= 20000 else None,372 "price": price,373 "avail": avail,374 })375 return out376