SPB Git

Repository Public

groupe_theoret.py 9.1 KB 219 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_theoret.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-09-0914#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/groupe_theoret.py : connecteur Groupe Théorêt (locationappartement.ca)91#   Refonte du site vers GoDaddy Airo (React Router, lancée ~2026-09-09) :92#   l'ancien widget « menu » du Website Builder (data-aid MENU_SECTION_*)93#   n'existe plus et l'URL accentuée /appartements-%C3%A0-louer redirige 30194#   vers /appartements-a-louer. La nouvelle page embarque TOUT le catalogue95#   dans le payload d'hydratation `window.__staticRouterHydrationData`96#   (JSON.parse("…")) : loaderData -> properties[] avec, par immeuble,97#   adresse + ville + code postal + slug (/proprietes/<slug>), services98#   (inclusions), photos (/airo-assets/images/<slotKey>) et contact du99#   concierge ; et par unité DISPONIBLE : id stable (clé BD du site), type100#   (« 3 1/2 (rénové) »), loyer mensuel et date de disponibilité ISO.101#   Une seule requête suffit — plus de pages immeuble ni de cache détail.102#   Contrairement à l'ancien site, celui-ci publie des photos par immeuble.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import re108109from ..schema import Listing, normalize_unit_type, strip_accents110from .base import BaseConnector111112BASE = "https://locationappartement.ca"113LIST_URL = f"{BASE}/appartements-a-louer"114115# villes réelles du parc (normalisation des variantes : Ste-Thérèse…)116_CITY_MAP = {117    "montreal": "Montréal",118    "laval": "Laval",119    "charlemagne": "Charlemagne",120    "terrebonne": "Terrebonne",121    "ste-therese": "Sainte-Thérèse",122    "sainte-therese": "Sainte-Thérèse",123    "shawinigan": "Shawinigan",124    "grand-mere": "Shawinigan",     # secteur fusionné de Shawinigan125}126127_HYDRATION_RE = re.compile(128    r'window\.__staticRouterHydrationData\s*=\s*'129    r'JSON\.parse\("((?:[^"\\]|\\.)*)"\)')130131132def _city_from(raw: str) -> str:133    key = strip_accents(raw.strip().lower())134    return _CITY_MAP.get(key, raw.strip().title())135136137class GroupeTheoretConnector(BaseConnector):138    source_id = "groupe_theoret"139    request_delay = 0.8140    use_detail_cache = False    # tout est dans la page liste depuis la refonte141142    def fetch(self) -> list[Listing]:143        html = self.get(LIST_URL).text144        props = self._hydration_properties(html)145        if not props:146            # la page saine embarque toujours les ~40 immeubles du parc147            # (même quand 0 unité est disponible) — payload absent ou vide148            # = structure changée : échec franc plutôt qu'un faux « 0 ok »149            raise RuntimeError(150                "groupe_theoret : payload __staticRouterHydrationData absent "151                f"ou sans immeuble sur {LIST_URL} — structure changée ?")152153        listings: list[Listing] = []154        for p in props:155            address = (p.get("address") or p.get("name") or "").strip()156            city = _city_from(p.get("city") or "")157            postal = (p.get("postalCode") or "").strip()158            slug = (p.get("slug") or "").strip()159            url = f"{BASE}/proprietes/{slug}" if slug else LIST_URL160            images = [161                f"{BASE}/airo-assets/images/{ph['slotKey']}"162                for ph in sorted(p.get("photos") or [],163                                 key=lambda x: x.get("sortOrder") or 0)164                if ph.get("slotKey")]165            amenities: list[str] = []166            for s in p.get("services") or []:167                name = (s.get("name") or "").strip()168                if not name:169                    continue170                if s.get("included"):171                    amenities.append(f"{name} (Inclus)")172                elif s.get("detail"):173                    amenities.append(f"{name} ({str(s['detail']).strip()})")174            details: dict = {}175            c = p.get("contact") or {}176            if c.get("contactName"):177                contact = {"name": str(c["contactName"]).strip()}178                for k_src, k_dst in (("phone", "phone"), ("mobile", "mobile")):179                    if c.get(k_src):180                        contact[k_dst] = str(c[k_src]).strip()181                details["contact"] = contact182183            for u in p.get("units") or []:184                size = (u.get("size") or "").strip()185                try:186                    price = float(u["monthlyRent"])187                except (KeyError, TypeError, ValueError):188                    price = None189                avail = str(u.get("availabilityDate") or "")[:10]190                listings.append(Listing(191                    source=self.source_id,192                    external_id=f"u{u['id']}",193                    url=url,194                    title=f"{size} au {address}, {city}".strip(", "),195                    address=f"{address}, {postal}" if postal else address,196                    city=city,197                    unit_type=normalize_unit_type(size),198                    price=price,199                    availability=avail,200                    amenities=list(amenities),201                    details=dict(details),202                    images=list(images),203                ))204        return listings205206    @staticmethod207    def _hydration_properties(html: str) -> list[dict]:208        """properties[] du payload d'hydratation React Router de la page."""209        m = _HYDRATION_RE.search(html)210        if not m:211            return []212        # littéral de chaîne JS (guillemets échappés) -> texte -> objet213        data = json.loads(json.loads(f'"{m.group(1)}"'))214        for value in (data.get("loaderData") or {}).values():215            if isinstance(value, dict) and isinstance(216                    value.get("properties"), list):217                return value["properties"]218        return []219
Files main
Menu

Theme