SPB Git

Repository Public

sotramont.py 12.4 KB 299 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/sotramont.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-10-2914#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/sotramont.py : connecteur Sotramont (sotramont.com)91#   Promoteur montréalais : condos locatifs Liveo (Pointe-Claire/Greenwich92#   1-2-3, Mascouche 1-2, Repentigny 1-2, Bois-Franc) et Curtiss Charlie93#   (Saint-Laurent). WordPress rendu serveur : le portfolio94#   ?category=locatifs liste les cartes article.c--article-project95#   (badge occupation, nom, « quartier – ville », « N condos locatifs »,96#   li typologies « 1-2 chambres sur 10 étages » + « à partir de N $ par97#   mois avec inclusions »). AUCUN inventaire par unité publié → une98#   annonce par PHASE/immeuble ; les cartes « Vendu » ou « En construction »99#   sont exclues. Détail (description, photos) tiré de la page phase quand100#   elle est hébergée sur sotramont.com (Repentigny pointe vers liveo.ca).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106import time107108from bs4 import BeautifulSoup109110from ..schema import Listing111from .base import BaseConnector112113BASE = "https://sotramont.com"114LIST_URL = f"{BASE}/projets-maison-ville-condo-vendre-louer/?category=locatifs"115116SKIP_TAG_RE = re.compile(r"vendu|en\s+construction", re.I)117PRICE_RE = re.compile(r"[àa]\s*partir\s*de\s*([\d\s  ,]+)\s*\$", re.I)118BEDS_RE = re.compile(r"(\d)(?:\s*-\s*(\d))?\s*chambres?", re.I)119UNITS_RE = re.compile(r"(\d{2,4})\s*condos\s*locatifs", re.I)120IMG_RE = re.compile(r"https://sotramont\.com/wp-content/uploads/"121                    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)122123124def _slugify(name: str) -> str:125    s = name.lower()126    s = re.sub(r"[àâä]", "a", s)127    s = re.sub(r"[éèêë]", "e", s)128    s = re.sub(r"[îï]", "i", s)129    s = re.sub(r"[ôö]", "o", s)130    s = re.sub(r"[ûüù]", "u", s)131    s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")132    return s133134135class SotramontConnector(BaseConnector):136    source_id = "sotramont"137    request_delay = 0.7138139    def fetch(self) -> list[Listing]:140        listings: list[Listing] = []141        # Hoquets transitoires récurrents : GET en échec (vagues DNS du nœud142        # 09-10/09-18, resets du VPS) mais AUSSI 200 servi SANS cartes143        # (épisodes 10-17 et 10-29) — les deux se retryent, puis échec FRANC144        # (jamais de `return []` silencieux → « 0 trouvé ok » à tort).145        arts = []146        last_err: Exception | None = None147        for attempt in range(3):148            if attempt:149                time.sleep(3 * attempt)150            try:151                html = self.get(LIST_URL).text152            except Exception as e:  # noqa: BLE001 — retry puis erreur franche153                last_err = e154                continue155            soup = BeautifulSoup(html, "html.parser")156            arts = soup.select("article.c--article-project")157            if arts:158                break159            last_err = None160        else:161            if last_err is not None:162                raise RuntimeError(163                    f"sotramont : portfolio inaccessible après 3 tentatives "164                    f"({last_err!r}) — {LIST_URL}")165            # Vrai zéro = cartes présentes mais aucune locative active ;166            # AUCUNE carte ×3 = gabarit remanié ou page vide → erreur franche.167            raise RuntimeError(168                "sotramont : aucune carte projet dans le portfolio "169                "(3 tentatives) — site remanié ? — "170                f"{LIST_URL}")171172        seen: set[str] = set()173        for art in arts:174            try:175                if "project-category-locatifs" not in (art.get("class") or []):176                    continue177                tag_el = art.select_one(".c--article-project__tag")178                tag = tag_el.get_text(" ", strip=True) if tag_el else ""179                if not tag or SKIP_TAG_RE.search(tag):180                    continue        # vendu / en construction / sans badge181                name_el = art.select_one(".c--article-project__text-lg")182                name = (name_el.get_text(" ", strip=True)183                        if name_el else "")184                if not name:185                    continue186                ext_id = _slugify(name)187                if ext_id in seen:188                    continue189                seen.add(ext_id)190191                # « Greenwich – Pointe-Claire » / « Mascouche »192                loc_el = art.select_one(".c--article-project__text-md")193                loc = re.sub(r"\s+", " ", loc_el.get_text(" ", strip=True)194                             if loc_el else "")195                sector, city = "", loc196                if "–" in loc or "-" in loc and "," not in loc:197                    parts = re.split(r"\s*[–—]\s*", loc)198                    if len(parts) == 2:199                        sector, city = parts[0].strip(), parts[1].strip()200                        # doublon d'accessibilité (« Bois-FrancBois-Franc »)201                        half = len(sector) // 2202                        if half and sector[:half] == sector[half:]:203                            sector = sector[:half]204205                lis = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))206                       for li in art.select("li")]207                price = None208                price_label = ""209                typologie = ""210                bedrooms = None211                for t in lis:212                    m = PRICE_RE.search(t)213                    if m and price is None:214                        try:215                            price = float(m.group(1).replace(" ", "")216                                          .replace(" ", "").replace(" ", "")217                                          .replace(",", ""))218                            price_label = t219                        except ValueError:220                            pass221                    m = BEDS_RE.search(t)222                    if m and not typologie:223                        typologie = t   # fourchette (« 1-2 chambres… »)224                        if not m.group(2):      # nombre précis seulement225                            bedrooms = float(m.group(1))226227                details: dict = {}228                if typologie:229                    details["typologies"] = typologie230                h5 = art.select_one(".content-text h5")231                if h5:232                    m = UNITS_RE.search(h5.get_text(" ", strip=True))233                    if m:234                        details["nb_unites"] = m.group(1)235236                a = art.select_one("a.c--article-project__inner")237                url = (a.get("href") or "").split("?")[0] if a else ""238                images: list[str] = []239                fig = art.find("figure")240                if fig:241                    m = re.search(r"url\(([^)]+)\)", fig.get("style", ""))242                    if m:243                        images.append(m.group(1).strip("'\""))244245                d: dict = {}246                if url.startswith(BASE):247                    key = hashlib.sha1(248                        "|".join([tag, name] + lis).encode("utf-8")249                    ).hexdigest()250                    d = self.detail(ext_id, key,251                                    lambda url=url: self._fetch_detail(url))252                elif not url:253                    url = LIST_URL254255                listings.append(Listing(256                    source=self.source_id,257                    external_id=ext_id,258                    url=url,259                    title=f"{name} — condos locatifs ({city})",260                    sector=sector,261                    city=city,262                    bedrooms=bedrooms,263                    price=price,264                    price_label=price_label,265                    availability=tag,266                    description=d.get("description", ""),267                    details=details,268                    images=(d.get("images") or images)[:20],269                ))270            except Exception:271                continue272        return listings273274    def _fetch_detail(self, url: str) -> dict:275        """Page phase : description marketing + galerie photos."""276        out: dict = {}277        try:278            html = self.get(url).text279        except Exception:280            return out281        soup = BeautifulSoup(html, "html.parser")282        main = soup.find("main") or soup283284        paras = [p.get_text(" ", strip=True) for p in main.find_all("p")285                 if len(p.get_text(strip=True)) > 80]286        # sauter les descriptions génériques du méga-menu (répétées partout)287        paras = [p for p in paras288                 if "portfolio" not in p.lower()289                 and "équilibre sain" not in p.lower()290                 and "quel que soit le budget" not in p.lower()]291        if paras:292            out["description"] = re.sub(r"\s+", " ",293                                        " ".join(paras[:3])).strip()[:1200]294        out["images"] = [295            u for u in dict.fromkeys(IMG_RE.findall(html))296            if not re.search(r"logo|icon|favicon|cropped-|plan|"297                             r"-\d{2,3}x\d{2,3}\.", u, re.I)][:20]298        return out299
Files main
Menu

Theme