SPB Git

Repository Public

voltige.py 19.2 KB 450 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/voltige.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-10-2214#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/voltige.py : Le Voltige (voltigemtl.ca) — complexe locatif DevImmo91#   à Ahuntsic (Montréal), 4 immeubles : Hélia, Belvédère, Aria, Panora.92#   Techno : widget Livya (ex-Realvuu), client « society-dev-immo », projet93#   « voltige ». Depuis la refonte Livya du 2026-10-22, le flux RSC de la page94#   plans ne contient plus les unités ET le client n'a PAS de module inventaire95#   SSR (unitSelectorSummaries: []) : les unités ne sont chargées QUE côté96#   client (api.realvuu.com, robots.txt interdit — on ne l'appelle pas).97#   On rend donc la page plans en navigateur (Scrapfly render_js, patron98#   trudel/quartier_sila) : la vue TABLEAU du DOM rendu (colonnes Nom/Étage/99#   Chambres/Salles de bain/Superficie/Prix/Statut) est la source de vérité ;100#   la grille de cartes fournit la photo de chaque unité. ⚠️ Les loyers ne101#   sont plus affichés nulle part dans la nouvelle UI (colonne Prix = « — »,102#   panneau détail sans prix malgré showUnitPriceWeb:true) — la cellule Prix103#   est parsée au cas où ils reviendraient, sinon price=None.104#   Mapping unité→immeuble : les « frames » du plan interactif, toujours SSR105#   dans le flux RSC de la même page — frame « Vue du bâtiment X »106#   (linkType=BUILDING) → polygones FLOOR (linkedFrameId → frame d'étage) →107#   polygones UNIT (linkId = unitId). Recoupé 23/23 avec l'historique au108#   2026-10-22 ; adresse/GPS repris de l'objet immeuble du RSC.109#   external_id = UUID unitId Livya (data-unit-id), identique à l'historique —110#   zéro churn. Type d'unité dérivé des chambres (recoupé avec l'historique :111#   — → Studio, 1 → 3½, 2 → 4½, 3 → 5½).112# -----------------------------------------------------------------------------113from __future__ import annotations114115import html as _html116import json117import re118import time119from urllib.parse import unquote120121from ..schema import Listing122from .base import BaseConnector123124SITE_URL = "https://voltigemtl.ca/plans/"125LIVYA_BASE = "https://app.livya.com"126SECTOR = "Ahuntsic"127FALLBACK_ADDRESS = "2200 Rue Sauvé Ouest"   # adresse du projet (RSC)128129# valeurs observées 2026-08-25, revérifiées 2026-10-22 (repli si la page WP130# ne les expose plus)131DEFAULT_CLIENT = "society-dev-immo"132DEFAULT_PROJECT = "voltige"133DEFAULT_ENTITY = "2aad7013-9b35-4b56-a72f-8dbf9d063678"134135_ATTR_RE = {k: re.compile(rf'data-{k}="([^"]+)"')136            for k in ("client", "project", "entity")}137138# fragments RSC de Next.js : self.__next_f.push([1,"…"])139_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')140141# vue tableau du DOM rendu (complète) + cartes de la grille (photos)142_ROW_RE = re.compile(r'<tr data-unit-id="([0-9a-f-]{36})"')143_TH_RE = re.compile(r'<th[^>]*>(.*?)</th>', re.S)144_TD_RE = re.compile(r'<td[^>]*>(.*?)</td>', re.S)145_CARD_RE = re.compile(r'<div[^>]*data-unit-id="([0-9a-f-]{36})"')146_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')147_COUNT_RE = re.compile(r'(\d+)\s*résultats?')148149_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,150         "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,151         "novembre": 11, "décembre": 12}152_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)153154# scrolle tous les conteneurs à overflow interne (grille lazy-loadée : le155# scroll de la fenêtre ne charge rien — auto_scroll Scrapfly inopérant)156_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"157              "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")158159160def _cell_text(cell: str) -> str:161    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", cell))).strip()162163164def _cell_num(s: str) -> float | None:165    digits = re.sub(r"[^\d.]", "", s or "")166    try:167        return float(digits) if digits else None168    except ValueError:169        return None170171172def _unit_type(beds: float | None) -> str:173    """Type dérivé des chambres (recoupé avec l'historique JSON) :174    — -> Studio, 1 -> 3½, 2 -> 4½, 3 -> 5½."""175    if beds is None or beds < 1:176        return "Studio"177    return f"{int(beds) + 2}½"178179180class VoltigeConnector(BaseConnector):181    """Le Voltige (Ahuntsic, Montréal) — vue tableau rendue du widget Livya."""182183    source_id = "voltige"184    request_delay = 1.0185    use_detail_cache = False186    max_units = 400                     # garde-fou (601 unités au portefeuille)187188    def _embed_params(self) -> tuple[str, str, str]:189        try:190            h = self.get(SITE_URL).text191            vals = {k: (rx.search(h).group(1) if rx.search(h) else "")192                    for k, rx in _ATTR_RE.items()}193            if all(vals.values()):194                return vals["client"], vals["project"], vals["entity"]195        except Exception:  # noqa: BLE001 — repli sur les valeurs connues196            pass197        return DEFAULT_CLIENT, DEFAULT_PROJECT, DEFAULT_ENTITY198199    # -- rendu navigateur -----------------------------------------------------200    def get_rendered(self, url: str, wait_ms: int = 0) -> str:201        """HTML rendu Scrapfly, scroll des conteneurs internes (grille202        lazy-loadée). Même nom que le patron trudel pour rester compatible203        avec le record/replay des fixtures — clé de rejeu = URL cible."""204        steps: list[dict] = []205        for _ in range(8):206            steps.append({"execute": {"script": _SCROLL_JS}})207            steps.append({"wait": 1200})208        html = self.get_scrapfly(url, render_js=True, asp=True,209                                 rendering_wait=wait_ms or 4000,210                                 js_scenario=steps)211        if not html:212            raise RuntimeError(f"Scrapfly : rendu vide — {url}")213        return html214215    def _render_ok(self, url: str) -> str:216        """Rendu dont la vue tableau est complète : le compteur « N résultats »217        doit être présent (sinon gabarit changé) et le nombre de lignes218        uniques du tableau doit l'atteindre — erreur franche après 3219        tentatives plutôt qu'un rendu tronqué qui dépublierait des unités."""220        last_err: Exception | None = None221        for attempt in range(3):222            html = self.get_rendered(url, wait_ms=4000)223            m = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))224            if not m:225                last_err = RuntimeError(226                    "app.livya.com (voltige) : compteur « N résultats » absent "227                    f"du rendu — gabarit Livya changé ? ({url})")228            else:229                announced = int(m.group(1))230                uniques = len(set(_ROW_RE.findall(html)))231                if uniques >= announced:232                    return html          # announced == 0 : vrai zéro accepté233                last_err = RuntimeError(234                    f"app.livya.com (voltige) : {uniques} ligne(s) unique(s) "235                    f"pour {announced} annoncées — rendu incomplet ? ({url})")236            if attempt < 2:237                time.sleep(5 * (attempt + 1))238        assert last_err is not None239        raise last_err240241    # -- vue tableau du DOM rendu -> unités ------------------------------------242    @staticmethod243    def _collect(html: str) -> dict[str, dict]:244        """Lignes du tableau (source de vérité) + photos des cartes de grille."""245        thead = re.search(r"<thead.*?</thead>", html, re.S)246        cols: dict[str, int] = {}247        if thead:248            for i, th in enumerate(_TH_RE.findall(thead.group(0))):249                t = _cell_text(th).lower()250                for key, label in (("name", "nom"), ("floor", "étage"),251                                   ("beds", "chambre"), ("baths", "salle"),252                                   ("area", "superficie"), ("price", "prix"),253                                   ("status", "statut")):254                    if t.startswith(label):255                        cols[key] = i256        if "name" not in cols or "status" not in cols:257            raise RuntimeError(258                "app.livya.com (voltige) : en-têtes du tableau introuvables "259                "(Nom/Statut) — gabarit Livya changé ?")260261        units: dict[str, dict] = {}262        rows = list(_ROW_RE.finditer(html))263        for i, m in enumerate(rows):264            end = rows[i + 1].start() if i + 1 < len(rows) else m.start() + 8000265            cells = [_cell_text(c) for c in266                     _TD_RE.findall(html[m.start():min(end, m.start() + 8000)])]267268            def col(key: str) -> str:269                j = cols.get(key)270                return cells[j] if j is not None and j < len(cells) else ""271272            parsed = {273                "number": col("name").lstrip("#") or None,274                "floor": _cell_num(col("floor")),275                "beds": _cell_num(col("beds")),276                "baths": _cell_num(col("baths")),277                "area": _cell_num(col("area")),278                "price": _cell_num(col("price")),279                "status": col("status") or None,280            }281            u = units.setdefault(m.group(1), {})282            for k, v in parsed.items():283                if u.get(k) is None and v is not None:284                    u[k] = v285286        # cartes de la grille : photo du plan/de l'unité type287        cards = [(x.start(), x.group(1)) for x in _CARD_RE.finditer(html)]288        for i, (pos, uid) in enumerate(cards):289            end = cards[i + 1][0] if i + 1 < len(cards) else pos + 9000290            im = _IMG_RE.search(html[pos:min(end, pos + 9000)])291            if im and uid in units and units[uid].get("image") is None:292                units[uid]["image"] = unquote(im.group(1))293        return units294295    # -- flux RSC (toujours SSR) : immeubles + frames du plan interactif --------296    @staticmethod297    def _rsc_blob(html: str) -> str:298        try:299            return "".join(300                json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))301        except Exception:  # noqa: BLE001302            return ""303304    @staticmethod305    def _buildings(blob: str) -> dict[str, dict]:306        """Objets immeuble du RSC : nom, adresse, ville, code postal, GPS."""307        dec = json.JSONDecoder()308        out: dict[str, dict] = {}309        for m in re.finditer(r'\{"buildingId"', blob):310            try:311                obj, _ = dec.raw_decode(blob[m.start():m.start() + 8000])312            except Exception:  # noqa: BLE001313                continue314            bid = obj.get("buildingId")315            if bid and obj.get("name") and bid not in out:316                out[bid] = obj317        return out318319    @staticmethod320    def _unit_buildings(blob: str) -> dict[str, str]:321        """unitId -> buildingId via les frames du plan interactif : frame322        « Vue du bâtiment X » (linkType=BUILDING, linkId=buildingId) →323        polygones FLOOR (linkedFrameId → frame d'étage) → polygones UNIT324        (linkId = unitId). Recoupé 23/23 avec l'historique au 2026-10-22."""325        dec = json.JSONDecoder()326        frames: dict[str, dict] = {}327        for m in re.finditer(r'\{"frameId"', blob):328            try:329                obj, _ = dec.raw_decode(blob[m.start():m.start() + 300000])330            except Exception:  # noqa: BLE001331                continue332            fid = obj.get("frameId")333            if fid and fid not in frames:334                frames[fid] = obj335336        unit2b: dict[str, str] = {}337        for f in frames.values():338            if f.get("linkType") != "BUILDING" or not f.get("linkId"):339                continue340            bid = f["linkId"]341            for p in f.get("polygons") or []:342                if p.get("linkType") != "FLOOR":343                    continue344                floor_frame = frames.get(p.get("linkedFrameId") or "")345                if not floor_frame:346                    continue347                for pu in floor_frame.get("polygons") or []:348                    if pu.get("linkType") == "UNIT" and pu.get("linkId"):349                        unit2b.setdefault(pu["linkId"], bid)350        return unit2b351352    def fetch(self) -> list[Listing]:353        client, project, entity = self._embed_params()354        plans_url = f"{LIVYA_BASE}/fr/{client}/projects/{project}/plans/{entity}"355        html = self._render_ok(plans_url)356        units = self._collect(html)357        cm = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))358        if cm and int(cm.group(1)) and not units:359            raise RuntimeError(360                "app.livya.com (voltige) : aucune ligne d'unité dans le rendu "361                "— gabarit changé ?")362363        blob = self._rsc_blob(html)364        buildings = self._buildings(blob)365        unit2b = self._unit_buildings(blob)366367        listings: list[Listing] = []368        for uid, u in list(units.items())[: self.max_units]:369            if not (u.get("status") or "").startswith("Disponible"):370                continue                 # « Réservé » & cie exclus371            building = buildings.get(unit2b.get(uid) or "") or {}372            listings.append(self._listing(uid, u, building))373        return listings374375    # -- une annonce par unité disponible ---------------------------------------376    def _listing(self, uid: str, u: dict, building: dict) -> Listing:377        num = str(u.get("number") or "").strip()378        bname = (building.get("name") or "").strip()379380        address = (building.get("address") or "").strip() or FALLBACK_ADDRESS381        city = (building.get("city") or "Montréal").strip()382383        price = u.get("price")384        price = float(price) if price and price > 1 else None385386        # « Disponible » ou « Disponible - 1 décembre 2026 » (date française)387        status = (u.get("status") or "").strip()388        availability = "Disponible"389        avail_date = None390        dm = _DATE_FR_RE.search(status)391        if dm and _MOIS.get(dm.group(2).lower()):392            avail_date = (f"{int(dm.group(3)):04d}-"393                          f"{_MOIS[dm.group(2).lower()]:02d}-"394                          f"{int(dm.group(1)):02d}")395            availability = f"Disponible à partir du {avail_date}"396397        beds, baths, area = u.get("beds"), u.get("baths"), u.get("area")398        unit_type = _unit_type(beds)399400        desc: list[str] = []401        if area and area > 0:402            desc.append(f"{int(area)} pi²")403        if beds:404            desc.append(f"{int(beds)} chambre(s)")405        if baths:406            desc.append(f"{int(baths)} salle(s) de bain")407        if bname:408            desc.append(f"Immeuble {bname} — Le Voltige")409410        details: dict = {}411        floor = u.get("floor")412        if floor and floor > 0:413            details["floor"] = int(floor)414        if bname:415            details["building"] = bname416417        images: list[str] = []418        if u.get("image"):419            images.append(u["image"])420421        try:422            lat = float(building["latitude"]) if building.get("latitude") else None423            lng = float(building["longitude"]) if building.get("longitude") else None424        except (TypeError, ValueError):425            lat = lng = None426427        title_bits = [x for x in (bname, f"unité {num}" if num else "") if x]428        return Listing(429            source=self.source_id,430            external_id=uid,                 # UUID Livya : stable, historique431            url=SITE_URL,                    # pas de page publique par unité432            title=("Le Voltige — " + ", ".join(title_bits)).strip(" —,"),433            address=address,434            sector=SECTOR,435            city=city,436            unit_type=unit_type,437            bedrooms=beds if beds and beds > 0 else None,438            bathrooms=baths if baths and baths > 0 else None,439            price=price,440            price_label=f"{price:.0f} $ /mois" if price else "",441            availability=availability,442            availability_date=avail_date,443            area_sqft=area if area and area > 0 else None,444            description=" | ".join(desc),445            details=details,446            images=images[:12],447            lat=lat,448            lng=lng,449        )450
Files main
Menu

Theme