SPB Git

Repository Public

cromwell.py 16.4 KB 403 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cromwell.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-09-1314#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/cromwell.py : connecteur Cromwell Management (cromwellmgt.ca)91#   ~20 immeubles à Montréal (Plateau, Outremont, Westmount, centre-ville,92#   Côte-des-Neiges, Hampstead). Les unités individuelles avec prix sont93#   publiées sur le site jumeau cromwellmontreal.ca (WordPress + thème94#   Houzez, rendu serveur) : cartes .item-listing-wrap avec data-listid,95#   fiches /property/<slug>/ pour photos, statut et description.96#   2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,97#   en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient98#   (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA99#   (même pattern que boreal_abitibi/citiluxx, hébergeur SiteGround identique).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import os105import re106import time107from urllib.parse import quote108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type112from .base import BaseConnector113114BASE = "https://cromwellmontreal.ca"115LIST_URL = f"{BASE}/apartments-for-rent-montreal/"116117IMG_RE = re.compile(118    r"https://cromwellmontreal\.ca/wp-content/uploads/"119    r"[^\"\s\\]+?\.(?:jpg|jpeg|png|webp)", re.I)120121# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)122_SG_MARKER = "/.well-known/sgcaptcha/"123124125def _sg_challenge(resp) -> bool:126    """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""127    if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():128        return True129    return _SG_MARKER in (resp.text or "")[:600]130131132# Municipalités de l'île qui ne sont pas des arrondissements de Montréal133_INDEPENDENT_CITIES = {134    "westmount": "Westmount", "hampstead": "Hampstead",135    "mont-royal": "Mont-Royal", "mount royal": "Mont-Royal",136    "côte-saint-luc": "Côte-Saint-Luc", "cote-saint-luc": "Côte-Saint-Luc",137    "montréal-ouest": "Montréal-Ouest", "montreal west": "Montréal-Ouest",138}139140141def _parse_price_us(raw: str) -> float | None:142    """'Starting at $1,995 /month' -> 1995.0 (symbole $ devant le nombre)."""143    m = re.search(r"\$\s*([\d,\s]+(?:\.\d{2})?)", raw or "")144    if not m:145        return None146    num = m.group(1).replace(",", "").replace(" ", "").replace(" ", "")147    try:148        val = float(num)149    except ValueError:150        return None151    return val if 100 <= val <= 20000 else None152153154def _unit_type(ptype: str, beds: str) -> str:155    """'1 Bedroom (3 1/2)' -> 3½ ; sinon via nb de chambres (0.5 = studio)."""156    m = re.search(r"(\d)\s*1/2", ptype or "")157    if m:158        return f"{m.group(1)}½"159    if re.search(r"studio", ptype or "", re.I):160        return "Studio"161    m = re.search(r"[\d.]+", beds or "")162    if m:163        n = float(m.group(0))164        if n < 1:165            return "Studio"166        return {1: "3½", 2: "4½", 3: "5½", 4: "6½"}.get(int(n), f"{int(n)} chambres")167    return normalize_unit_type(ptype)168169170class CromwellConnector(BaseConnector):171    source_id = "cromwell"172    request_delay = 0.6173    max_pages = 8            # garde-fou de pagination174    max_details = 60         # garde-fou de fetch des fiches175176    def _enable_residential_proxy(self) -> bool:177        """Route toute la session via Oxylabs résidentiel CA (session collante)."""178        endpoint = os.environ.get("OXYLABS_PROXY")179        user = os.environ.get("OXYLABS_PROXY_USER")180        pwd = os.environ.get("OXYLABS_PROXY_PASS")181        if not (endpoint and user and pwd):182            return False183        puser = f"{user}-cc-CA-sessid-cromwell{int(time.time())}-sesstime-10"184        proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"185        self.session.proxies = {"http": proxy, "https": proxy}186        self.session.verify = False  # CA MITM du proxy Oxylabs (cf. _resilient)187        return True188189    def _get_html(self, url: str) -> str:190        """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""191        resp = self.get(url)192        if not _sg_challenge(resp):193            return resp.text194        if not self.session.proxies and self._enable_residential_proxy():195            resp = self.get(url)196            if not _sg_challenge(resp):197                return resp.text198        raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")199200    def fetch(self) -> list[Listing]:201        listings: dict[str, Listing] = {}202203        # 1) Liste paginée des unités disponibles — la 1re page échoue204        #    franchement (fini le « 0 trouvé ok » silencieux du challenge)205        url = LIST_URL206        for page in range(self.max_pages):207            if page == 0:208                html = self._get_html(url)209            else:210                try:211                    html = self._get_html(url)212                except Exception:213                    break214            soup = BeautifulSoup(html, "html.parser")215            for it in soup.select("div.item-listing-wrap"):216                try:217                    lst = self._parse_card(it)218                except Exception:219                    continue220                if lst and lst.external_id not in listings:221                    listings[lst.external_id] = lst222            nxt = soup.select_one("a.page-link[rel=next], .pagination a.next,"223                                  " a[rel=next]")224            if not nxt or not nxt.get("href"):225                break226            url = nxt["href"]227228        # 2) Fiches détaillées (avec cache BD) : photos, description, statut,229        #    type exact, caractéristiques complètes, secteur230        for i, lst in enumerate(listings.values()):231            if i >= self.max_details:232                break233            key = hashlib.sha1("|".join([234                lst.title, lst.price_label, lst.address,235                ";".join(lst.amenities),236            ]).encode("utf-8")).hexdigest()237            try:238                payload = self.detail(lst.external_id, key,239                                      lambda u=lst.url: self._fetch_detail(u))240            except Exception:241                continue242            if payload.get("images"):243                lst.images = payload["images"]244            if payload.get("description"):245                lst.description = payload["description"]246            if payload.get("availability"):247                lst.availability = payload["availability"]248            if payload.get("unit_type"):249                lst.unit_type = payload["unit_type"]250            if payload.get("amenities"):251                lst.amenities = list(dict.fromkeys(252                    lst.amenities + payload["amenities"]))253            if payload.get("sector") and not lst.sector:254                lst.sector = payload["sector"]255256        return list(listings.values())257258    # -- fiche détaillée (thème Houzez) ------------------------------------------259    def _fetch_detail(self, url: str) -> dict:260        # _get_html lève sur challenge : pas de payload vide en detail_cache261        detail = self._get_html(url)262        payload: dict = {}263        imgs = [u for u in dict.fromkeys(IMG_RE.findall(detail))264                if not re.search(r"logo|favicon|icon|-\d+x\d+\.", u, re.I)]265        if imgs:266            payload["images"] = imgs[:30]267        dsoup = BeautifulSoup(detail, "html.parser")268        og = dsoup.find("meta", attrs={"property": "og:description"})269        desc_el = dsoup.select_one("#property-description-wrap .block-content-wrap")270        if desc_el:271            payload["description"] = desc_el.get_text(" ", strip=True)[:600]272        elif og and og.get("content"):273            payload["description"] = og["content"].strip()[:600]274        labels = [a.get_text(" ", strip=True)275                  for a in dsoup.select(".property-labels-wrap a")]276        labels = list(dict.fromkeys(l for l in labels if l))277        if labels:278            payload["availability"] = ", ".join(labels)[:120].title()279280        # Bloc Détails : type exact (« 1 Bedroom (3 1/2) »), salles de bain,281        # statut (repli si aucune étiquette)282        for li in dsoup.select(".detail-wrap li"):283            txt = li.get_text(" ", strip=True)284            low = txt.lower()285            if low.startswith("property type"):286                ut = _unit_type(txt, "")287                if ut:288                    payload["unit_type"] = ut289            elif low.startswith("bathroom"):290                m = re.search(r"[\d.]+", txt)291                if m:292                    payload.setdefault("amenities", []).append(293                        f"{m.group(0)} Bathroom(s)")294            elif low.startswith("property status") and not labels:295                status = txt.split(None, 2)[-1] if len(txt.split()) > 2 else ""296                if status:297                    payload["availability"] = status.title()298299        # Caractéristiques complètes (Features : Elevator, Heating, Hot300        # Water, Laundry Room, Parking…) — plus riches que la carte liste301        feats = [li.get_text(" ", strip=True)302                 for li in dsoup.select(".property-features-wrap li")]303        feats = [f for f in dict.fromkeys(feats) if f][:25]304        if feats:305            payload["amenities"] = payload.get("amenities", []) + feats306307        # Bloc Adresse : « City/ Ville: Montreal, Plateau Mont-Royal »308        for li in dsoup.select(".property-address-wrap li"):309            txt = li.get_text(" ", strip=True)310            m = re.match(r"(?:City|Ville)[^:]*:\s*(.+)$", txt, re.I)311            if m:312                parts = [p.strip() for p in m.group(1).split(",")]313                if len(parts) >= 2 and parts[1]:314                    payload["sector"] = parts[1]315                break316        return payload317318    # -- parsing d'une carte ---------------------------------------------------319    def _parse_card(self, it) -> Listing | None:320        a = it.select_one('a[href*="/property/"]')321        if not a:322            return None323        url = a["href"].split("?")[0]324        m = re.search(r"/property/([a-z0-9\-]+)/?$", url)325        if not m:326            return None327        slug = m.group(1)328        lid = it.get("data-listid") or ""329        if not lid:330            el = it.select_one("[data-listid]")331            lid = el.get("data-listid") if el else ""332333        title_el = it.select_one(".item-title")334        addr_el = it.select_one(".item-address")335        price_el = it.select_one(".item-price")336        title = title_el.get_text(" ", strip=True) if title_el else slug337        address = addr_el.get_text(" ", strip=True) if addr_el else ""338        price_label = price_el.get_text(" ", strip=True) if price_el else ""339340        if re.search(r"parking|stationnement|commercial|garage", title, re.I):341            return None342343        beds = baths = ""344        amenities: list[str] = []345        for li in it.select(".item-amenities li"):346            txt = li.get_text(" ", strip=True)347            if re.match(r"bed", txt, re.I):348                beds = txt349            elif re.match(r"bath", txt, re.I):350                baths = txt351            elif txt:352                amenities.append(txt)353354        # « 3605 Rue Saint-Urbain, Montréal, QC, Canada » -> secteur/ville.355        # NB : « Mont-Royal » dans un titre désigne l'avenue/le Plateau, pas VMR ;356        # on ne détecte les villes défusionnées que dans l'adresse (+ Westmount/357        # Hampstead dans le titre, non ambigus).358        sector, city = "", "Montréal"359        parts = [p.strip() for p in address.split(",")]360        locality = parts[1] if len(parts) >= 2 else ""361        city = _INDEPENDENT_CITIES.get(locality.lower(), "")362        if not city:363            for key in ("westmount", "hampstead"):364                if key in f"{address} {title}".lower():365                    city = _INDEPENDENT_CITIES[key]366                    break367        if not city:368            city = "Montréal"369            if (locality and not locality.lower().startswith(("montr", "qc"))370                    and not re.search(r"\d", locality)):371                sector = locality372373        # secteur depuis le titre si absent (quartiers connus de Cromwell)374        if city == "Montréal" and not sector:375            m2 = re.search(r"(Plateau(?:\s+Mont-Royal)?|Outremont|Downtown|"376                           r"Golden Square Mile|Mile End|C[oô]te-des-Neiges|"377                           r"Snowdon)", title, re.I)378            if m2:379                sector = m2.group(1)380381        images: list[str] = []382        img = it.select_one("img[data-src], img[src^='https']")383        if img:384            src = img.get("data-src") or img.get("src") or ""385            if src.startswith("https"):386                images.append(src)387388        return Listing(389            source=self.source_id,390            external_id=lid or slug,391            url=url,392            title=title,393            address=address,394            sector=sector,395            city=city,396            unit_type=_unit_type(title, beds),397            price=_parse_price_us(price_label),398            price_label=price_label,399            availability="",400            amenities=amenities,401            images=images,402        )403
Files main
Menu

Theme