SPB Git

Repository Public

quartier_sila.py 23.8 KB 546 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/quartier_sila.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# 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/quartier_sila.py : connecteur Quartier Sila (silalevis.ca)91#   Complexe de condos locatifs du Groupe Damco / Développement Beaubourg à92#   Saint-Romuald (Lévis) — 4 phases (Guillaume-Couture, J.-B.-Demers,93#   d'Anticosti). Le site WordPress embarque le module de plans Livya94#   (app.livya.com, client « damco », projet « sila ») sur DEUX pages :95#   /condos-locatifs-sila/ (sélecteur des phases 1-3) et /phase4/ (sélecteur96#   couvrant toutes les phases, dont la phase 4 en prélocation).97#   Depuis la refonte Livya du 2026-10-22, le flux RSC des pages plans ne98#   contient plus les unités ET le client damco n'a PAS de module inventaire99#   SSR (unitSelectorSummaries: []) : les unités ne sont chargées QUE côté100#   client (api.realvuu.com, robots.txt interdit — on ne l'appelle pas).101#   On rend donc chaque page plans en navigateur (Scrapfly render_js, patron102#   le_fjord/louis14) : le DOM rendu contient une vue TABLEAU complète103#   (colonnes Nom/Étage/Chambres/Salles de bain/Superficie/Prix/Statut) qui104#   sert de source de vérité, plus une grille de cartes (lazy-loadée, donc105#   partielle) dont on tire les photos de plans. external_id = UUID unitId106#   Livya (data-unit-id), identique à l'historique — zéro churn. Adresse/GPS :107#   métadonnées des immeubles « Phase N », toujours SSR dans le RSC de la108#   page ; type d'unité dérivé des chambres (— → Studio, 1 → 3½, 2 → 4½,109#   3 → 5½ — recoupé 183/183 avec l'historique en base).110#   ⚠️ Les loyers ne sont PLUS collectables : damco masque les prix sur le111#   web (showUnitPriceWeb: false, colonne Prix = « — ») — l'ancien connecteur112#   les lisait dans le JSON brut du RSC, désormais retiré. La cellule Prix est113#   tout de même parsée au cas où ils reviendraient.114#   La page WordPress /condos-locatifs-sila/ fournit toujours commodités,115#   galerie photos par immeuble, téléphone et bannières d'état des phases.116# -----------------------------------------------------------------------------117from __future__ import annotations118119import html as _html120import json121import re122import time123from urllib.parse import unquote124125from bs4 import BeautifulSoup126127from ..schema import Listing, infer_city128from .base import BaseConnector129130BASE = "https://silalevis.ca"131LIST_URL = f"{BASE}/condos-locatifs-sila/"132PHASE4_URL = f"{BASE}/phase4/"133LIVYA = "https://app.livya.com"134SECTOR = "Saint-Romuald"135136# Valeurs observées dans les modules des deux pages — replis si l'extraction137# dynamique casse138DEFAULT_CLIENT = "damco"139DEFAULT_PROJECT = "sila"140DEFAULT_ENTITIES = [141    "629800af-26e4-4697-84ba-9ea603b6affb",   # /condos-locatifs-sila/ (ph. 1-3)142    "ec7c9199-4134-44c9-b678-dd5d240a07d2",   # /phase4/ (toutes les phases)143]144145# conteneur du module plans sur les pages WordPress146_CONTAINER_RE = re.compile(147    r'<div[^>]*livya-module-container-plans[^>]*>', re.I)148_ATTR_RE = re.compile(r'data-(project|entity|lang)="([^"]*)"')149_CLIENT_RE = re.compile(r'data-client="([^"]+)"')150# fragments RSC de Next.js : self.__next_f.push([1,"…"])151_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')152153# vue tableau du DOM rendu (complète) + cartes de la grille (photos)154_ROW_RE = re.compile(r'<tr data-unit-id="([0-9a-f-]{36})"')155_TH_RE = re.compile(r'<th[^>]*>(.*?)</th>', re.S)156_TD_RE = re.compile(r'<td[^>]*>(.*?)</td>', re.S)157_CARD_RE = re.compile(r'<div[^>]*data-unit-id="([0-9a-f-]{36})"')158_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')159_COUNT_RE = re.compile(r'(\d+)\s*résultats?')160# « SILA 1 -202 » -> (immeuble « Sila 1 », numéro « 202 »)161_NAME_RE = re.compile(r'^\s*(SILA\s*\d)\s*-?\s*(\S+)\s*$', re.I)162163_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,164         "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,165         "novembre": 11, "décembre": 12}166_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)167168# bannières de la page : « Phase 4 en prélocation … »169_PHASE_BANNER_RE = re.compile(170    r"Phase\s*(\d)\s*(en\s+(?:construction|pr[ée]location)[^!.<]{0,80})", re.I)171# item de commodité réservé à certaines phases : « (Phases 2 et 3) »172_AMEN_PHASE_RE = re.compile(r"phases?\s*([\d\s,et]+)", re.I)173# photos de la page WordPress (galerie du projet)174_WP_IMG_RE = re.compile(175    r"https://silalevis\.ca/wp-content/uploads/[^\"'\s\\?]+?\.(?:jpe?g|webp)")176_WP_IMG_SKIP_RE = re.compile(177    r"logo|favicon|icon|header|loading|damco|beaubourg-ca|accordeon|"178    r"-\d+x\d+\.", re.I)179180# scrolle tous les conteneurs à overflow interne (grille lazy-loadée : le181# scroll de la fenêtre ne charge rien — auto_scroll Scrapfly inopérant)182_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"183              "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")184185186def _cell_text(cell: str) -> str:187    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", cell))).strip()188189190def _cell_num(s: str) -> float | None:191    digits = re.sub(r"[^\d.]", "", s or "")192    try:193        return float(digits) if digits else None194    except ValueError:195        return None196197198def _unit_type(beds: float | None) -> str:199    """Type dérivé des chambres (recoupé 183/183 avec l'historique JSON) :200    — -> Studio, 1 -> 3½, 2 -> 4½, 3 -> 5½…"""201    if beds is None:202        return "Studio"203    if beds < 1:204        return "Studio"205    return f"{int(beds) + 2}½"206207208class QuartierSilaConnector(BaseConnector):209    source_id = "quartier_sila"210    request_delay = 0.8211    max_units = 600                      # garde-fou (~200 unités par phase 1-4)212213    # -- page WordPress : commodités listées sous « Services et commodités » ----214    @staticmethod215    def _amenities(soup: BeautifulSoup) -> list[str]:216        """Items `<li>` entre le titre « Services et commodités » et le titre217        suivant (le pied de page et le bandeau de cookies ont aussi des puces)."""218        items: list[str] = []219        collecting = False220        for el in soup.find_all(["h1", "h2", "h3", "h4", "li"]):221            text = re.sub(r"\s+", " ", el.get_text(" ", strip=True))222            if el.name != "li":223                if collecting:224                    break225                collecting = "services et commodit" in text.lower()226                continue227            if collecting and 3 <= len(text) <= 120:228                items.append(text)229        return list(dict.fromkeys(items))[:20]230231    @staticmethod232    def _wp_gallery(html: str) -> dict[str, list[str]]:233        """Photos de la page WordPress, classées par immeuble : clés « Sila 2 »,234        « Sila 3 »… (déduites du nom de fichier : SilaII, Sila3) et « * » pour235        les photos génériques (aires communes, panoramas) valables partout."""236        gallery: dict[str, list[str]] = {}237        seen: set[str] = set()238        for u in _WP_IMG_RE.findall(html):239            if _WP_IMG_SKIP_RE.search(u):240                continue241            base = re.sub(r"\.(?:jpe?g|webp)$", "", u.rsplit("/", 1)[-1]).lower()242            if base in seen:                    # doublon .jpg/.webp243                continue244            seen.add(base)245            m = re.search(r"sila(?:_?([234])|(ii))", base)246            key = "*"247            if m:248                key = f"Sila {m.group(1) or '2'}"249            gallery.setdefault(key, []).append(u)250        return gallery251252    @staticmethod253    def _amenities_for_phase(amenities: list[str], phase: str) -> list[str]:254        """Écarte les items réservés à d'autres phases (« (Phases 2 et 3) »)."""255        out = []256        for item in amenities:257            m = _AMEN_PHASE_RE.search(item)258            if m and phase and phase not in re.findall(r"\d", m.group(1)):259                continue260            out.append(item)261        return out262263    # -- modules Livya des pages WordPress ---------------------------------------264    def _module_entities(self) -> tuple[str, str, str, list[str], str]:265        """(client, project, lang, [entités], html de la page principale).266267        Les deux pages portent chacune un sélecteur de plans distinct ;268        replis constants si l'extraction casse (gabarit WP changé)."""269        client, project, lang = DEFAULT_CLIENT, DEFAULT_PROJECT, "fr"270        entities: list[str] = []271        wp_main = ""272        for page in (LIST_URL, PHASE4_URL):273            try:274                html = self.get(page).text275            except Exception:276                continue277            if page == LIST_URL:278                wp_main = html279            mc = _CLIENT_RE.search(html)280            if mc:281                client = mc.group(1).strip() or client282            for tag in _CONTAINER_RE.findall(html):283                attrs = dict(_ATTR_RE.findall(tag))284                project = attrs.get("project") or project285                lang = attrs.get("lang") or lang286                ent = attrs.get("entity")287                if ent and ent not in entities:288                    entities.append(ent)289        if not entities:290            entities = list(DEFAULT_ENTITIES)291        return client, project, lang, entities, wp_main292293    # -- rendu navigateur ---------------------------------------------------------294    def get_rendered(self, url: str, wait_ms: int = 0) -> str:295        """HTML rendu Scrapfly, scroll des conteneurs internes (grille296        lazy-loadée). Surchargée (même nom que base) pour rester compatible297        avec le record/replay des fixtures — clé de rejeu = URL cible."""298        steps: list[dict] = []299        for _ in range(8):300            steps.append({"execute": {"script": _SCROLL_JS}})301            steps.append({"wait": 1200})302        html = self.get_scrapfly(url, render_js=True, asp=True,303                                 rendering_wait=wait_ms or 4000,304                                 js_scenario=steps)305        if not html:306            raise RuntimeError(f"Scrapfly : rendu vide — {url}")307        return html308309    def _render_ok(self, url: str) -> str:310        """Rendu dont la vue tableau est complète : le compteur « N résultats »311        doit être présent (sinon gabarit changé) et le nombre de lignes312        uniques du tableau doit l'atteindre — erreur franche après 3313        tentatives plutôt qu'un rendu tronqué qui dépublierait des unités."""314        last_err: Exception | None = None315        for attempt in range(3):316            html = self.get_rendered(url, wait_ms=4000)317            m = _COUNT_RE.search(318                _html.unescape(re.sub(r"<[^>]+>", " ", html)))319            if not m:320                last_err = RuntimeError(321                    "app.livya.com (quartier_sila) : compteur « N résultats » "322                    f"absent du rendu — gabarit Livya changé ? ({url})")323            else:324                announced = int(m.group(1))325                uniques = len(set(_ROW_RE.findall(html)))326                if uniques >= announced:327                    return html          # announced == 0 : vrai zéro accepté328                last_err = RuntimeError(329                    f"app.livya.com (quartier_sila) : {uniques} ligne(s) "330                    f"unique(s) pour {announced} annoncées — rendu "331                    f"incomplet ? ({url})")332            if attempt < 2:333                time.sleep(5 * (attempt + 1))334        assert last_err is not None335        raise last_err336337    # -- vue tableau du DOM rendu -> unités ---------------------------------------338    @staticmethod339    def _collect(html: str, units: dict[str, dict]) -> None:340        """Lignes du tableau (source de vérité) + photos des cartes de grille."""341        thead = re.search(r"<thead.*?</thead>", html, re.S)342        cols: dict[str, int] = {}343        if thead:344            for i, th in enumerate(_TH_RE.findall(thead.group(0))):345                t = _cell_text(th).lower()346                for key, label in (("name", "nom"), ("floor", "étage"),347                                   ("beds", "chambre"), ("baths", "salle"),348                                   ("area", "superficie"), ("price", "prix"),349                                   ("status", "statut")):350                    if t.startswith(label):351                        cols[key] = i352        if "name" not in cols or "status" not in cols:353            raise RuntimeError(354                "app.livya.com (quartier_sila) : en-têtes du tableau "355                "introuvables (Nom/Statut) — gabarit Livya changé ?")356357        rows = list(_ROW_RE.finditer(html))358        for i, m in enumerate(rows):359            end = rows[i + 1].start() if i + 1 < len(rows) else m.start() + 8000360            cells = [_cell_text(c) for c in361                     _TD_RE.findall(html[m.start():min(end, m.start() + 8000)])]362363            def col(key: str) -> str:364                j = cols.get(key)365                return cells[j] if j is not None and j < len(cells) else ""366367            name = col("name")368            nm = _NAME_RE.match(name)369            parsed = {370                "building": nm.group(1).title() if nm else None,371                "number": (nm.group(2) if nm else name.lstrip("#")) or None,372                "floor": _cell_num(col("floor")),373                "beds": _cell_num(col("beds")),374                "baths": _cell_num(col("baths")),375                "area": _cell_num(col("area")),376                "price": _cell_num(col("price")),377                "status": col("status") or None,378            }379            u = units.setdefault(m.group(1), {})380            for k, v in parsed.items():381                if u.get(k) is None and v is not None:382                    u[k] = v383384        # cartes de la grille (lazy-loadée, partielle) : photo du plan385        cards = [(x.start(), x.group(1)) for x in _CARD_RE.finditer(html)]386        for i, (pos, uid) in enumerate(cards):387            end = cards[i + 1][0] if i + 1 < len(cards) else pos + 9000388            im = _IMG_RE.search(html[pos:min(end, pos + 9000)])389            if im and uid in units and units[uid].get("image") is None:390                units[uid]["image"] = unquote(im.group(1))391392    # -- métadonnées des immeubles « Phase N » (flux RSC, toujours SSR) -----------393    @staticmethod394    def _buildings(html: str) -> dict[str, dict]:395        """n° de phase -> {address, city, postalCode, latitude, longitude}."""396        try:397            blob = "".join(398                json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))399        except Exception:400            return {}401        dec = json.JSONDecoder()402        out: dict[str, dict] = {}403        for m in re.finditer(r'\{"buildingId"', blob):404            try:405                obj, _ = dec.raw_decode(blob[m.start():m.start() + 8000])406            except Exception:407                continue408            pm = re.fullmatch(r"Phase\s*(\d)", (obj.get("name") or "").strip())409            if pm and obj.get("address"):410                out.setdefault(pm.group(1), obj)411        return out412413    def fetch(self) -> list[Listing]:414        client, project, lang, entities, wp = self._module_entities()415416        # page WordPress principale : commodités, galerie, téléphone, bannières417        amenities: list[str] = []418        gallery: dict[str, list[str]] = {}419        contact: dict = {}420        banners: dict[str, str] = {}421        if wp:422            soup = BeautifulSoup(wp, "html.parser")423            amenities = self._amenities(soup)424            gallery = self._wp_gallery(wp)425            tel = re.search(r'href="tel:([\d\s\-.]{10,14})"', wp)426            if tel:427                d = re.sub(r"\D", "", tel.group(1))[-10:]428                if len(d) == 10:429                    contact["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"430            banners = {n: f"Phase {n} {re.sub(r'[  ]+', ' ', rest).strip()}"431                       for n, rest in _PHASE_BANNER_RE.findall(432                           soup.get_text(" ", strip=True))}433434        units: dict[str, dict] = {}435        buildings: dict[str, dict] = {}436        announced_total = 0437        for ent in entities:438            url = (f"{LIVYA}/{lang}/{client}/projects/{project}"439                   f"/plans/{ent}?noLayout=1")440            html = self._render_ok(url)441            cm = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))442            announced_total += int(cm.group(1)) if cm else 0443            self._collect(html, units)444            buildings.update(self._buildings(html))445        if announced_total and not units:446            raise RuntimeError(447                "app.livya.com (quartier_sila) : aucune ligne d'unité dans "448                f"les rendus ({len(entities)} sélecteur(s)) — gabarit changé ?")449450        listings: list[Listing] = []451        for uid, u in list(units.items())[: self.max_units]:452            if not (u.get("status") or "").startswith("Disponible"):453                continue454            listings.append(self._listing(455                uid, u, buildings, amenities, gallery, contact, banners))456        return listings457458    # -- une annonce par unité disponible ------------------------------------------459    def _listing(self, uid: str, u: dict, buildings: dict[str, dict],460                 amenities: list[str], gallery: dict[str, list[str]],461                 contact: dict, banners: dict[str, str]) -> Listing:462        num = str(u.get("number") or "").strip()463        building = (u.get("building") or "").strip()      # « Sila 3 »464        phase = (re.sub(r"\D", "", building) or "")[:1]465        b = buildings.get(phase, {})466467        address = ", ".join(x for x in (468            (b.get("address") or "").strip(), (b.get("city") or "").strip(),469            (b.get("postalCode") or "").strip()) if x)470471        price = u.get("price")472        price = float(price) if price and price > 1 else None473474        # « Disponible » ou « Disponible - 1 décembre 2026 » (date française) ;475        # sans date : bannière d'état de la phase (« Phase 4 en prélocation… »)476        status = (u.get("status") or "").strip()477        availability = banners.get(phase, "Disponible")478        avail_date = None479        dm = _DATE_FR_RE.search(status)480        if dm and _MOIS.get(dm.group(2).lower()):481            avail_date = (f"{int(dm.group(3)):04d}-"482                          f"{_MOIS[dm.group(2).lower()]:02d}-"483                          f"{int(dm.group(1)):02d}")484            availability = f"Disponible à partir du {avail_date}"485486        beds, baths, area = u.get("beds"), u.get("baths"), u.get("area")487        unit_type = _unit_type(beds)488489        desc: list[str] = []490        floor = u.get("floor")491        if floor and floor > 0:492            desc.append(f"Étage {int(floor)}")493        if phase:494            desc.append(f"Phase {phase}")495        if beds:496            desc.append(f"{int(beds)} chambre(s)")497        if baths:498            desc.append(f"{int(baths)} salle(s) de bain")499500        details: dict = {}501        if contact:502            details["contact"] = dict(contact)503        if floor and floor > 0:504            details["floor"] = int(floor)505        if phase == "4":506            details["prelocation"] = True507508        images: list[str] = []509        if u.get("image"):510            images.append(u["image"])511        for img in (gallery.get(building) or []) + (gallery.get("*") or []):512            if img not in images:513                images.append(img)514515        try:516            lat = float(b["latitude"]) if b.get("latitude") else None517            lng = float(b["longitude"]) if b.get("longitude") else None518        except (TypeError, ValueError):519            lat = lng = None520521        titre = (f"Quartier Sila — {building}, unité {num}" if building522                 else f"Quartier Sila — unité {num}")523        return Listing(524            source=self.source_id,525            external_id=uid,                 # UUID Livya : stable, historique526            url=PHASE4_URL if phase == "4" else LIST_URL,527            title=f"{titre} ({unit_type})",528            address=address,529            sector=SECTOR,530            city=(b.get("city") or "").strip() or infer_city(SECTOR),531            unit_type=unit_type,532            bedrooms=beds if beds and beds > 0 else None,533            bathrooms=baths if baths and baths > 0 else None,534            price=price,                     # masqué par damco depuis la535            price_label=(f"{price:.0f} $ /mois" if price else ""),  # refonte536            availability=availability,537            availability_date=avail_date,538            area_sqft=area if area and area > 0 else None,539            description=" | ".join(desc),540            amenities=self._amenities_for_phase(amenities, phase),541            details=details,542            images=images[:12],543            lat=lat,544            lng=lng,545        )546
Files main
Menu

Theme