SPB Git

Repository Public

res_soleil.py 11.0 KB 257 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/res_soleil.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-10-0714#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/res_soleil.py : Les Résidences Soleil (Groupe Savoie) — 15 manoirs91#   pour aînés au Québec (Montréal, Laval, Rive-Sud, Sherbrooke, Granby,92#   Pointe-aux-Trembles…). WordPress avec API REST maison :93#   /wp-json/closest_residence_locator/coordinates/<lat>/<lng>/-1/fr retourne94#   les 15 manoirs géolocalisés (adresse civique, ville, téléphone, url).95#   Depuis la refonte d'octobre 2026, chaque fiche manoir publie une grille de96#   prix HTML sémantique (section .lrs-<manoir>-pricing : .pricing-row avec97#   .unit-type / .meal-plan / .monthly-price) — fini l'OCR de l'ancienne image98#   « Notre offre ». Une annonce Lou-Ka par manoir × typologie (1½ studio …99#   5½), prix plancher de la fourchette « sans repas » quand elle existe,100#   sinon du forfait repas le moins cher (noté en détails).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing109from .base import BaseConnector110111API = ("https://residencessoleil.ca/wp-json/closest_residence_locator/"112       "coordinates/45.5/-73.5/-1/fr")113114_IMG_RE = re.compile(115    r"https://residencessoleil\.ca/wp-content/uploads/[^\"\s\\']+"116    r"\.(?:jpe?g|webp)", re.I)117_IMG_SKIP_RE = re.compile(118    r"logo|icon|favicon|Notre-offre|grille|Programme|Meilleur-rapport|"119    r"Feuillet|-\d+x\d+\.", re.I)120_TYPO_RE = re.compile(r"([1-5])\s*½")121_PRICE_RE = re.compile(r"(\d[\d\s]{2,9}?)\s*\$")122_REPAS_RE = re.compile(r"(\d+)\s*(?:à\s*(\d+)\s*)?repas/mois")123124125class ResidencesSoleilConnector(BaseConnector):126    source_id = "res_soleil"127    request_delay = 0.8128    timeout = 45129    max_images = 15130    use_detail_cache = False  # la grille de prix est inline dans la page131132    # -- grille de prix HTML de la fiche manoir --------------------------------133    @staticmethod134    def _parse_grille(soup: BeautifulSoup) -> dict[int, list[dict]]:135        """Section .pricing-row -> {typologie: [{forfait, min, max}, …]}."""136        rows: dict[int, list[dict]] = {}137        for row in soup.select("section[class*=pricing] .pricing-row"):138            unit = row.select_one(".unit-type")139            price = row.select_one(".monthly-price")140            if not unit or not price:141                continue142            tm = _TYPO_RE.search(unit.get_text(" ", strip=True))143            if not tm:144                continue145            typo = int(tm.group(1))146            prices = []147            for p in _PRICE_RE.findall(price.get_text(" ", strip=True)):148                try:149                    val = int(re.sub(r"\s", "", p))150                except ValueError:151                    continue152                if 500 <= val <= 20000:153                    prices.append(val)154            if not prices:155                continue156            meal = row.select_one(".meal-plan")157            low = meal.get_text(" ", strip=True).lower() if meal else ""158            if re.search(r"s[ae]ns\s+repas", low):159                forfait = "sans repas"160            else:161                rm = _REPAS_RE.search(low)162                if rm:163                    n = rm.group(1) + (f" à {rm.group(2)}" if rm.group(2) else "")164                    forfait = f"{n} repas/mois inclus"165                else:166                    forfait = "forfait repas inclus"167            rows.setdefault(typo, []).append(168                {"forfait": forfait, "min": min(prices), "max": max(prices)})169        return rows170171    # -- fiche manoir : grille, galerie, présentation --------------------------172    def _page_payload(self, url: str) -> dict:173        html = self.get(url).text174        images = [u for u in dict.fromkeys(_IMG_RE.findall(html))175                  if not _IMG_SKIP_RE.search(u)][: self.max_images]176        soup = BeautifulSoup(html, "html.parser")177        intro = ""178        for p in soup.find_all("p"):179            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()180            if len(t) >= 120 and "crédit d" not in t.lower():181                intro = t182                break183        return {"rows": self._parse_grille(soup), "images": images,184                "intro": intro}185186    def fetch(self) -> list[Listing]:187        out: list[Listing] = []188        residences = self.get(API).json()189        if not isinstance(residences, list):190            return out191        pages_sans_grille: list[str] = []192        for res in residences:193            url = res.get("residence_url") or ""194            title = (res.get("residence_title") or "").strip()195            if not url or not title:196                continue197            slug = url.rstrip("/").rsplit("/", 1)[-1]198            page = self._page_payload(url)199            rows = page.get("rows") or {}200            if not rows:201                pages_sans_grille.append(slug)202                continue203204            address = " ".join(x for x in (res.get("residence_street_number"),205                                           res.get("residence_street_name"))206                               if x).strip()207            city = (res.get("residence_city") or "").strip()208            try:209                lat = float(res.get("residence_latitude"))210                lng = float(res.get("residence_longitude"))211            except (TypeError, ValueError):212                lat = lng = None213214            for typo in sorted(rows):215                options = rows[typo]216                # loyer de référence : fourchette « sans repas » si publiée,217                # sinon le forfait repas le moins cher218                sans = [o for o in options if o["forfait"] == "sans repas"]219                best = (min(sans, key=lambda o: o["min"]) if sans220                        else min(options, key=lambda o: o["min"]))221                raw_type = "1 ½ (studio)" if typo == 1 else f"{typo} ½"222                label = (f"De {best['min']:,} $ à {best['max']:,} $ par mois"223                         .replace(",", " "))224                if best["forfait"] != "sans repas":225                    label += f" ({best['forfait']})"226                details = {"Résidence pour aînés": "oui",227                           "Loyer estimé": "grille de prix officielle "228                                           "de la résidence"}229                if best["forfait"] != "sans repas":230                    details["Forfait repas"] = best["forfait"]231                out.append(Listing(232                    source=self.source_id,233                    external_id=f"{slug}-{typo}-5",234                    url=url,235                    title=f"{raw_type} — Les Résidences Soleil {title}",236                    address=address,237                    city=city,238                    unit_type=f"{typo}½",239                    price=float(best["min"]),240                    price_label=label,241                    description=page.get("intro") or "",242                    details=details,243                    images=list(page.get("images") or []),244                    lat=lat,245                    lng=lng,246                ))247        # erreur FRANCHE : les 15 manoirs sont permanents — zéro grille de prix248        # sur TOUTES les fiches = gabarit remanié, pas un vrai zéro (c'est249        # l'ancienne image « Notre offre » disparue qui a causé les zéros250        # silencieux d'octobre 2026).251        if not out and residences:252            raise RuntimeError(253                "res_soleil : aucune grille de prix trouvée sur les "254                f"{len(residences)} fiches manoir (ex. {pages_sans_grille[:3]}) "255                "— gabarit probablement remanié, vérifier le connecteur")256        return out257
Files main
Menu

Theme