SPB Git

Repository Public

metcap.py 20.1 KB 484 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/metcap.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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/metcap.py : connecteur MetCap Living (metcap.com)91#   Site WordPress rendu serveur. La page /province/quebec liste les villes QC92#   (province=115) ; chaque page « province-search-results » liste les93#   immeubles (avec lat/lng dans l'attribut onclick=centerMap) et leurs types94#   d'unités (« Montreal 2 Bedrooms from $1,819 »). Les fiches /apartment/...95#   donnent le détail structuré : tableau « Suite Details » (statut, lits,96#   sdb, pi²), listes « Building Amenities », « Rent Includes »,97#   « Pet Friendly », contact du bureau de location, description bilingue et98#   photos d'unité ; les fiches /property/... la galerie photo de l'immeuble.99#   Fiches visitées via self.detail(...) (cache BD). Gestionnaire pancanadien :100#   seules les villes du Grand Montréal sont couvertes.101#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,102#   la page /province/ontario (province=113) est aussi balayée pour les villes103#   Toronto/GTA + Barrie (province="ON", adresse suffixée « ON », compteur104#   d'unités séparé — le parc QC n'est jamais rogné). Sans la variable,105#   comportement strictement identique (QC seulement).106# -----------------------------------------------------------------------------107from __future__ import annotations108109import hashlib110import os111import re112import urllib.parse113114from bs4 import BeautifulSoup115116from ..schema import Listing, parse_price, strip_accents117from .base import BaseConnector118119# Expansion Ontario 2026-08 — gate d'environnement (défaut : QC seulement)120_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"121122BASE = "https://www.metcap.com"123QC_PROVINCE_URL = f"{BASE}/province/quebec?lang=en"124ON_PROVINCE_URL = f"{BASE}/province/ontario?lang=en"125126# Villes admissibles (Grand Montréal), clés sans accents/minuscules127_GM_CITIES = {128    "montreal": ("Montréal", ""),129    "saint laurent": ("Montréal", "Saint-Laurent"),130    "st laurent": ("Montréal", "Saint-Laurent"),131    "saint lambert": ("Saint-Lambert", ""),132    "st lambert": ("Saint-Lambert", ""),133    "verdun": ("Montréal", "Verdun"),134    "lasalle": ("Montréal", "LaSalle"),135    "laval": ("Laval", ""),136    "longueuil": ("Longueuil", ""),137    "brossard": ("Brossard", ""),138    "pointe-claire": ("Pointe-Claire", ""),139    "dorval": ("Dorval", ""),140}141142# Villes admissibles Ontario (Toronto/GTA + Barrie) — expansion 2026-08,143# consommées seulement sous LOUKA_ONTARIO=1. Clés sans accents/minuscules.144_ON_CITIES = {145    "toronto": ("Toronto", ""),146    "north york": ("Toronto", "North York"),147    "scarborough": ("Toronto", "Scarborough"),148    "etobicoke": ("Toronto", "Etobicoke"),149    "east york": ("Toronto", "East York"),150    "thornhill": ("Thornhill", ""),151    "mississauga": ("Mississauga", ""),152    "brampton": ("Brampton", ""),153    "burlington": ("Burlington", ""),154    "oshawa": ("Oshawa", ""),155    "barrie": ("Barrie", ""),156}157158_TYPE_MAP = [159    (re.compile(r"bachelor|studio", re.I), "Studio"),160    (re.compile(r"1\s*bed", re.I), "3½"),161    (re.compile(r"2\s*bed", re.I), "4½"),162    (re.compile(r"3\s*bed", re.I), "5½"),163    (re.compile(r"4\s*bed", re.I), "6½"),164]165_SKIP_IMG = re.compile(r"logo|icon|favicon|header|/map/|walk\.sc|sharethis",166                       re.I)167_LATLNG_RE = re.compile(r"\{\s*lat:\s*(-?[\d.]+)\s*,\s*"168                        r"lon:\s*(-?[\d.]+)\s*\}")169_PHONE_RE = re.compile(r"\(?\b([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-](\d{4})\b")170_EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b")171172# « Rent Includes » (texte anglais structuré) -> clés inclusions Lou-Ka173_INCLUDES_MAP = [174    (re.compile(r"heat", re.I), "heating"),175    (re.compile(r"hydro|electric", re.I), "electricity"),176    (re.compile(r"hot\s*water", re.I), "hot_water"),177    (re.compile(r"internet|wi-?fi", re.I), "internet"),178    (re.compile(r"cable", re.I), "cable"),179]180181182class _CapAtteint(Exception):183    """Plafond de requêtes détail atteint pour cette synchronisation."""184185186class MetcapConnector(BaseConnector):187    source_id = "metcap"188    request_delay = 0.6189    max_units = 60           # garde-fou fiches unités190    max_images = 25191    max_real_details = 150   # vraies requêtes détail par sync (hits cache exclus)192193    def fetch(self) -> list[Listing]:194        self._real_details = 0195        listings: list[Listing] = []196        # Québec (comportement historique, inchangé)197        self._scan_province(QC_PROVINCE_URL, "115", _GM_CITIES, "QC",198                            listings)199        # Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO (compteur d'unités200        # séparé : le parc QC garde tout son budget max_units)201        if _ONTARIO:202            try:203                self._scan_province(ON_PROVINCE_URL, "113", _ON_CITIES, "ON",204                                    listings)205            except Exception:206                pass    # l'échec ON ne doit jamais faire tomber la synchro QC207        return listings208209    def _scan_province(self, province_url: str, province_id: str,210                       cities_map: dict, province: str,211                       listings: list[Listing]) -> None:212        """Balaye une page province (liens de villes -> pages résultats)."""213        html = self.get(province_url).text214        # Liens de villes : /province-search-results?...province=<id>&city=X215        cities = []216        for href in re.findall(r'href="(/province-search-results\?[^"]+)"',217                               html):218            q = urllib.parse.parse_qs(urllib.parse.urlparse(219                href.replace("&amp;", "&")).query)220            if (q.get("province") or [""])[0] != province_id:221                continue222            city = (q.get("city") or [""])[0]223            if city and city not in cities:224                cities.append(city)225226        count = 0227        for city_name in cities:228            key = strip_accents(city_name.lower()).replace(".", "").strip()229            if key not in cities_map:230                continue    # hors région couverte (garde REIT pancanadien)231            city, sector = cities_map[key]232            try:233                page = self.get(234                    f"{BASE}/province-search-results?lang=en"235                    f"&province={province_id}"236                    f"&city={urllib.parse.quote(city_name)}").text237            except Exception:238                continue239            soup = BeautifulSoup(page, "html.parser")240            for item in soup.select(".province-results__item"):241                try:242                    block = item.select_one(".province-results__content")243                    if not block:244                        continue245                    h2a = block.select_one("h2 a[href^='/property/']")246                    if not h2a:247                        continue248                    address = h2a.get_text(" ", strip=True)249                    prop_path = h2a.get("href", "").split("?")[0]250                    # lat/lng de l'immeuble : onclick="centerMap(..., {lat, lon})"251                    lat = lng = None252                    lm = _LATLNG_RE.search(item.get("onclick", "") or "")253                    if lm:254                        lat, lng = float(lm.group(1)), float(lm.group(2))255                    spans = block.select("p span.d-block")256                    prop_name = ""257                    if spans and not spans[0].find("a"):258                        prop_name = spans[0].get_text(" ", strip=True)259                    for a in block.select("a[href^='/apartment/']"):260                        if count >= self.max_units:261                            break262                        count += 1263                        text = a.get_text(" ", strip=True)264                        lst = self._unit_listing(265                            a.get("href", ""), text, address, prop_name,266                            prop_path, city, sector, lat, lng,267                            province=province)268                        if lst:269                            listings.append(lst)270                except Exception:271                    continue272273    # -- pages détail (via cache BD self.detail) -------------------------------274    def _gallery(self, prop_path: str) -> list[str]:275        """Galerie photo de la fiche immeuble (partagée entre unités)."""276        def _fetch() -> dict:277            if self._real_details >= self.max_real_details:278                raise _CapAtteint()279            self._real_details += 1280            imgs: list[str] = []281            ph = self.get(f"{BASE}{prop_path}?lang=en").text282            for u in re.findall(283                    r'https://www\.metcap\.com/wp-content/uploads/'284                    r'[^"\'\s\)]+\.(?:jpg|jpeg|png|webp)', ph):285                if not _SKIP_IMG.search(u) and u not in imgs:286                    imgs.append(u)287            return {"images": imgs[: self.max_images]}288289        try:290            return self.detail(f"property:{prop_path}", prop_path,291                               _fetch).get("images") or []292        except Exception:293            return []294295    def _unit_detail(self, slug: str, url: str, card_key: str) -> dict:296        """Fiche unité : tableau Suite Details, listes sidebar, contact,297        description, intersection et photos d'unité."""298        def _fetch() -> dict:299            if self._real_details >= self.max_real_details:300                raise _CapAtteint()301            self._real_details += 1302            html = self.get(url).text303            soup = BeautifulSoup(html, "html.parser")304            out: dict = {}305306            # Tableau « Suite Details » : Price/Status/Beds/Baths/Sq. Ft307            suites = []308            table = soup.select_one("table.table-listing")309            if table:310                for tr in table.select("tbody tr"):311                    row = {td.get("data-title", "").strip():312                           td.get_text(" ", strip=True)313                           for td in tr.select("td") if td.get("data-title")}314                    if row:315                        suites.append(row)316            out["suites"] = suites317318            # Listes structurées de la barre latérale319            def _ul(titre: str) -> list[str]:320                h = soup.find("h2", string=re.compile(321                    rf"^\s*{titre}\s*$", re.I))322                ul = h.find_next_sibling("ul") if h else None323                return ([li.get_text(" ", strip=True) for li in324                         ul.select("li")] if ul else [])325326            out["building_amenities"] = _ul("Building Amenities")327            out["rent_includes"] = _ul("Rent Includes")328            out["pet_friendly"] = _ul("Pet Friendly")329            out["local_amenities"] = _ul("Local Amenities")330331            # Contact du bureau de location332            contact = soup.select_one(".listing-contact")333            if contact:334                ctxt = contact.get_text(" ", strip=True)335                pm = _PHONE_RE.search(ctxt)336                if pm:337                    out["phone"] = f"{pm.group(1)}-{pm.group(2)}-{pm.group(3)}"338                em = _EMAIL_RE.search(ctxt)339                if em:340                    out["email"] = em.group(0)341342            # Description (partie anglaise, avant l'avis de non-responsabilité)343            dm = re.search(r"<h2>Description</h2>(.*?)(?:<h2|<hr)", html, re.S)344            if dm:345                dtxt = re.sub(r"<[^>]+>", " ", dm.group(1))346                dtxt = re.sub(r"\s+", " ", dtxt).strip()347                dtxt = re.split(r"The safest way|Disclaimer", dtxt)[0]348                out["description"] = dtxt.strip()[:600]349350            # Intersection (en-tête de fiche)351            txt = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))352            im = re.search(r"Intersection:\s*([^|]{3,60}?)\s{0,2}Suite", txt)353            if im:354                out["intersection"] = im.group(1).strip()355356            # Photos de l'unité (carrousel span data-bg)357            imgs = re.findall(358                r'data-bg="(https://www\.metcap\.com/wp-content/uploads/'359                r'[^"]+\.(?:jpg|jpeg|png|webp))"', html)360            out["images"] = [u for u in dict.fromkeys(imgs)361                             if not _SKIP_IMG.search(u)][: self.max_images]362            return out363364        try:365            return self.detail(slug, card_key, _fetch)366        except Exception:367            return {}368369    # -- construction d'une annonce --------------------------------------------370    def _unit_listing(self, href: str, card_text: str, address: str,371                      prop_name: str, prop_path: str, city: str, sector: str,372                      lat: float | None, lng: float | None,373                      province: str = "QC") -> Listing | None:374        path = href.split("?")[0]375        slug = path.rstrip("/").split("/")[-1]376        if not slug:377            return None378        url = f"{BASE}{path}?lang=en"379380        unit_type = ""381        for rx, ut in _TYPE_MAP:382            if rx.search(card_text):383                unit_type = ut384                break385        price = parse_price(386            card_text.replace("from $", "").replace(",", "") + " $")387        price_label = ""388        pm = re.search(r'from \$[\d,.]+', card_text)389        if pm:390            price_label = pm.group(0).replace("from", "À partir de") + " /mois"391392        # Fiche unité (cache BD, clé = contenu de la carte liste)393        card_key = hashlib.sha1(394            f"{card_text}|{address}".encode("utf-8")).hexdigest()[:16]395        det = self._unit_detail(slug, url, card_key)396397        # Tableau Suite Details : statut, superficie (structurés à la source)398        availability = ""399        area_sqft: float | None = None400        bits: list[str] = []401        suites = det.get("suites") or []402        row = next((r for r in suites403                    if (r.get("Status") or "").lower() == "available"),404                   suites[0] if suites else None)405        if row:406            status = row.get("Status") or ""407            availability = {"Available": "Disponible",408                            "Waiting List": "Liste d'attente",409                            "Rented": "Loué"}.get(status, status)410            sq = re.sub(r"[^\d.]", "", row.get("Sq. Ft") or "")411            try:412                v = float(sq)413                if 80 <= v <= 20000:414                    area_sqft = v415            except ValueError:416                pass417            beds, baths = row.get("Beds") or "", row.get("Baths") or ""418            if beds or baths:419                bits.append(" — ".join(x for x in [420                    f"{beds} ch." if beds else "",421                    f"{baths} sdb" if baths else ""] if x))422        if det.get("intersection") and not sector:423            bits.append(f"Intersection : {det['intersection']}")424425        # Commodités brutes (immeuble + inclusions), fidèles à la source426        amenities = list(dict.fromkeys(427            (det.get("building_amenities") or []) +428            (det.get("rent_includes") or [])))[:25]429430        # Inclusions structurées (« Rent Includes ») et animaux (« Pet Friendly »)431        details: dict = {}432        inclusions: dict = {}433        for item in det.get("rent_includes") or []:434            for rx, cle in _INCLUDES_MAP:435                if rx.search(item):436                    inclusions[cle] = True437        if inclusions:438            details["inclusions"] = inclusions439        pets = None440        pf = " ".join(det.get("pet_friendly") or []).strip().lower()441        if pf.startswith("yes"):442            pets = "oui"443        elif pf.startswith("no"):444            pets = "non"445        contact = {k: det[k] for k in ("phone", "email") if det.get(k)}446        if contact:447            details["contact"] = contact448449        # Photos : unité d'abord, sinon galerie de l'immeuble450        images = det.get("images") or []451        if not images:452            images = self._gallery(prop_path)453454        desc = det.get("description") or ""455        title_type = re.sub(r"\s*from \$[\d,.].*$", "", card_text).strip()456        title = (f"{prop_name} — {title_type}" if prop_name457                 else f"{address} — {title_type}")458        # Ontario : adresse suffixée « ON » (standard expansion 2026-08)459        if province == "ON" and address \460                and not re.search(r",\s*ON\b", address):461            address = f"{address}, ON"462        return Listing(463            source=self.source_id,464            external_id=slug,465            url=url,466            title=title,467            address=address,468            province=province,469            sector=sector,470            city=city,471            unit_type=unit_type,472            price=price,473            price_label=price_label,474            availability=availability,475            area_sqft=area_sqft,476            pets=pets,477            description=" — ".join([desc] + bits if desc else bits)[:600],478            amenities=amenities,479            details=details,480            images=images,481            lat=lat,482            lng=lng,483        )484
Files main
Menu

Theme