SPB Git

Repository Public

groupe_robin.py 12.0 KB 295 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_robin.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-10-2814#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_robin.py : connecteur Groupe Robin (grouperobin.com)91#   WordPress Elementor multi-lignes d'affaires. La page /appartement/ charge92#   ses immeubles via admin-ajax.php (action get_list_immeubles_ajx,93#   explicitement permis par robots.txt) : JSON riche par immeuble (adresse94#   + GPS, photos, descriptions, résumé par grandeur avec loyer « à partir95#   de », superficie, statut et dates de disponibilité). On ne garde que la96#   catégorie 126 = appartements locatifs résidentiels ; 1 annonce =97#   1 immeuble × grandeur (le grain affiché par le site). ~2 requêtes/sync.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102import time103104import requests105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110BASE = "https://grouperobin.com"111AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"112CAT_APPARTEMENT = "126"      # taxonomie « type » : Appartement (résidentiel)113PER_PAGE = 40114115# villes où Groupe Robin exploite du locatif résidentiel (multi-régions :116# District 55 à Trois-Rivières + parc historique à Saint-Hyacinthe)117_CITY_RE = re.compile(118    r"(Trois-Rivi[eè]res|Saint-Hyacinthe|St-Hyacinthe|"119    r"Saint-Bruno(?:-de-Montarville)?|Mont-Saint-Hilaire|Belo?eil)", re.I)120_CITY_CANON = {121    "st-hyacinthe": "Saint-Hyacinthe",122    "saint-bruno": "Saint-Bruno-de-Montarville",123}124125126def _city_name(raw: str) -> str:127    k = raw.strip().lower().replace("é", "e").replace("è", "e")128    for pref, canon in _CITY_CANON.items():129        if k.startswith(pref):130            return canon131    return raw.strip()132133134def _strip_html(raw: str, limit: int = 1200) -> str:135    if not raw:136        return ""137    txt = BeautifulSoup(raw, "html.parser").get_text("\n", strip=True)138    return re.sub(r"[ \t]+", " ", txt).strip()[:limit]139140141def _num(raw) -> float | None:142    """'1625' -> 1625.0 ; '' / '0' / non numérique -> None (jamais deviné)."""143    s = str(raw or "").strip().replace(",", ".")144    if re.fullmatch(r"\d+(\.\d+)?", s):145        val = float(s)146        return val if val > 0 else None147    return None148149150class GroupeRobinConnector(BaseConnector):151    source_id = "groupe_robin"152    request_delay = 0.8153    max_pages = 5        # garde-fou (2 pages réelles à 40 immeubles/page)154    timeout = 60         # payload admin-ajax ~3,9 Mo, backend WP parfois lent155156    # Le POST admin-ajax (3,9 Mo) hoquète par épisodes (ReadTimeout isolés157    # 09-13, 10-17, 10-28) alors que le site est sain entre deux — 3158    # tentatives avec backoff ; erreur franche inchangée si les 3 échouent.159    def _post_ajax(self, offset: int) -> list:160        """POST admin-ajax paginé, avec la même politesse que get()."""161        last: Exception | None = None162        for attempt in range(3):163            if attempt:164                time.sleep(5 * attempt)165            wait = self.request_delay - (time.time() - self._last_request)166            if wait > 0:167                time.sleep(wait)168            try:169                resp = self.session.post(AJAX_URL, data={170                    "action": "get_list_immeubles_ajx",171                    "offset": str(offset),172                    "immeubles_per_page": str(PER_PAGE),173                    "categories[]": CAT_APPARTEMENT,174                }, timeout=self.timeout)175            except (requests.Timeout, requests.ConnectionError) as exc:176                self._last_request = time.time()177                last = exc178                continue179            self._last_request = time.time()180            if resp.status_code >= 500:181                last = requests.HTTPError(182                    f"{resp.status_code} sur {AJAX_URL}", response=resp)183                continue184            resp.raise_for_status()185            return resp.json()186        raise last  # type: ignore[misc]187188    def fetch(self) -> list[Listing]:189        listings: dict[str, Listing] = {}190        total_pages = 1191        for page in range(self.max_pages):192            if page >= total_pages:193                break194            data = self._post_ajax(page * PER_PAGE)195            immeubles = data[0] if data else []196            opts = data[1] if len(data) > 1 else {}197            total_pages = min(int(opts.get("total_pages") or 1), self.max_pages)198            if not immeubles:199                break200            for imm in immeubles:201                try:202                    self._parse_immeuble(imm, listings)203                except Exception:204                    continue205        return list(listings.values())206207    # -- un immeuble = n annonces (une par grandeur, le grain du site) --------208    def _parse_immeuble(self, imm: dict, listings: dict[str, Listing]) -> None:209        imm_id = str(imm.get("id") or "")210        titre = (imm.get("titre") or "").strip()211        if not imm_id or not titre:212            return213        # défense : autres lignes d'affaires (résidences aînés, commercial…)214        if re.search(r"r[ée]sidence|retrait[ée]|commercial|bureau|h[oô]tel",215                     titre, re.I):216            return217        resumer = imm.get("appartements_resumer")218        if not isinstance(resumer, dict) or not resumer:219            return           # immeuble sans unité annoncée220221        url = imm.get("lien") or f"{BASE}/appartement/"222        adresse = imm.get("adresse_postale") or {}223        full_addr = adresse.get("address") or "" if isinstance(adresse, dict) else ""224        address = full_addr.split(",")[0].strip() if full_addr else ""225        lat = adresse.get("lat") if isinstance(adresse, dict) else None226        lng = adresse.get("lng") if isinstance(adresse, dict) else None227228        # ville réelle : cherchée dans l'adresse Google, sinon dans le terme229        # d'emplacement des unités (« Trois-Rivières (District 55) »)230        city, sector = "", ""231        m = _CITY_RE.search(full_addr) or _CITY_RE.search(titre)232        if m:233            city = _city_name(m.group(1))234        for apt in imm.get("appartements") or []:235            for term in apt.get("emplacement") or []:236                name = term.get("name") or ""237                mm = re.match(r"(.+?)\s*\((.+)\)", name)238                if mm:239                    city = city or _city_name(mm.group(1))240                    sector = mm.group(2)241                elif not city:242                    city = _city_name(name)243                break244            if city:245                break246247        description = _strip_html(imm.get("description_generale") or "")248249        images: list[str] = []250        main_img = imm.get("image_immeuble")251        if isinstance(main_img, str) and main_img.startswith("http"):252            images.append(main_img)253        for ph in imm.get("photos") or []:254            u = ((ph or {}).get("photo") or {}).get("url") or ""255            if u.startswith("http") and u not in images:256                images.append(u)257258        for grandeur, grp in resumer.items():259            if not isinstance(grp, dict):260                continue261            g = (grp.get("grandeur") or grandeur or "").strip()262            loyer = _num(grp.get("loyer"))263            # rendu du site : « à partir de 1625$ » ou « Prix sur demande »264            price_label = f"à partir de {int(loyer)}$" if loyer else "Prix sur demande"265            labels = [l for l in (grp.get("dates_disponibilite_label") or []) if l]266            availability = ", ".join(dict.fromkeys(labels))267            if not availability:268                availability = str(grp.get("statut_disponible") or "")269270            amenities = [a for a in (grp.get("inclusions") or [])271                         if isinstance(a, str) and a]272273            ext_id = f"{imm_id}-{re.sub(r'[^0-9a-zA-Z½]+', '', g) or 'u'}"274            if ext_id in listings:275                continue276            listings[ext_id] = Listing(277                source=self.source_id,278                external_id=ext_id,       # id WP de l'immeuble + grandeur279                url=url,280                title=f"{g} — {titre}" if g else titre,281                address=address,282                sector=sector,283                city=city,284                unit_type=normalize_unit_type(g),285                price=loyer,286                price_label=price_label,287                availability=availability,288                area_sqft=_num(grp.get("superficie")),289                description=description,290                amenities=amenities,291                images=images[:15],292                lat=lat if isinstance(lat, (int, float)) else None,293                lng=lng if isinstance(lng, (int, float)) else None,294            )295
Files main
Menu

Theme