Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/medallion.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/medallion.py : connecteur Medallion Corporation (medallioncorp.com)91# Gestionnaire torontois (~25 000 unités est., Toronto/GTA + Brampton, Ajax,92# Whitby, Oshawa, Richmond Hill, Hamilton, London). Site WordPress (thème93# RealHomes/inspiry + CPT UI) SANS anti-bot : le CPT `property` est exposé94# par l'API REST standard — `/wp-json/wp/v2/properties?per_page=100`95# (84 propriétés au moment de l'écriture, x-wp-total 84, une seule page).96# Chaque entrée porte dans `class_list` la ville (property-city-<slug>), le97# type (property-type-residential/commercial…) et le statut (property-status-98# for-rent vs commercial-rent) : on ne garde que le résidentiel à louer99# (56 immeubles). `property_meta` fournit l'adresse civique complète100# (REAL_HOMES_property_address), les coordonnées GPS et la galerie photo101# (URLs wp-content/uploads, variantes redimensionnées).102# Les prix/types d'unités ne sont PAS dans le flux : la fiche propriété103# (rendu serveur) affiche un accordéon « Floor Plans » (nom, N Bedrooms,104# N Bathrooms, prix plancher, « Call for Availability ») — visitée via le105# cache BD self.detail() (clé = date `modified` du flux). Une annonce par106# plan d'étage ; repli « une annonce par propriété » (sans prix inventé)107# quand l'accordéon est absent.108#109# Expansion Ontario — GATÉE par LOUKA_ONTARIO=1 : sans la variable, le110# connecteur est `disabled` et exclu du registre (zéro impact prod QC).111# -----------------------------------------------------------------------------112from __future__ import annotations113114import os115import re116117from bs4 import BeautifulSoup118119from ..schema import Listing, normalize_unit_type, parse_price120from .base import BaseConnector121122BASE = "https://medallioncorp.com"123FEED_URL = f"{BASE}/wp-json/wp/v2/properties?per_page=100"124125# Gate expansion Ontario : le connecteur reste hors registre tant que la126# variable d'environnement LOUKA_ONTARIO=1 n'est pas posée.127_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"128129# villes du flux (slug de class_list `property-city-<slug>`) -> affichage ;130# tout slug inconnu est titré tel quel (« richmond-hill » -> « Richmond Hill »)131_CITY_LABEL = {132 "toronto": "Toronto",133 "brampton": "Brampton",134 "ajax": "Ajax",135 "whitby": "Whitby",136 "oshawa": "Oshawa",137 "richmond-hill": "Richmond Hill",138 "hamilton": "Hamilton",139 "london": "London",140 "milton": "Milton",141}142143# lignes de l'accordéon plans d'étage : « 2 Bedrooms », « 1.5 Bathrooms »144_BED_RE = re.compile(r"(\d+)\s*Bedroom", re.I)145_BATH_RE = re.compile(r"([\d.]+)\s*Bathroom", re.I)146_SQFT_RE = re.compile(r"([\d,]+)\s*(?:sq\.?\s*ft|pi2|ft2)", re.I)147_CITY_CLS_RE = re.compile(r"^property-city-(.+)$")148149150class MedallionConnector(BaseConnector):151 source_id = "medallion"152 request_delay = 1.0153 disabled = not _ONTARIO # gate expansion Ontario (LOUKA_ONTARIO=1)154 max_properties = 80 # garde-fou (56 immeubles résidentiels aujourd'hui)155 max_images = 20156157 def fetch(self) -> list[Listing]:158 props = self.get(FEED_URL, headers={"Accept": "application/json"}).json()159160 listings: list[Listing] = []161 count = 0162 for p in props:163 try:164 cls = set(p.get("class_list") or [])165 # résidentiel longue durée seulement : à louer, non commercial166 if "property-status-for-rent" not in cls:167 continue168 if "property-type-residential" not in cls:169 continue170 if count >= self.max_properties:171 break172 count += 1173 listings.extend(self._property_listings(p))174 except Exception:175 continue176 return listings177178 # -- annonces d'une propriété (une par plan d'étage, repli propriété) -------179 def _property_listings(self, p: dict) -> list[Listing]:180 pid = str(p.get("id"))181 url = p.get("link") or ""182 title = BeautifulSoup((p.get("title") or {}).get("rendered") or "",183 "html.parser").get_text(" ", strip=True)184 meta = p.get("property_meta") or {}185186 # adresse civique complète du flux (« 25 Kitney Dr, Ajax, ON L1S 0G6,187 # Canada ») — suffixe « , Canada » retiré188 address = re.sub(r",\s*Canada$", "",189 (meta.get("REAL_HOMES_property_address") or "").strip())190191 # ville : slug property-city-<slug> de class_list192 city = ""193 for c in p.get("class_list") or []:194 m = _CITY_CLS_RE.match(c)195 if m:196 slug = m.group(1)197 city = _CITY_LABEL.get(slug, slug.replace("-", " ").title())198 break199200 # coordonnées GPS du flux (finalize() valide la bbox Ontario)201 loc = meta.get("REAL_HOMES_property_location") or {}202 try:203 lat = float(loc.get("latitude")) if loc.get("latitude") else None204 lng = float(loc.get("longitude")) if loc.get("longitude") else None205 except (TypeError, ValueError):206 lat = lng = None207208 # galerie photo : variantes redimensionnées du flux (large ~1024px)209 images: list[str] = []210 for img in meta.get("REAL_HOMES_property_images") or []:211 sizes = (img or {}).get("sizes") or {}212 u = ""213 for k in ("1536x1536", "large", "medium_large"):214 u = (sizes.get(k) or {}).get("url") or ""215 if u:216 break217 if not u and img.get("file"):218 u = f"{BASE}/wp-content/uploads/{img['file']}"219 if u and u not in images:220 images.append(u)221 images = images[: self.max_images]222223 # description : contenu WordPress de la fiche (rendu texte)224 desc = BeautifulSoup((p.get("content") or {}).get("rendered") or "",225 "html.parser").get_text(" ", strip=True)[:600]226227 # fiche propriété (plans d'étage + commodités) via le cache BD :228 # revisitée seulement quand le post WordPress est modifié229 feed_key = str(p.get("modified") or p.get("modified_gmt") or "")230 d = self.detail(pid, feed_key, lambda: self._fetch_detail(url))231 amenities = d.get("amenities") or []232233 common = dict(234 source=self.source_id, url=url, address=address, city=city,235 province="ON", description=desc, amenities=amenities[:25],236 images=images, lat=lat, lng=lng,237 )238239 # une annonce par plan d'étage (type d'unité + prix plancher affiché)240 out: list[Listing] = []241 for fp in d.get("floorplans") or []:242 name = fp.get("name") or ""243 slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")244 beds = fp.get("beds")245 price = fp.get("price")246 out.append(Listing(247 external_id=f"{pid}-{slug or 'u'}",248 title=f"{title} — {name}" if name else title,249 unit_type=("Studio" if beds == 0 else normalize_unit_type(250 f"{int(beds)} chambres") if beds is not None251 else normalize_unit_type(name)),252 bedrooms=beds,253 bathrooms=fp.get("baths"),254 price=price,255 price_label=(f"À partir de {price:.0f} $ /mois"256 if price is not None else ""),257 availability=fp.get("avail") or "",258 area_sqft=fp.get("sqft"),259 **common,260 ))261 if out:262 return out263264 # repli : une annonce par propriété — aucun prix inventé (None = inconnu)265 return [Listing(266 external_id=pid,267 title=title,268 unit_type="",269 **common,270 )]271272 # -- fiche propriété : plans d'étage + commodités ----------------------------273 def _fetch_detail(self, url: str) -> dict:274 """Scrape l'accordéon « Floor Plans » (nom, chambres, sdb, prix,275 disponibilité) et la liste « Buildings Features » de la fiche."""276 out: dict = {"floorplans": [], "amenities": []}277 if not url:278 return out279 try:280 page = self.get(url).text281 except Exception:282 return out283 soup = BeautifulSoup(page, "html.parser")284285 # plans d'étage : <div class="floor-plan"> (nom h3, meta « N Bedrooms /286 # N Bathrooms / prix / Call for Availability »)287 seen: set[str] = set()288 for fp in soup.select(".floor-plans-accordions .floor-plan"):289 h = fp.select_one(".floor-plan-title .title h3")290 name = h.get_text(" ", strip=True) if h else ""291 if not name or name.lower() in seen:292 continue293 seen.add(name.lower())294 meta_el = fp.select_one(".floor-plan-meta")295 meta_txt = meta_el.get_text(" ", strip=True) if meta_el else ""296 mb = _BED_RE.search(meta_txt) or _BED_RE.search(name)297 beds = (float(mb.group(1)) if mb298 else 0.0 if re.search(r"bachelor|studio", name, re.I)299 else None)300 mba = _BATH_RE.search(meta_txt)301 msq = _SQFT_RE.search(meta_txt)302 sqft = float(msq.group(1).replace(",", "")) if msq else None303 price_el = fp.select_one(".floor-price-value")304 price = parse_price(price_el.get_text(" ", strip=True)) \305 if price_el else None306 # texte de dispo : ce qui suit le prix (« Call for Availability »)307 avail = ""308 fprice = fp.select_one(".floor-price")309 if fprice:310 avail = fprice.get_text(" ", strip=True)311 if price_el:312 avail = avail.replace(313 price_el.get_text(" ", strip=True), "").strip()314 out["floorplans"].append({315 "name": name,316 "beds": beds,317 "baths": float(mba.group(1)) if mba else None,318 "sqft": sqft if sqft and 80 <= sqft <= 20000 else None,319 "price": price,320 "avail": avail,321 })322323 # commodités : « Buildings Features » (liste à puces de la fiche)324 h = soup.find(["h3", "h4"], string=re.compile(325 r"Buildings? Features", re.I))326 if h:327 ul = h.find_next("ul")328 if ul:329 amenities = []330 for li in ul.find_all("li"):331 t = li.get_text(" ", strip=True)332 if t and len(t) < 60 and t not in amenities:333 amenities.append(t)334 out["amenities"] = amenities[:25]335 return out336