SPB Git

Repository Public

groupe_maurice.py 13.5 KB 317 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_maurice.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1713# 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/groupe_maurice.py : Le Groupe Maurice — 37 résidences pour aînés91#   (RPA) au Québec (Montréal, Laval, Rive-Sud/Nord, Québec, Gatineau…).92#   WordPress avec API REST maison : /wp-json/api/v1/residences retourne les93#   37 résidences géolocalisées (adresse, lat/lng, ville, url, vignette).94#   Chaque page résidence (SSR) expose la grille des types d'unités dans des95#   <article class="y-bordered"> : « Studio | 408 pi.ca à 628 pi.ca |96#   À partir de 2 286 $ par mois ». Une annonce Lou-Ka par type × résidence,97#   prix plancher « à partir de », étiquetée Résidence pour aînés.98#   La même page (déjà téléchargée) fournit aussi la galerie de la résidence99#   (photos des appartements et des aires communes — carousel360 +100#   gallery--large + alentours), le texte de présentation et la liste des101#   caractéristiques des unités (« Le confort à votre mesure ») : on les102#   applique à chaque annonce sans aucune requête supplémentaire.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type111from .base import BaseConnector112113API = "https://www.legroupemaurice.com/wp-json/api/v1/residences"114115_ROW_RE = re.compile(116    r"^(?P<type>.+?)\s+(?P<a1>[\d\s]+)\s*pi\.?\s*ca(?:\s*à\s*(?P<a2>[\d\s]+)\s*pi\.?\s*ca)?"117    r"\s*À partir de\s*(?P<prix>[\d\s]+)\s*\$\s*par mois", re.S)118_TAG_RE = re.compile(r"<[^>]+>")119_IMG_EXT_RE = re.compile(r"\.(?:jpe?g|webp|png)$", re.I)120# visuels génériques partagés entre résidences (le carrousel « Les121# appartements » mélange des photos SEV/LJM/STH… d'autres résidences) et UI122_IMG_SKIP_RE = re.compile(r"(?:Carrousel_Appartements|Bloc_Votre_Appartement|"123                          r"logo|icon|favicon|picto)", re.I)124_SIZE_SUFFIX_RE = re.compile(r"-\d+x\d+(?=\.)")125# « …_3.5-Salon-… » dans le nom de fichier : photo d'un type d'unité précis,126# priorisée pour l'annonce du type correspondant127_TYPE_IN_FN_RE = re.compile(r"[_-](\d\.\d)-")128129130class GroupeMauriceConnector(BaseConnector):131    source_id = "groupe_maurice"132    request_delay = 0.6133    max_images = 30134135    def _rows(self, soup: BeautifulSoup) -> list[dict]:136        out = []137        for art in soup.find_all("article"):138            if "y-bordered" not in (art.get("class") or []):139                continue140            text = re.sub(r"\s+", " ", art.get_text(" ", strip=True))141            m = _ROW_RE.match(text)142            if not m:143                continue144            try:145                price = float(m.group("prix").replace(" ", ""))146                area = float(m.group("a1").replace(" ", ""))147            except ValueError:148                continue149            area_max = None150            if m.group("a2"):151                try:152                    area_max = float(m.group("a2").replace(" ", ""))153                except ValueError:154                    area_max = None155            out.append({"type": m.group("type").strip(),156                        "price": price, "area": area, "area_max": area_max})157        return out158159    # -- galerie de la résidence -------------------------------------------------160    def _gallery(self, soup: BeautifulSoup) -> list[str]:161        """Photos de la résidence, dans l'ordre des carrousels de la page :162        visite « carousel360 » (pièces des appartements types + communs),163        galerie des aires communes, puis les alentours. Les visuels164        génériques inter-résidences et les variantes redimensionnées sont165        écartés (dédoublonnage par nom de fichier)."""166        imgs: list[str] = []167        seen: set[str] = set()168        for sel in ("div.carousel360 img", "div.gallery.gallery--large img",169                    "div.carousel-residence__carousel img"):170            for im in soup.select(sel):171                src = (im.get("src") or im.get("data-src") or "").split("?")[0]172                fn = src.rsplit("/", 1)[-1]173                if not src.startswith("http") or not _IMG_EXT_RE.search(fn):174                    continue175                if _IMG_SKIP_RE.search(fn):176                    continue177                key = _SIZE_SUFFIX_RE.sub("", fn).lower()178                if key in seen:179                    continue180                seen.add(key)181                imgs.append(src)182        return imgs183184    # -- présentation + caractéristiques des unités --------------------------------185    @staticmethod186    def _presentation(soup: BeautifulSoup) -> tuple[str, str, list[str]]:187        """(intro, alentours, caractéristiques des unités) de la page.188189        Intro = premier paragraphe long de la page (texte d'accueil de la190        résidence) ; alentours = paragraphe sous « Aux alentours de la191        résidence » ; caractéristiques = liste « Le confort à votre mesure »192        (cuisine, balcon, insonorisation…)."""193        intro = alentours = ""194        for p in soup.find_all("p"):195            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()196            if len(t) >= 120:197                intro = t198                break199        for h in soup.find_all("h2"):200            if "alentours" not in h.get_text(" ", strip=True).lower():201                continue202            sec = h203            for _ in range(5):204                sec = sec.parent205                if sec is None:206                    break207                for p in sec.find_all("p"):208                    t = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()209                    if len(t) >= 120:210                        alentours = t211                        break212                if alentours:213                    break214            break215        feats: list[str] = []216        for h in soup.find_all("h2"):217            if "confort à votre mesure" not in h.get_text(" ", strip=True).lower():218                continue219            sec = h220            for _ in range(5):221                sec = sec.parent222                if sec is None:223                    break224                lis = sec.find_all("li")225                if lis:226                    for li in lis[:20]:227                        t = re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip()228                        if 3 <= len(t) <= 90 and t not in feats:229                            feats.append(t)230                    break231            break232        return intro, alentours, feats233234    def fetch(self) -> list[Listing]:235        data = self.get(API).json()236        residences = (data.get("result") or {})237        if isinstance(residences, dict):238            residences = list(residences.values())239        out: list[Listing] = []240        for res in residences:241            url = res.get("url") or ""242            if not url:243                continue244            slug = url.rstrip("/").rsplit("/", 1)[-1]245            try:246                soup = BeautifulSoup(self.get(url).text, "html.parser")247            except Exception:248                continue249            rows = self._rows(soup)250            gallery = self._gallery(soup)251            intro, alentours, feats = self._presentation(soup)252253            excerpt = _TAG_RE.sub("", res.get("excerpt") or "").strip()254            # description : accueil de la page + extrait API + quartier —255            # sans doublon (l'extrait reprend parfois le début de l'intro)256            paras = []257            for t in (intro, excerpt, alentours):258                if t and all(t[:80] not in p for p in paras):259                    paras.append(t)260            desc = "\n\n".join(paras)261262            try:263                lat, lng = float(res.get("latitude")), float(res.get("longitude"))264            except (TypeError, ValueError):265                lat = lng = None266            for row in rows:267                raw_type = row["type"]268                unit_type = normalize_unit_type(raw_type)269                details = {"Résidence pour aînés": "oui"}270                if "den" in raw_type.lower() or "+" in raw_type:271                    details["Type d'unité (résidence)"] = raw_type272                if row.get("area_max") and row["area_max"] > row["area"]:273                    details["Superficie"] = (f"{row['area']:.0f} à "274                                             f"{row['area_max']:.0f} pi²")275                eid = f"{slug}-{re.sub(r'[^a-z0-9]+', '-', raw_type.lower()).strip('-')}"276277                # galerie : vignette (façade) d'abord, puis les photos du type278                # d'unité de l'annonce (« 3.5-Salon »…), puis le reste279                images: list[str] = []280                if res.get("thumbnail"):281                    images.append(res["thumbnail"])282                token = ""283                m = re.search(r"(\d)\s*[½]", raw_type)284                if m:285                    token = f"{m.group(1)}.5"286                matched, rest = [], []287                for u in gallery:288                    tm = _TYPE_IN_FN_RE.search(u.rsplit("/", 1)[-1])289                    if token and tm and tm.group(1) == token:290                        matched.append(u)291                    else:292                        rest.append(u)293                for u in matched + rest:294                    if u not in images:295                        images.append(u)296297                out.append(Listing(298                    source=self.source_id,299                    external_id=eid,300                    url=url,301                    title=f"{raw_type} — Résidence {res.get('residence', slug)}",302                    address=res.get("address") or "",303                    city=res.get("city") or "",304                    unit_type=unit_type,305                    price=row["price"],306                    price_label=f"À partir de {row['price']:,.0f} $ par mois"307                                .replace(",", " "),308                    area_sqft=row["area"],309                    description=desc,310                    amenities=list(feats),311                    details=details,312                    images=images[: self.max_images],313                    lat=lat,314                    lng=lng,315                ))316        return out317
Files main
Menu

Theme