SPB Git

Repository Public

serra.py 10.4 KB 268 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/serra.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/serra.py : connecteur SERRA Montréal (serramtl.com)91#   Tour locative « tout inclus » au 1124, rue De Bleury (Ville-Marie,92#   centre-ville de Montréal) — studios, 3½ et 4½, bail minimal de 12 mois.93#   Site Rentsync (assets.rentsync.com/bleury1124) RENDU SERVEUR : la page94#   /availabilities publie le tableau des unités disponibles dans des95#   div.suite structurées (data-beds, data-sqft, data-building,96#   data-availability-date MMAAAA, numéro d'unité, plan d'étage PDF) et un97#   identifiant RentSync stable par unité (data-suite-id du bouton modal)98#   -> une annonce Lou-Ka par unité. Aucun prix public (ni sur le site ni99#   dans le JS — pas de flux LiftSystem pour ce client) : price_label vide,100#   la fiche reste utile (dispo, superficie, plan, tout inclus).101#   La description vient de /apartments et la galerie de /gallery (variante102#   /256/, la seule servie publiquement par le CDN pour ce client).103# -----------------------------------------------------------------------------104from __future__ import annotations105106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing111from .base import BaseConnector112113BASE = "https://www.serramtl.com"114AVAIL_URL = f"{BASE}/availabilities"115ABOUT_URL = f"{BASE}/apartments"116GALLERY_URL = f"{BASE}/gallery"117118# adresses vérifiées par immeuble (jamais devinées : inconnu -> vide)119_BUILDINGS = {120    "BLEURY": "1124, rue De Bleury, Montréal",121}122SECTOR = "Ville-Marie (centre-ville)"123PHONE = "514-788-4385"124125# chambres (data-beds) -> type d'unité Lou-Ka126_BED_TYPES = {"0": "Studio", "studio": "Studio", "1": "3½", "2": "4½",127              "3": "5½"}128# galerie Rentsync de la page /gallery (le CDN ne sert que /256/)129_IMG_RE = re.compile(130    r"https://assets\.rentsync\.com/bleury1124/images/gallery/[^\"'\\)\s]+"131    r"\.(?:jpg|jpeg|png|webp)", re.I)132_SKIP_IMG = re.compile(r"logo|icon|favicon|thumbnail|theme-settings", re.I)133# date structurée « 092026 » (MMAAAA) de data-availability-date134_MMYYYY_RE = re.compile(r"^(0[1-9]|1[0-2])(20\d{2})$")135136137class SerraConnector(BaseConnector):138    source_id = "serra"139    request_delay = 0.6140    max_images = 15141142    def fetch(self) -> list[Listing]:143        html = self.get(AVAIL_URL).text144        soup = BeautifulSoup(html, "html.parser")145146        description = self._description()147        gallery = self._gallery()148149        listings: list[Listing] = []150        seen: set[str] = set()151        for suite in soup.select("div.suite"):152            try:153                lst = self._suite_listing(suite, description, gallery)154            except Exception:155                continue156            if lst and lst.external_id not in seen:157                seen.add(lst.external_id)158                listings.append(lst)159        return listings160161    # -- une annonce par unité disponible ---------------------------------------162    def _suite_listing(self, suite, description: str,163                       gallery: list[str]) -> Listing | None:164        type_el = suite.select_one(".suite-type")165        unit = ""166        if type_el:167            unit = re.sub(r"^\s*Unit\s*", "",168                          type_el.get_text(" ", strip=True)).strip()169        if not unit:170            return None171172        building = (suite.get("data-building") or "").strip().upper()173        beds_raw = (suite.get("data-beds") or "").strip().lower()174        unit_type = _BED_TYPES.get(beds_raw, "")175176        # superficie structurée (attribut + cellule)177        area = None178        try:179            v = float((suite.get("data-sqft") or "0").replace(",", ""))180            if 80 <= v <= 20000:181                area = v182        except ValueError:183            pass184185        # disponibilité : texte de la cellule + date structurée MMAAAA186        avail_el = suite.select_one(".suite-availability")187        availability = ""188        if avail_el:189            availability = re.sub(190                r"^\s*Availability\s*", "",191                avail_el.get_text(" ", strip=True)).strip()192        avail_date = None193        m = _MMYYYY_RE.match((suite.get("data-availability-date")194                              or "").strip())195        if m:196            avail_date = f"{m.group(2)}-{m.group(1)}-01"197        elif (suite.get("data-availability-date") or "") == "000000" \198                and not availability:199            availability = "Disponible maintenant"200201        # identifiant RentSync stable de l'unité (bouton « Request Info »)202        sid = ""203        btn = suite.select_one("[data-suite-id]")204        if btn:205            sid = (btn.get("data-suite-id") or "").strip()206        ext_id = sid or f"{building.lower()}-{re.sub(r'[^0-9A-Za-z-]', '', unit)}"207208        # plan d'étage PDF de l'unité (colonne structurée)209        details: dict = {"contact": {"phone": PHONE}}210        if building:211            details["building"] = building.title()212        plan = suite.select_one(".suite-floorplans a[href^='http']")213        if plan:214            details["floorplan"] = plan["href"]215216        amenities = ["Tout inclus (chauffage, eau chaude, climatisation)"]217        if area:218            amenities.append(f"{int(area)} pi²")219220        return Listing(221            source=self.source_id,222            external_id=ext_id,223            url=AVAIL_URL,224            title=f"SERRA Montréal — unité {unit}",225            address=_BUILDINGS.get(building, ""),226            sector=SECTOR,227            city="Montréal",228            unit_type=unit_type,229            price=None,                      # aucun prix public chez SERRA230            price_label="",231            availability=availability,232            availability_date=avail_date,233            description=description,234            amenities=amenities,235            details=details,236            images=gallery[: self.max_images],237        )238239    # -- description du projet (/apartments) ------------------------------------240    def _description(self) -> str:241        default = ("SERRA Montréal — tour locative tout inclus au centre-ville "242                   "(1124, rue De Bleury) : studios, 1 et 2 chambres, bail "243                   "minimal de 12 mois.")244        try:245            soup = BeautifulSoup(self.get(ABOUT_URL).text, "html.parser")246            paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]247            paras = [p for p in paras if len(p) > 100]248            if paras:249                return " ".join(paras[:2])[:600]250        except Exception:251            pass252        return default253254    # -- galerie (/gallery + page dispo) ----------------------------------------255    def _gallery(self) -> list[str]:256        images: list[str] = []257        for url in (GALLERY_URL, AVAIL_URL):258            try:259                html = self.get(url).text260            except Exception:261                continue262            for u in _IMG_RE.findall(html):263                if not _SKIP_IMG.search(u) and u not in images:264                    images.append(u)265            if images:266                break267        return images268
Files main
Menu

Theme