SPB Git

Repository Public

zumper.py 19.1 KB 440 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/zumper.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#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/zumper.py : Zumper (zumper.com) — portail locatif nord-américain,91#   filtré PROVINCE DE QUÉBEC, en DIRECT (aucun proxy payant).92#   API JSON interne (celle du site) :93#     1. GET  /api/t/1/bundle                → cookie `csrftoken` + jeton `csrf`94#     2. POST /api/t/1/pages/listables       → annonces par bbox (en-tête95#        `x-csrftoken`) ; paginé offset/limit, réponse = groupes « immeuble »96#        (fourchettes prix/chambres) et pads individuels, champ `state` filtrable97#     3. GET  /api/t/1/buildings/{id}        → fiche immeuble : description,98#        `floorplan_listings` = TOUTES les unités (prix, chambres, sdb, pi²,99#        disponibilité) — 1 requête par immeuble, mise en cache BD et invalidée100#        par `modified_on` (le champ bouge quand l'inventaire change).101#   Photos : https://img.zumpercdn.com/{media_id}/1280x960 (vérifié 2026-08-18).102#   ⚠️ Le HTML du site est derrière un « Client Challenge » JS, mais l'API103#   répond en direct avec des en-têtes navigateur + le rituel CSRF ci-dessus.104#   Un 429 ponctuel = throttling : une seule reprise après pause, sinon on105#   laisse le disjoncteur d'ingestion faire son travail.106#   ⚠️ PadMapper (padmapper.com) = MÊME compagnie et MÊME API (`/api/t/1/…`,107#   mêmes listing_id — vérifié 100/100 identiques sur Montréal 2026-08-18) :108#   un seul connecteur suffit, `padmapper` reste dans PORTALS (dédup) au cas où.109#   Recherche par bbox métropolitaines (le slug de ville est fragile, ex.110#   « quebec-city-qc » ne matche rien) + filtre state == QC (Ottawa exclu).111# -----------------------------------------------------------------------------112from __future__ import annotations113114import json115import os116import time117118from ..schema import Listing119from .base import BaseConnector120121BASE = "https://www.zumper.com"122BUNDLE_URL = f"{BASE}/api/t/1/bundle"123LISTABLES_URL = f"{BASE}/api/t/1/pages/listables"124BUILDING_URL = f"{BASE}/api/t/1/buildings/{{}}"125LISTING_URL = f"{BASE}/api/t/1/listings/{{}}"126IMG_URL = "https://img.zumpercdn.com/{}/1280x960"127128# bbox des régions QC couvertes : nom -> (minLat, maxLat, minLng, maxLng)129# surchargeable : LOUKA_ZUMPER_REGIONS="nom:minLat,maxLat,minLng,maxLng;…"130_DEFAULT_REGIONS = {131    "montreal":       (45.30, 45.80, -74.10, -73.20),   # inclut Laval/Longueuil132    "quebec-levis":   (46.65, 47.00, -71.55, -71.00),133    "gatineau":       (45.35, 45.75, -76.10, -75.40),   # state==QC exclut Ottawa134    "sherbrooke":     (45.25, 45.55, -72.10, -71.70),135    "trois-rivieres": (46.25, 46.50, -72.75, -72.40),136    "saguenay":       (48.30, 48.55, -71.35, -70.90),137    "drummondville":  (45.80, 45.95, -72.60, -72.40),138    "granby-stjean":  (45.20, 45.45, -73.35, -72.60),139}140141142def _regions() -> dict[str, tuple[float, float, float, float]]:143    raw = os.environ.get("LOUKA_ZUMPER_REGIONS", "")144    if not raw.strip():145        return _DEFAULT_REGIONS146    out = {}147    for part in raw.split(";"):148        if ":" not in part:149            continue150        name, coords = part.split(":", 1)151        try:152            a, b, c, d = (float(x) for x in coords.split(","))153            out[name.strip()] = (a, b, c, d)154        except ValueError:155            continue156    return out or _DEFAULT_REGIONS157158159PAGE_SIZE = int(os.environ.get("LOUKA_ZUMPER_PAGE_SIZE", "100"))160MAX_PER_REGION = int(os.environ.get("LOUKA_ZUMPER_MAX_PER_REGION", "1500"))161# budget de fiches immeuble (vraies requêtes) par synchronisation — le cache BD162# (clé modified_on) absorbe l'essentiel après le premier passage163DETAIL_LIMIT = int(os.environ.get("LOUKA_ZUMPER_DETAIL_LIMIT", "150"))164165166def _unit_type_from_bedrooms(bedrooms) -> str:167    if bedrooms is None:168        return ""169    try:170        n = int(float(bedrooms))171    except (TypeError, ValueError):172        return ""173    if n <= 0:174        return "Studio"175    pieces = n + 2                      # convention QC : n ch. -> (n+2)½176    return "6½+" if pieces >= 6 else f"{pieces}½"177178179class ZumperConnector(BaseConnector):180    source_id = "zumper"181    request_delay = 1.2182183    def __init__(self) -> None:184        super().__init__()185        self._csrf = ""186        self.session.headers.update({187            "Accept": "application/json",188            "Origin": BASE,189            "Referer": f"{BASE}/apartments-for-rent/montreal-qc",190        })191192    # -- rituel CSRF -----------------------------------------------------------193    def _bootstrap(self) -> None:194        data = self.get(BUNDLE_URL).json()195        self._csrf = data.get("csrf") or ""196        if not self._csrf:197            raise RuntimeError("zumper: jeton csrf absent du bundle")198199    def _api(self, method: str, url: str, payload: dict | None = None) -> dict:200        """Appel API avec en-tête CSRF + une reprise sur 429/403 (rebootstrap)."""201        if not self._csrf:202            self._bootstrap()203        headers = {"x-csrftoken": self._csrf,204                   "content-type": "application/json"}205        for attempt in (1, 2):206            try:207                if method == "POST":208                    resp = self.post(url, data=json.dumps(payload or {}),209                                     headers=headers)210                else:211                    resp = self.get(url, headers=headers)212                return resp.json()213            except Exception as exc:214                code = getattr(getattr(exc, "response", None),215                               "status_code", None)216                if attempt == 1 and code in (403, 429):217                    time.sleep(30 if code == 429 else 3)218                    self._bootstrap()219                    headers["x-csrftoken"] = self._csrf220                    continue221                raise222        return {}223224    # -- collecte --------------------------------------------------------------225    def fetch(self) -> list[Listing]:226        rows: dict[int, dict] = {}227        for name, (min_lat, max_lat, min_lng, max_lng) in _regions().items():228            offset = 0229            while offset < MAX_PER_REGION:230                data = self._api("POST", LISTABLES_URL, {231                    "external": True, "longTerm": True, "shortTerm": False,232                    "minPrice": 0, "transits": {},233                    "minLat": min_lat, "maxLat": max_lat,234                    "minLng": min_lng, "maxLng": max_lng,235                    "limit": PAGE_SIZE, "offset": offset,236                    "matching": True, "excludeGroupIds": [],237                    "ignorePopular": True, "descriptionLength": 0,238                })239                batch = data.get("listables") or []240                for row in batch:241                    lid = row.get("listing_id")242                    if lid and row.get("state") == "QC":243                        rows.setdefault(int(lid), row)244                total = data.get("matching") or 0245                offset += PAGE_SIZE246                if not batch or offset >= total:247                    break248249        listings: dict[str, Listing] = {}250        budget = DETAIL_LIMIT251        for row in rows.values():252            multi = (row.get("floorplan_count") or 1) > 1 or (253                row.get("min_price") != row.get("max_price"))254            building_id = row.get("building_id")255            expanded = False256            payload = None257            # fiche immeuble même pour les rangées à unité unique : c'est la258            # SEULE source de description (listables ne renvoie jamais259            # short_description, peu importe descriptionLength — testé260            # 2026-08-18) ; cache BD (clé modified_on) + budget partagés261            if building_id:262                payload, budget = self._building_units(row, budget)263            if multi and payload:264                for unit in payload.get("floorplans", []):265                    lst = self._unit_listing(row, unit, payload)266                    if lst and lst.uid not in listings:267                        listings[lst.uid] = lst268                        expanded = True269            if not expanded:270                desc = (payload or {}).get("description") or ""271                if not desc and not row.get("short_description"):272                    # pad sans immeuble (building_id null) : la description273                    # vit sur /api/t/1/listings/{id} (fiche du pad)274                    pad, budget = self._pad_detail(row, budget)275                    desc = (pad or {}).get("description") or ""276                lst = self._row_listing(row, desc)277                if lst and lst.uid not in listings:278                    listings[lst.uid] = lst279        return list(listings.values())280281    # -- fiche pad (cache BD, clé modified_on) ----------------------------------282    def _pad_detail(self, row: dict, budget: int) -> tuple[dict | None, int]:283        """Fiche /api/t/1/listings/{id} d'un pad individuel : description284        longue (1 000-2 500 caractères). Même cache/budget que les immeubles."""285        lid = row.get("listing_id")286        if not lid:287            return None, budget288        key = f"m{row.get('modified_on') or 0}"289        from .. import db290        if self._detail_con is None:291            self._detail_con = db.connect()292        cached = db.get_cached_detail(self._detail_con, self.source_id,293                                      f"p{lid}", key)294        if cached is not None:295            return cached, budget296        if budget <= 0:297            return None, budget298        budget -= 1299        try:300            data = self._api("GET", LISTING_URL.format(lid))301        except Exception:302            return None, budget303        payload = {"description": (data.get("description") or "")[:2500]}304        db.put_cached_detail(self._detail_con, self.source_id,305                             f"p{lid}", key, payload)306        return payload, budget307308    # -- fiche immeuble (cache BD, clé modified_on) -----------------------------309    def _building_units(self, row: dict, budget: int) -> tuple[dict | None, int]:310        building_id = row["building_id"]311        key = f"m{row.get('modified_on') or 0}"312        from .. import db313        if self._detail_con is None:314            self._detail_con = db.connect()315        cached = db.get_cached_detail(self._detail_con, self.source_id,316                                      f"b{building_id}", key)317        if cached is not None:318            return cached, budget319        if budget <= 0:320            return None, budget321        budget -= 1322        try:323            data = self._api("GET", BUILDING_URL.format(building_id))324        except Exception:325            return None, budget326        fps = []327        for fp in data.get("floorplan_listings") or []:328            if fp.get("listing_status") not in (None, 1):329                continue330            fps.append({331                "listing_id": fp.get("listing_id"),332                "title": fp.get("title") or "",333                "price": fp.get("min_price") or fp.get("price"),334                "max_price": fp.get("max_price"),335                "bedrooms": fp.get("bedrooms"),336                "bathrooms": fp.get("bathrooms"),337                "half_bathrooms": fp.get("half_bathrooms"),338                "square_feet": fp.get("square_feet"),339                "date_available": fp.get("date_available"),340                "image_ids": [m.get("media_id") for m in fp.get("media") or []341                              if m.get("media_type") == 1][:8],342            })343        payload = {"floorplans": fps,344                   "description": (data.get("description") or "")[:2000],345                   "year_built": data.get("year_built"),346                   "homepage": data.get("homepage")}347        db.put_cached_detail(self._detail_con, self.source_id,348                             f"b{building_id}", key, payload)349        return payload, budget350351    # -- constructions ----------------------------------------------------------352    def _common(self, row: dict) -> dict:353        amen = list(dict.fromkeys((row.get("amenity_tags") or []) +354                                  (row.get("building_amenity_tags") or [])))355        details = {k: row[k] for k in ("neighborhood_name", "brokerage_name",356                                       "building_name", "zipcode")357                   if row.get(k)}358        return {"amenities": amen[:40], "details": details}359360    def _url(self, row: dict) -> str:361        path = row.get("url") or ""362        if path.startswith("/"):363            return f"{BASE}{path}"364        if row.get("pb_url"):365            return f"{BASE}/apartment-buildings/p{row.get('pb_id')}/{row['pb_url']}"366        return f"{BASE}/apartments-for-rent/montreal-qc"367368    def _unit_listing(self, row: dict, unit: dict, payload: dict) -> Listing | None:369        price = unit.get("price")370        if not price or price < 200:371            return None372        ext_id = str(unit.get("listing_id") or373                     f"{row['building_id']}-{unit.get('title', '')}")374        beds = unit.get("bedrooms")375        baths = unit.get("bathrooms")376        if baths is not None and unit.get("half_bathrooms"):377            baths = float(baths) + 0.5 * float(unit["half_bathrooms"])378        common = self._common(row)379        imgs = [IMG_URL.format(m) for m in unit.get("image_ids") or []] or \380               [IMG_URL.format(m) for m in (row.get("image_ids") or [])[:8]]381        avail = unit.get("date_available") or ""382        return Listing(383            source=self.source_id,384            external_id=ext_id,385            url=self._url(row),386            title=(f"{row.get('building_name') or row.get('address', '')} — "387                   f"{unit.get('title') or ''}").strip(" —"),388            address=row.get("address", ""),389            sector=row.get("neighborhood_name") or "",390            city=row.get("city", ""),391            unit_type=_unit_type_from_bedrooms(beds),392            bedrooms=float(beds) if beds is not None else None,393            bathrooms=float(baths) if baths is not None else None,394            price=float(price),395            price_label=f"{price:,.0f} $/mois".replace(",", " "),396            availability=str(avail),397            area_sqft=(float(unit["square_feet"])398                       if unit.get("square_feet") else None),399            description=payload.get("description") or "",400            amenities=common["amenities"],401            details=common["details"],402            images=imgs,403            lat=row.get("lat"),404            lng=row.get("lng"),405        )406407    def _row_listing(self, row: dict, description: str = "") -> Listing | None:408        price = row.get("min_price")409        if not price or price < 200:410            return None411        mn, mx = row.get("min_price"), row.get("max_price")412        from_price = bool(mx and mx != mn)413        beds = row.get("min_bedrooms")414        baths = row.get("min_bathrooms")415        common = self._common(row)416        label = (f"à partir de {price:,.0f} $/mois" if from_price417                 else f"{price:,.0f} $/mois").replace(",", " ")418        return Listing(419            source=self.source_id,420            external_id=str(row["listing_id"]),421            url=self._url(row),422            title=(row.get("building_name") or row.get("title")423                   or row.get("address", "")),424            address=row.get("address", ""),425            sector=row.get("neighborhood_name") or "",426            city=row.get("city", ""),427            unit_type=_unit_type_from_bedrooms(beds),428            bedrooms=float(beds) if beds is not None else None,429            bathrooms=float(baths) if baths is not None else None,430            price=float(price),431            price_label=label,432            availability=str(row.get("date_available") or ""),433            description=row.get("short_description") or description,434            amenities=common["amenities"],435            details=common["details"],436            images=[IMG_URL.format(m) for m in (row.get("image_ids") or [])[:8]],437            lat=row.get("lat"),438            lng=row.get("lng"),439        )440
Files main
Menu

Theme