SPB Git

Repository Public

tour_fides.py 12.3 KB 306 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/tour_fides.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/tour_fides.py : connecteur La Tour Fides (latourfides.com)91#   290 unités locatives au 235, boulevard René-Lévesque Est (Ville-Marie,92#   Montréal). Le site WordPress ne publie aucun prix (le « budget » de la93#   page d'accueil est un menu de formulaire) : les vraies données vivent sur94#   le portail Yardi RentCafe/SecureCafe95#   latourfides.securecafe.com/onlineleasing/la-tour-fides/floorplans.aspx,96#   protégé par Cloudflare (403 direct) -> Scrapfly (ASP + rendu JS).97#   La page floorplans expose un accordéon par plan (data-selenium-id98#   FloorPlanName_n / Bed_Bath_n / Rent_n / Availability_n / floorplandesc_n)99#   avec fourchette de loyer réelle, superficie, salles de bain et carrousel100#   de plans par unité (id fp-myCarousel<FloorPlanID>, identifiant RentCafe101#   STABLE -> external_id). Une annonce par plan (granularité la plus fine102#   publiée, comme elite.py). Les photos du projet viennent du site vitrine103#   latourfides.com (accès direct, wp-content).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, strip_accents112from .base import BaseConnector113114SITE = "https://latourfides.com"115FLOORPLANS_URL = ("https://latourfides.securecafe.com/onlineleasing/"116                  "la-tour-fides/floorplans.aspx?nocache=-1")117118ADDRESS = "235, boulevard René-Lévesque Est, Montréal, QC H2X 1N8"119SECTOR = "Ville-Marie"120PHONE = "514-700-2589"121122# « $1,920 - à $2,920 » / « $8,600 » (format RentCafe, virgule = milliers)123_RENT_RE = re.compile(r"\$\s*([\d,]+)(?:\s*-\s*(?:à\s*)?\$\s*([\d,]+))?")124# « 424 - à 766 Square Foot » (texte de la rangée d'accordéon)125_SQFT_RE = re.compile(r"([\d,]+)(?:\s*-\s*(?:à\s*)?([\d,]+))?\s*Square\s*F",126                      re.I)127# « Bed/Bath Studio / 1 » / « Bed/Bath 2 / 1.5 »128_BEDBATH_RE = re.compile(r"(Studio|\d+)\s*/\s*([\d.]+)", re.I)129# identifiant RentCafe stable du plan (carrousel de l'accordéon)130_CAROUSEL_RE = re.compile(r"fp-myCarousel(\d+)")131# photos du site vitrine (originaux seulement, pas les variantes -WxH)132_WP_IMG_RE = re.compile(133    r"https://latourfides\.com/wp-content/uploads/[^\"'\s\)]+\.(?:jpg|jpeg|webp)",134    re.I)135_SKIP_IMG = re.compile(r"logo|icon|favicon|-\d{2,4}x\d{2,4}\.", re.I)136137138def _slugify(s: str) -> str:139    return re.sub(r"[^a-z0-9]+", "-", strip_accents(s.lower())).strip("-")140141142def _fmt(n: float) -> str:143    return f"{int(n):,}".replace(",", " ") + " $"144145146class TourFidesConnector(BaseConnector):147    source_id = "tour_fides"148    request_delay = 1.0149    max_plans = 25150    max_images = 12151152    # -- page floorplans SecureCafe (Cloudflare -> Scrapfly) --------------------153    def _floorplans_html(self) -> str:154        for wait in (4000, 9000):        # seconde chance si rendu incomplet155            html = self.get_scrapfly(FLOORPLANS_URL, rendering_wait=wait)156            if html and "FloorPlanName_1" in html:157                return html158        raise RuntimeError(159            "floorplans.aspx SecureCafe inaccessible via Scrapfly")160161    # -- photos + description du site vitrine (accès direct) --------------------162    def _site_extras(self) -> tuple[list[str], str]:163        images: list[str] = []164        blurb = ""165        try:166            html = self.get(SITE).text167            for u in dict.fromkeys(_WP_IMG_RE.findall(html)):168                if not _SKIP_IMG.search(u) and u not in images:169                    images.append(u)170            og = BeautifulSoup(html, "html.parser").find(171                "meta", attrs={"property": "og:description"})172            if og:173                blurb = (og.get("content") or "").strip()[:400]174        except Exception:175            pass176        return images[: self.max_images], blurb177178    def fetch(self) -> list[Listing]:179        # un échec transitoire doit être journalisé comme ÉCHEC par ingest180        # (ok=0), pas comme un passage « ok » à 0 annonce181        soup = BeautifulSoup(self._floorplans_html(), "html.parser")182        site_images, blurb = self._site_extras()183184        listings: list[Listing] = []185        seen: set[str] = set()186        for n in range(1, self.max_plans + 1):187            name_el = soup.select_one(f"[data-selenium-id='FloorPlanName_{n}']")188            if not name_el:189                break190            try:191                lst = self._plan_listing(soup, n, name_el, site_images, blurb)192            except Exception:193                continue194            if lst and lst.external_id not in seen:195                seen.add(lst.external_id)196                listings.append(lst)197        return listings198199    # -- une annonce par plan d'étage --------------------------------------------200    def _plan_listing(self, soup, n: int, name_el, site_images: list[str],201                      blurb: str) -> Listing | None:202        name = re.sub(r"(?i)^plan d.[ée]tage\s*", "",203                      name_el.get_text(" ", strip=True)).strip()204        if not name:205            return None206207        def _txt(prefix: str) -> str:208            el = soup.select_one(f"[data-selenium-id='{prefix}_{n}']")209            return el.get_text(" ", strip=True) if el else ""210211        # chambres / salles de bain (« Bed/Bath 2 / 1.5 »)212        unit_type = ""213        bathrooms = None214        m = _BEDBATH_RE.search(_txt("Bed_Bath"))215        if m:216            if m.group(1).lower() == "studio":217                unit_type = "Studio"218            else:219                unit_type = normalize_unit_type(f"{m.group(1)} chambres")220            try:221                bathrooms = float(m.group(2))222            except ValueError:223                pass224225        # loyer : fourchette réelle RentCafe (borne basse retenue)226        rent_txt = _txt("Rent")227        price = None228        price_label = ""229        rm = _RENT_RE.search(rent_txt)230        if rm:231            lo = float(rm.group(1).replace(",", ""))232            hi = float(rm.group(2).replace(",", "")) if rm.group(2) else None233            if 300 <= lo <= 30000:234                price = lo235                price_label = (f"À partir de {_fmt(lo)} (max {_fmt(hi)})/mois"236                               if hi and hi > lo else f"{_fmt(lo)}/mois")237        elif re.search(r"(?i)appelez|call", rent_txt):238            price_label = "Appelez-nous pour plus de détails"239240        availability = _txt("Availability")241242        # superficie « 424 - à 766 Square Foot » de la rangée d'accordéon243        area = None244        row = soup.select_one(f"[data-selenium-id='tRow{n}_1']")245        row_txt = row.get_text(" ", strip=True) if row else ""246        sm = _SQFT_RE.search(row_txt)247        sqft_bits = ""248        if sm:249            lo_s = float(sm.group(1).replace(",", ""))250            hi_s = float(sm.group(2).replace(",", "")) if sm.group(2) else None251            if 80 <= lo_s <= 20000:252                area = lo_s253                sqft_bits = (f"Superficie : {int(lo_s)} à {int(hi_s)} pi²"254                             if hi_s and hi_s > lo_s255                             else f"Superficie : {int(lo_s)} pi²")256257        # identifiant RentCafe stable du plan (id du carrousel de l'accordéon)258        ext_id = ""259        img_cell = soup.select_one(f"[data-selenium-id='Image_{n}']")260        if img_cell:261            cm = _CAROUSEL_RE.search(str(img_cell))262            if cm:263                ext_id = f"fp-{cm.group(1)}"264        ext_id = ext_id or _slugify(name)265266        # plans des unités du carrousel (cdngeneralcf.rentcafe.com) + photos site267        plan_imgs: list[str] = []268        if img_cell:269            for im in img_cell.select("img"):270                src = (im.get("src") or im.get("data-src") or "").strip()271                if src.startswith("http") and src not in plan_imgs:272                    plan_imgs.append(src)273        images = (site_images + plan_imgs)[: self.max_images + 6]274275        # description : blurb du site + texte du plan (« lire plus » exclu)276        desc = _txt("floorplandesc")277        desc = re.sub(r"(?i)\s*lire (plus|moins)\s*", " ", desc).strip()278        desc_parts = [b for b in (blurb, desc) if b]279280        amenities = []281        if sqft_bits:282            amenities.append(sqft_bits)283        specials = _txt("Specials")284        if 3 < len(specials) < 120:285            amenities.append(f"Promotion : {specials}")286287        return Listing(288            source=self.source_id,289            external_id=ext_id,290            url=FLOORPLANS_URL,291            title=f"La Tour Fides — {name}",292            address=ADDRESS,293            sector=SECTOR,294            city="Montréal",295            unit_type=unit_type,296            bathrooms=bathrooms,297            price=price,298            price_label=price_label,299            availability=availability,300            area_sqft=area,301            description=" — ".join(desc_parts)[:700],302            amenities=amenities,303            details={"contact": {"phone": PHONE}},304            images=images,305        )306
Files main
Menu

Theme