SPB Git

Repository Public

osgoode.py 14.9 KB 362 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/osgoode.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# 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 (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/osgoode.py : connecteur Osgoode Properties (osgoodeproperties.com)91#   Grand gestionnaire Ottawa-Gatineau ; côté Québec : 4 immeubles à Gatineau92#   (Le 700 St Joseph, Le Faubourg de l'Île, Village Cité-des-Jeunes,93#   Le Salaberry). Site RentCafe/Yardi protégé par Cloudflare (403 direct) :94#   tout passe par le rendu Scrapfly, comme realstar.py (ex-Firecrawl).95#   1) pages recherche /1-bedroom|2-bedroom/qc/gatineau/apartments -> cartes96#      propriétés (li.property-box : nom, adresse, lits/sdb/pi², fourchette97#      de prix, téléphone, vignette) — les cartes hors Québec (liens /on/)98#      sont ignorées ;99#   2) fiche propriété -> galerie resource.rentcafe.com ;100#   3) /floorplans -> plans structurés (nom, chambres, sdb, pi², prix) ;101#      ⚠ contrairement à Realstar, AUCUN décompte d'unités disponibles n'est102#      publié -> availability reste vide (rien d'inventé).103#   Une annonce par propriété (uid stables). Les fiches passent par104#   self.detail(...) (cache BD) avec budget de rendus par sync.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import hashlib109import re110111from bs4 import BeautifulSoup112113from ..schema import Listing, parse_price114from .base import BaseConnector115116BASE = "https://www.osgoodeproperties.com"117# pages recherche par typologie (chaque carte affiche la fourchette complète118# de l'immeuble : l'union 1-2 chambres couvre tout le parc résidentiel)119SEARCH_PATHS = ["/1-bedroom/qc/gatineau/apartments",120                "/2-bedroom/qc/gatineau/apartments"]121122_BED_TYPES = {"0": "Studio", "1": "3½", "2": "4½", "3": "5½", "4": "6½"}123_SKIP_IMG = re.compile(r"logo|icon|favicon|placeholder", re.I)124125126class _BudgetReached(Exception):127    """Plafond de rendus atteint pour cette synchronisation."""128129130class OsgoodeConnector(BaseConnector):131    source_id = "osgoode"132    request_delay = 1.0133    max_properties = 10134    max_images = 20135    max_renders = 14         # 2 recherches + 2 par propriété (hors cache)136137    # -- rendu JS avec attente (Cloudflare + SPA RentCafe) — Scrapfly ----------138    # (migré de Firecrawl le 2026-08-27 ; retry + échec honnête dans139    #  BaseConnector.get_rendered, que les fixtures monkeypatchent)140    def _rendered(self, url: str, wait_ms: int = 9000) -> str:141        return self.get_rendered(url, wait_ms)142143    # -- fetch -----------------------------------------------------------------144    def fetch(self) -> list[Listing]:145        self._renders = 0146        listings: list[Listing] = []147        seen: set[str] = set()148        for path in SEARCH_PATHS:149            try:150                html = self._rendered(BASE + path, 10000)151                self._renders += 1152            except Exception:153                continue154            soup = BeautifulSoup(html, "html.parser")155            # [class*=…] : rendu Scrapfly = cartes encore property-box-hidden156            for card in soup.select('li[class*="property-box"]'):157                try:158                    a = card.select_one("a[href*='/apartments/qc/']")159                    if not a:160                        continue    # propriété ontarienne : exclue161                    url = (a.get("href") or "").split("?")[0].rstrip("/")162                    m = re.search(r"/apartments/qc/([a-z0-9\-.]+)/([a-z0-9\-]+)",163                                  url)164                    if not m or m.group(2) in seen:165                        continue166                    if len(seen) >= self.max_properties:167                        break168                    seen.add(m.group(2))169                    listings.append(170                        self._property_listing(card, url, m.group(2)))171                except Exception:172                    continue173        return listings174175    # -- carte propriété ---------------------------------------------------------176    def _property_listing(self, card, url: str, slug: str) -> Listing:177        name = ""178        fav = card.select_one("[data-property]")179        if fav:180            name = (fav.get("data-property") or "").strip()181        if not name:182            h = card.select_one(".property-name a")183            if h:184                name = h.get_text(" ", strip=True)185        name = re.sub(r"\s*opens in a new tab\s*", "", name).strip()186        name = name or slug.replace("-", " ").title()187188        addr_el = card.select_one(".card-prop-address")189        address = addr_el.get_text(" ", strip=True) if addr_el else ""190191        meta = card.select_one(".card-bed-bath-rent")192        beds = baths = sqft = ""193        if meta:194            for li in meta.select("li"):195                it = li.get_text(" ", strip=True)196                if "Bed" in it:197                    beds = it198                elif "Bath" in it:199                    baths = it200                elif "Sq" in it:201                    sqft = re.sub(r"\s*to\s*-\s*", " - ", it)202        unit_type = ""203        bm = re.match(r"^(\d)(?:\s|-)?.*Bed", beds or "")204        if bm and "-" not in beds.split("Bed")[0]:205            unit_type = _BED_TYPES.get(bm.group(1), "")206207        # fourchette « $1,015.00 to - $1,544.00 » de la carte208        price = None209        price_label = ""210        pm = re.search(r"\$[\d,]+(?:\.\d{2})?(?:(?:\s*(?:-|to))+\s*"211                       r"\$[\d,]+(?:\.\d{2})?)?",212                       card.get_text(" ", strip=True))213        if pm:214            price_label = re.sub(r"\s*to\s*-\s*", " - ", pm.group(0))215            first = (price_label.split("-")[0]216                     .replace("$", "").replace(",", "").strip())217            try:218                price = float(first)219            except ValueError:220                price = parse_price(price_label)221            if "-" in price_label:222                price_label = "À partir de " + price_label223224        phone = ""225        tel = card.select_one("a[href^='tel:']")226        if tel:227            tm = re.search(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})",228                           tel.get("href", ""))229            if tm:230                phone = f"{tm.group(1)}-{tm.group(2)}-{tm.group(3)}"231232        images: list[str] = []233        img = card.select_one("img[src*='rentcafe']")234        if img and img.get("src"):235            images.append(img["src"])236237        # fiche + plans via cache BD (clé = contenu de la carte liste)238        key = hashlib.sha1(239            f"{name}|{address}|{beds}|{baths}|{sqft}|{price_label}"240            .encode("utf-8")).hexdigest()241        try:242            payload = self.detail(slug, key, lambda: self._fetch_detail(url))243        except Exception:244            payload = {}245246        for im in (payload.get("images") or []):247            if im not in images:248                images.append(im)249250        # plans structurés : prix « à partir de » réel + résumé fidèle251        plans = payload.get("floorplans") or []252        prices = [p["price"] for p in plans253                  if p.get("price") and 100 <= p["price"] <= 20000]254        if prices:255            price = min(prices)256            price_label = (f"À partir de {price:,.0f} $/mois"257                           .replace(",", " ") if len(plans) > 1258                           else f"{price:,.0f} $/mois".replace(",", " "))259        plan_bits = []260        for p in plans[:8]:261            seg = p["name"]262            if p.get("sqft"):263                seg += f" ({p['sqft']:.0f} pi²)"264            if p.get("price"):265                seg += f" : {p['price']:,.0f} $/mois".replace(",", " ")266            plan_bits.append(seg)267        if len(plans) == 1 and plans[0].get("unit_type"):268            unit_type = plans[0]["unit_type"]269270        details: dict = {}271        if phone:272            details["contact"] = {"phone": phone}273274        desc_parts = ([payload["description"]]275                      if payload.get("description") else [])276        desc_parts += [b for b in [beds, baths, sqft] if b]277        if plan_bits:278            desc_parts.append("Plans : " + " ; ".join(plan_bits))279280        return Listing(281            source=self.source_id,282            external_id=slug,283            url=url,284            title=name,285            address=address,286            sector="",           # le site ne publie pas le secteur par immeuble287            city="Gatineau",288            unit_type=unit_type,289            price=price,290            price_label=price_label,291            availability="",     # aucun décompte d'unités publié292            description=" — ".join(desc_parts)[:900],293            details=details,294            images=images[: self.max_images],295        )296297    # -- pages détail (fiche + plans) --------------------------------------------298    def _fetch_detail(self, url: str) -> dict:299        if self._renders + 2 > self.max_renders:300            raise _BudgetReached()301        self._renders += 2302303        payload: dict = {"description": "", "images": [], "floorplans": []}304        try:305            psoup = BeautifulSoup(self._rendered(url, 8000), "html.parser")306            for im in psoup.select("img[src*='resource.rentcafe.com']"):307                src = im.get("src", "")308                if src and not _SKIP_IMG.search(src) \309                        and src not in payload["images"]:310                    payload["images"].append(src)311            paras = [p.get_text(" ", strip=True) for p in psoup.find_all("p")]312            paras = [p for p in paras if len(p) > 80]313            if paras:314                payload["description"] = " ".join(paras[:2])[:600]315        except Exception:316            pass317318        try:319            fh = self._rendered(url + "/floorplans", 10000)320            payload["floorplans"] = self._parse_floorplans(fh)321        except Exception:322            pass323        return payload324325    @staticmethod326    def _parse_floorplans(html: str) -> list[dict]:327        """Cartes de plans RentCafe : nom, chambres, pi², prix (ou fourchette,328        borne basse retenue). Pas de décompte de disponibilité chez Osgoode."""329        soup = BeautifulSoup(html, "html.parser")330        plans: list[dict] = []331        for cont in soup.select("div[id^='fp-container-']"):332            try:333                name_el = cont.select_one("span[data-selenium-id$='Name']")334                name = name_el.get_text(" ", strip=True) if name_el else ""335                if not name:336                    continue337                plan: dict = {"name": name}338                beds_el = cont.select_one("span[data-selenium-id$='Beds']")339                if beds_el:340                    bm = re.match(r"^\s*(\d)\s*Bed",341                                  beds_el.get_text(" ", strip=True))342                    if bm:343                        plan["unit_type"] = _BED_TYPES.get(bm.group(1), "")344                sq_el = cont.select_one("span[data-selenium-id$='SqFt']")345                if sq_el:346                    sm = re.search(r"([\d,]{2,})",347                                   sq_el.get_text(" ", strip=True))348                    if sm:349                        v = float(sm.group(1).replace(",", ""))350                        if 80 <= v <= 20000:351                            plan["sqft"] = v352                rent_el = cont.select_one("span[data-selenium-id$='Rent']")353                if rent_el:354                    rm = re.search(r"\$([\d,]+)(?:\.\d{2})?",355                                   rent_el.get_text(" ", strip=True))356                    if rm:357                        plan["price"] = float(rm.group(1).replace(",", ""))358                plans.append(plan)359            except Exception:360                continue361        return plans362
Files main
Menu

Theme