SPB Git

Repository Public

tours_st_martin.py 9.1 KB 230 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/tours_st_martin.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/tours_st_martin.py : connecteur Les Tours Saint-Martin91#   (lestourssaintmartin.ca) — deux tours locatives de 12 étages au92#   2976, boulevard Saint-Martin Ouest, Laval (Chomedey). Même thème WordPress93#   maison que Le L Laval (l_laval.py) : pages /plans/ (phase 1) et94#   /plans-phase-2/ avec une ligne <tr id="rowUnitNNN"> par unité — classe95#   « not-available » = louée ; onclick=loadPage(unité, prix, pi², étage, état,96#   modèle, typologie). Les prix par unité ne sont pas publiés : on récupère les97#   « à partir de » affichés sur la page d'accueil (ex. « Grands 4½ à partir de98#   1972$/mois ») comme price_label par typologie. Granularité : unité.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from ..schema import Listing, normalize_unit_type105from .base import BaseConnector106107BASE = "https://lestourssaintmartin.ca"108PHASES = [("1", f"{BASE}/plans/"), ("2", f"{BASE}/plans-phase-2/")]109110ADDRESS = "2976, boulevard Saint-Martin Ouest, Laval"111CITY = "Laval"112SECTOR = "Chomedey"113114ROW_RE = re.compile(115    r'<tr\s+id="rowUnit(\w+)"[^>]*class="([^"]*)"[^>]*'116    r"onclick='loadPage\(([^)]*)\)'", re.I)117ARG_RE = re.compile(r'"([^"]*)"')118# « Grands 4½ à partir de 1972$/mois » (page d'accueil)119FROM_RE = re.compile(120    r"(\d\s*(?:½|1/2|&frac12;)|[Ss]tudios?)[^<$]{0,40}?"121    r"à\s+partir\s+de\s+(\d[\d\s,]*)\s*\$", re.I)122IMG_RE = re.compile(123    r"https://lestourssaintmartin\.ca/wp-content/uploads/"124    r"[^\"'\s\\]+\.(?:jpe?g|png|webp)", re.I)125SKIP_IMG_RE = re.compile(r"logo|favicon|icon|plan|-\d{2,4}x\d{2,4}\.", re.I)126127128class ToursStMartinConnector(BaseConnector):129    source_id = "tours_st_martin"130    request_delay = 0.6131    max_images = 10132133    def _from_prices(self) -> dict[str, str]:134        """{'4½': 'à partir de 1972$/mois'} depuis la page d'accueil."""135        prices: dict[str, str] = {}136        try:137            html = self.get(f"{BASE}/").text138        except Exception:139            return prices140        for typo, amount in FROM_RE.findall(html):141            key = normalize_unit_type(142                typo.replace("&frac12;", "½").replace("1/2", "½"))143            amount = amount.strip().replace(" ", "")144            if key and key not in prices:145                prices[key] = f"à partir de {amount}$/mois"146        return prices147148    def _site_images(self) -> list[str]:149        try:150            html = self.get(f"{BASE}/appartements-laval/").text151        except Exception:152            return []153        return [u for u in dict.fromkeys(IMG_RE.findall(html))154                if not SKIP_IMG_RE.search(u)][: self.max_images]155156    def fetch(self) -> list[Listing]:157        from_prices = self._from_prices()158        images = self._site_images()159160        listings: list[Listing] = []161        for phase, url in PHASES:162            try:163                html = self.get(url).text164            except Exception:165                continue166            seen: set[str] = set()167            for unit, classes, raw_args in ROW_RE.findall(html):168                if "not-available" in classes or unit in seen:169                    continue170                seen.add(unit)171                # loadPage(unité, prix, pi², étage, état, modèle, typologie)172                args = ARG_RE.findall(raw_args)173                if len(args) < 5:174                    continue175                _, price_raw, sqft_raw, floor, etat = args[:5]176                if etat.strip() not in ("", "0"):177                    continue178                model = args[5] if len(args) > 5 else ""179                typo = args[6] if len(args) > 6 else ""180                typo = typo.replace("&frac12;", "½").replace("1/2", "½")181                unit_type = normalize_unit_type(typo)182183                price = None184                price_label = ""185                m = re.search(r"(\d[\d\s,]*)\s*\$", price_raw)186                if m:187                    try:188                        val = float(m.group(1).replace(" ", "")189                                    .replace(",", ""))190                        if 300 <= val <= 20000:191                            price = val192                            price_label = price_raw.strip()193                    except ValueError:194                        pass195                if price is None:196                    price_label = from_prices.get(unit_type,197                                                  "Prix sur demande")198199                area = None200                try:201                    v = float(sqft_raw)202                    if 100 <= v <= 10000:203                        area = v204                except ValueError:205                    pass206207                desc_bits = [208                    f"Phase {phase}",209                    f"Unité {unit}, {floor}e étage" if floor else "",210                    f"Modèle {model}" if model else "",211                ]212                listings.append(Listing(213                    source=self.source_id,214                    external_id=f"p{phase}-{unit}",215                    url=f"{url}#unite-{unit}",216                    title=f"Les Tours Saint-Martin (phase {phase})"217                          f" — Unité {unit}",218                    address=ADDRESS,219                    sector=SECTOR,220                    city=CITY,221                    unit_type=unit_type,222                    price=price,223                    price_label=price_label,224                    availability="Disponible",225                    area_sqft=area,226                    description=" — ".join(b for b in desc_bits if b),227                    images=list(images),228                ))229        return listings230
Files main
Menu

Theme