Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/urban_services.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/urban_services.py : connecteur Urban Services (urbanservices.ca)91# Gestionnaire de Gatineau (Urban Tenant Solutions) ; portail de location92# dédié rent.urbanservices.ca sur la plateforme Building Stack — même93# famille que le portail edifialocation.com du connecteur edifia.py :94# - /Listing/Listings embarque `var units = [...]` (une entrée par95# appartement annoncé : prix, pi², chambres, sdb, adresse complète,96# GPS, contact de l'immeuble, photo) ;97# - les pages immeuble /b/<id> listent TOUTES les unités disponibles98# (onglets : numéro, prix, pi², chambres, sdb, date de disponibilité,99# attribut data-unitid) + les commodités de l'immeuble — le JSON de la100# liste est parfois tronqué (immeubles à fort inventaire), la page101# /b/<id> fait donc foi pour l'inventaire et les dates ; le JSON102# enrichit (GPS, contact…) ;103# - le fragment /Listing/ApartmentView?id=<unitid> (cache BD) fournit la104# GALERIE COMPLÈTE de l'unité (wfiles.buildingstack.com), l'étage, les105# équipements (plancher, chauffage, wi-fi…) et le bloc « Commentaires »106# (description libre) — absents de la liste et du HTML des pages.107# Une annonce Lou-Ka = une unité disponible. Le parc ontarien (Ottawa)108# est exclu (province != QC). ~17 requêtes par sync (1 + 16 immeubles)109# + 1 fragment par unité nouvelle/modifiée (cache).110# -----------------------------------------------------------------------------111from __future__ import annotations112113import html as _html114import json115import re116117from bs4 import BeautifulSoup118119from ..schema import Listing, parse_price120from .base import BaseConnector121122BASE = "https://rent.urbanservices.ca"123LIST_URL = f"{BASE}/Listing/Listings"124125126def _extract_json(html: str, marker: str):127 """Décode la structure JSON qui suit `marker` dans un script inline."""128 i = html.find(marker)129 if i < 0:130 return None131 try:132 data, _ = json.JSONDecoder().raw_decode(html[i + len(marker):])133 except Exception:134 return None135 return data136137138def _sqft(raw) -> float | None:139 try:140 v = float(str(raw).strip().replace(" ", "").replace(" ", "")141 .replace(",", "."))142 except (TypeError, ValueError):143 return None144 return v if 80 <= v <= 20000 else None145146147class UrbanServicesConnector(BaseConnector):148 source_id = "urban_services"149 request_delay = 0.6150 max_buildings = 40 # garde-fou pages immeuble (16 au 2026-08)151 max_images = 12152153 def fetch(self) -> list[Listing]:154 html = self.get(LIST_URL).text155 bs_units = _extract_json(html, "var units = ") or []156157 # regrouper le JSON par immeuble (parc québécois seulement)158 by_pub: dict[str, list[dict]] = {}159 for u in bs_units:160 addr = u.get("Address") or {}161 prov = ((addr.get("Province") or {}).get("ProvinceCode") or "")162 if prov.upper() != "QC":163 continue # Ottawa (Ontario) : exclu164 pub = str((u.get("Building") or {})165 .get("PublicListBuildingName") or "")166 if pub:167 by_pub.setdefault(pub, []).append(u)168169 listings: list[Listing] = []170 for pub, units in sorted(by_pub.items())[: self.max_buildings]:171 try:172 listings.extend(self._building(pub, units))173 except Exception:174 continue # un immeuble ne bloque pas le reste175 # dédup par external_id (sécurité)176 uniq: dict[str, Listing] = {}177 for lst in listings:178 uniq.setdefault(lst.external_id, lst)179 return list(uniq.values())180181 # -- page immeuble /b/<id> : inventaire complet + commodités -------------------182 def _building_page(self, pub: str) -> tuple[list[dict], list[str]]:183 """(lignes d'unités des onglets, commodités de l'immeuble)."""184 html = self.get(f"{BASE}/b/{pub}").text185 soup = BeautifulSoup(html, "html.parser")186 rows: list[dict] = []187 for a in soup.select("ul.wpb-tabs-menu a.apartment-view-potential"):188 spans = [s.get_text(" ", strip=True) for s in a.find_all("span")]189 if len(spans) >= 6 and spans[0]:190 rows.append({ # Unité, Prix, pi², chambres, sdb, dispo191 "unit": spans[0], "price": spans[1], "sqft": spans[2],192 "beds": spans[3], "baths": spans[4], "dispo": spans[5],193 "uid": str(a.get("data-unitid") or "")})194 amenities: list[str] = []195 for li in soup.select(".facilities ul li label"):196 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))197 if 3 <= len(t) <= 90 and t not in amenities:198 amenities.append(t)199 return rows, amenities200201 # -- fragment détail /Listing/ApartmentView?id=<unitid> ---------------------202 def _fetch_apartment(self, uid: str) -> dict:203 """Galerie complète, champs structurés et « Commentaires » de l'unité."""204 html = self.get(f"{BASE}/Listing/ApartmentView", params={"id": uid}).text205 soup = BeautifulSoup(html, "html.parser")206 out: dict = {}207 images: list[str] = []208 for a in soup.select(".content-slider a[href]"):209 u = str(a.get("href") or "")210 if u.startswith("http") and u not in images:211 images.append(u)212 if images:213 out["images"] = images[: self.max_images]214 fields: dict[str, str] = {}215 for li in soup.select("ul.main-items li"):216 lab, val = li.select_one("p.title"), li.find("h4")217 if lab and val:218 k = re.sub(r"\s+", " ", lab.get_text(" ", strip=True))219 v = re.sub(r"\s+", " ", val.get_text(" ", strip=True))220 if k and v and k not in fields:221 fields[k] = v222 if fields:223 out["fields"] = fields224 notes = soup.select_one(".unit-notes p")225 if notes:226 lines = [re.sub(r"\s+", " ", t).strip()227 for t in notes.stripped_strings]228 txt = ". ".join(dict.fromkeys(x.rstrip(".") for x in lines if x))229 if txt:230 out["comments"] = (txt + ".")[:1500]231 return out232233 def _building(self, pub: str, units: list[dict]) -> list[Listing]:234 rows, amenities = self._building_page(pub)235236 # infos communes de l'immeuble depuis le JSON de la liste237 ref = units[0]238 addr = ref.get("Address") or {}239 # le JSON Razor du portail encode les apostrophes (') : décoder240 bname = _html.unescape(str(ref.get("BuildingName") or "")).strip()241 try:242 lat = float(addr.get("Latitude"))243 lng = float(addr.get("Longitude"))244 except (TypeError, ValueError):245 lat = lng = None246 contact: dict = {}247 contacts = ((ref.get("Building") or {})248 .get("ListingEmployeesContacts") or [])249 if contacts:250 c = contacts[0]251 contact = {k: v for k, v in [252 ("name", c.get("FullName")),253 ("phone", c.get("FormattedPhoneNumber")),254 ("email", c.get("Email"))] if v}255 b_img = str(ref.get("BuildingPreviewUrl") or "")256 by_name = {str((u.get("Apartment") or {}).get("UnitName") or ""): u257 for u in units}258259 out: list[Listing] = []260 seen: set[str] = set()261 for row in rows:262 num = row["unit"].strip()263 if not num or num in seen:264 continue265 seen.add(num)266 js = by_name.get(num) or {}267 out.append(self._listing(pub, num, row, js, bname, addr,268 amenities, contact, b_img, lat, lng))269 # unités du JSON absentes des onglets (prudence : ne rien perdre)270 for num, js in by_name.items():271 if num and num not in seen:272 seen.add(num)273 out.append(self._listing(pub, num, None, js, bname, addr,274 amenities, contact, b_img, lat, lng))275 return out276277 # -- une annonce par unité -------------------------------------------------------278 def _listing(self, pub: str, num: str, row: dict | None, js: dict,279 bname: str, addr: dict, amenities: list[str], contact: dict,280 b_img: str, lat, lng) -> Listing:281 apt = js.get("Apartment") or {}282283 # chambres / sdb : onglet de la page immeuble, sinon JSON de la liste284 def _int(v) -> int | None:285 try:286 return int(str(v).strip())287 except (TypeError, ValueError):288 return None289290 beds = _int(row["beds"]) if row else None291 if beds is None:292 beds = _int(apt.get("NumberOfBedrooms"))293 baths = _int(row["baths"]) if row else None294 if baths is None:295 baths = _int(apt.get("NumberOfBathrooms"))296 # convention Building Stack (comme edifia) : 0 chambre = studio297 unit_type = "" if beds is None else ("Studio" if beds == 0298 else f"{beds + 2}½")299300 # prix : JSON structuré prioritaire, sinon texte de l'onglet301 price = float(apt.get("Price") or 0) or None302 price_label = str(apt.get("PriceFormatted") or "")303 if row and not price_label:304 price_label = row["price"]305 if price is None and row:306 price = parse_price(row["price"])307308 area = _sqft(apt.get("Area"))309 if area is None and row:310 area = _sqft(row["sqft"])311312 # disponibilité : texte de l'onglet (« Disponible dès maintenant! »,313 # « oct. 01, 2027 »…) — préfixé quand c'est une date nue314 availability = ""315 if row:316 dispo = row["dispo"].strip()317 if dispo and re.search(r"\d", dispo) and "maintenant" not in dispo.lower():318 availability = f"Libre {dispo}"319 else:320 availability = dispo321322 # fragment détail (cache BD) : galerie, étage, équipements, commentaires323 uid = (row or {}).get("uid") or (str(js.get("ApartmentId") or "") or "")324 payload: dict = {}325 if uid:326 key = f"a1|{price_label or price}|{availability}|{area or ''}"327 try:328 payload = self.detail(f"{pub}-{num}", key,329 lambda u=uid: self._fetch_apartment(u))330 except Exception:331 payload = {}332 fields: dict = payload.get("fields") or {}333334 details: dict = {}335 if bname:336 details["building"] = bname337 if contact:338 details["contact"] = dict(contact)339 if beds is not None:340 details["bedrooms"] = beds341 if baths is not None:342 details["bathrooms"] = baths343 etage = fields.get("Étage")344 if etage and etage.isdigit():345 details["floor"] = int(etage)346 if area is None:347 area = _sqft(fields.get("Superficie (pi.ca)"))348349 # commodités : immeuble + équipements de l'unité (« Plancher : Bois… »)350 _GENERIC = {"Superficie (pi.ca)", "Étage", "Ch. à coucher",351 "Salles de bains", "Salles à manger"}352 unit_amen: list[str] = []353 for k, v in fields.items():354 if k in _GENERIC:355 continue356 lbl = k if v.lower() in ("oui", "gratuit", "inclus") else f"{k} : {v}"357 if v.lower() == "non":358 continue359 if lbl not in unit_amen:360 unit_amen.append(lbl)361 all_amen = list(amenities) + [a for a in unit_amen362 if a not in amenities]363364 # description : « Commentaires » de la fiche, sinon résumé des faits365 desc = payload.get("comments") or ""366 facts = " — ".join(x for x in [367 f"{area:g} pi²" if area else "",368 f"{beds} chambre(s)" if beds else "",369 f"{baths} salle(s) de bain" if baths else ""] if x)370 if desc and facts:371 desc = f"{desc}\n{facts}"372 elif not desc:373 desc = facts374375 # galerie complète de la fiche, sinon aperçus du JSON de la liste376 # (PreviewUrl = miniature du même visuel : ignorée si galerie présente)377 images: list[str] = [u for u in (payload.get("images") or [])378 if isinstance(u, str) and u.startswith("http")]379 if not images:380 prev = str(js.get("PreviewUrl") or "")381 if prev.startswith("http"):382 images.append(prev)383 if b_img.startswith("http") and b_img not in images:384 images.append(b_img)385386 apt_id = js.get("ApartmentId")387 url = (f"{BASE}/b/{pub}/{apt_id}" if apt_id else f"{BASE}/b/{pub}")388 title = (f"{bname} — unité {num}" if bname389 else f"Urban Services — unité {num}")390 return Listing(391 source=self.source_id,392 external_id=f"{pub}-{num}",393 url=url,394 title=title,395 address=_html.unescape(str(addr.get("Full") or "")),396 sector="",397 city=_html.unescape(str(addr.get("City") or "")),398 unit_type=unit_type,399 price=price,400 price_label=price_label,401 availability=availability,402 area_sqft=area,403 description=desc,404 amenities=all_amen,405 details=details,406 images=images[: self.max_images],407 lat=lat,408 lng=lng,409 )410