Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/chartwell.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/chartwell.py : Chartwell (chartwell.com/fr) — résidences pour91# retraités. Chaîne PANCANADIENNE : on ne garde QUE le Québec, garanti deux92# fois — par le préfixe /fr/qc/ des URLs du sitemap ET par le champ93# Province Abbreviation == "QC" des données de la page.94# Site Next.js/Sitecore rendu serveur : chaque page « plans des95# appartements » (/fr/qc/<ville>/<résidence>/plans-des-appartements)96# embarque dans __NEXT_DATA__ la fiche complète de la résidence (nom,97# adresse civique, ville, lat/lng, téléphone) et la liste98# « Property Suit Plans » : type d'unité (Studio, 2 1/2 … 5 1/2), prix99# « À partir de » (Regular SuitePrice), niveau de soins (Autonome…),100# inclusions (Key Features) et visuel. Une annonce Lou-Ka par résidence ×101# type d'unité, prix plancher « à partir de ».102# -----------------------------------------------------------------------------103from __future__ import annotations104105import json106import re107108from ..schema import Listing, normalize_unit_type109from .base import BaseConnector110111SITEMAP = "https://chartwell.com/sitemap.xml"112113_PLANS_URL_RE = re.compile(114 r"https://chartwell\.com/fr/qc/[a-z0-9-]+/[a-z0-9-]+/plans-des-appartements$")115_NEXT_DATA_RE = re.compile(116 r'<script id="__NEXT_DATA__"[^>]*>([\s\S]*?)</script>')117118119def _jv(fields: dict, name: str):120 """Valeur `jsonValue` d'un champ Sitecore (liste de {name, jsonValue})."""121 f = fields.get(name)122 return f.get("jsonValue") if isinstance(f, dict) else None123124125def _scalar(fields: dict, name: str) -> str:126 v = _jv(fields, name)127 if isinstance(v, dict):128 return str(v.get("value") or "").strip()129 return ""130131132class ChartwellConnector(BaseConnector):133 source_id = "chartwell"134 request_delay = 0.8135 timeout = 45136137 # -- fiche résidence (champs Sitecore du parent de la page plans) ----------------138 @staticmethod139 def _property_fields(next_data: dict) -> dict | None:140 """Trouve le nœud « fields » du bien (celui qui porte141 Property Suit Plans) n'importe où dans le layout Sitecore."""142 stack = [next_data]143 while stack:144 node = stack.pop()145 if isinstance(node, dict):146 if isinstance(node.get("fields"), list):147 names = {f.get("name") for f in node["fields"]148 if isinstance(f, dict)}149 if "Property Suit Plans" in names and "Latitude" in names:150 return {f["name"]: f for f in node["fields"]151 if isinstance(f, dict) and f.get("name")}152 stack.extend(node.values())153 elif isinstance(node, list):154 stack.extend(node)155 return None156157 def _parse_page(self, url: str, html: str) -> list[Listing]:158 m = _NEXT_DATA_RE.search(html)159 if not m:160 return []161 try:162 data = json.loads(m.group(1))163 except ValueError:164 return []165 fields = self._property_fields(data)166 if not fields:167 return []168169 # garde-fou province : Chartwell est pancanadien, Québec seulement170 prov = _jv(fields, "Province") or []171 abbr = ""172 if isinstance(prov, list) and prov:173 abbr = str(((prov[0].get("fields") or {})174 .get("Province Abbreviation") or {}).get("value") or "")175 if abbr and abbr.upper() != "QC":176 return []177178 name = (_scalar(fields, "NavigationTitle")179 or _scalar(fields, "Short Property Name")180 or _scalar(fields, "Property Name"))181 address = _scalar(fields, "StreetNameAndNumber")182 postal = _scalar(fields, "Postal code")183 phone = _scalar(fields, "Contact Number")184 city = ""185 cv = _jv(fields, "City") or []186 if isinstance(cv, list) and cv:187 # « City Name » porte les accents (Lévis), displayName non (Levis)188 city = str(((cv[0].get("fields") or {}).get("City Name") or {})189 .get("value")190 or cv[0].get("displayName") or cv[0].get("name") or "")191 lat = lng = None192 try:193 lat = float(_scalar(fields, "Latitude"))194 lng = float(_scalar(fields, "Longitude"))195 except ValueError:196 lat = lng = None197198 thumb = ""199 tv = _jv(fields, "Thumbnail Photo")200 if isinstance(tv, dict):201 thumb = str(((tv.get("value") or {}).get("src")) or "")202203 res_slug = url.rstrip("/").rsplit("/", 2)[-2]204 city_slug = url.rstrip("/").rsplit("/", 3)[-3]205206 def val(d, *keys):207 cur = d208 for k in keys:209 if not isinstance(cur, dict):210 return None211 cur = cur.get(k)212 return cur213214 out: list[Listing] = []215 plans = _jv(fields, "Property Suit Plans") or []216 for plan in plans:217 pf = plan.get("fields") if isinstance(plan, dict) else None218 if not isinstance(pf, dict):219 continue220 suite = val(pf, "SuiteName", "fields", "suiteType", "value") or ""221 price_raw = val(pf, "Regular SuitePrice", "value")222 care = val(pf, "Care Level", "fields",223 "Suite Care Level", "value") or ""224 try:225 price = float(str(price_raw).replace(" ", "").replace(",", ""))226 except (TypeError, ValueError):227 continue228 if not suite or not 400 <= price <= 20000:229 continue230 feats = []231 for kf in (val(pf, "Key Features") or []):232 t = val(kf, "fields", "Key Feature Name", "value")233 if t and t not in feats:234 feats.append(str(t))235 images = []236 bg = val(pf, "background Image", "value", "src")237 if bg:238 images.append(str(bg))239 if thumb:240 images.append(thumb)241 details = {"Résidence pour aînés": "oui"}242 if care:243 details["Niveau de soins"] = care244 if postal:245 details["Code postal"] = postal246 if phone:247 details["contact"] = {"phone": phone}248 eid = (f"{city_slug}-{res_slug}-"249 f"{re.sub(r'[^a-z0-9]+', '-', suite.lower()).strip('-')}")250 out.append(Listing(251 source=self.source_id,252 external_id=eid,253 url=url,254 title=f"{suite} — {name}",255 address=address,256 city=city,257 unit_type=normalize_unit_type(suite),258 price=price,259 price_label=f"À partir de {price:,.0f} $ par mois"260 .replace(",", " "),261 amenities=feats,262 details=details,263 images=images,264 lat=lat,265 lng=lng,266 ))267 return out268269 def fetch(self) -> list[Listing]:270 out: list[Listing] = []271 xml = self.get(SITEMAP).text272 urls = sorted({u for u in re.findall(r"<loc>([^<]+)</loc>", xml)273 if _PLANS_URL_RE.match(u)})274 for url in urls:275 try:276 out.extend(self._parse_page(url, self.get(url).text))277 except Exception:278 continue279 return out280