SPB Git

Repository Public

trams.py 9.0 KB 228 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/trams.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/trams.py : connecteur T.R.A.M.S Property Management (tramsmgmt.com)91#   Gestionnaire montréalais : 3 immeubles locatifs résidentiels au Québec —92#   Chateau Ste-Marie (Kirkland), L'Ambiance Ouest (Dollard-des-Ormeaux),93#   Palacio D'Anjou (Anjou). WordPress rendu serveur : la page94#   /residential-properties-for-rent/ liste les cartes (les propriétés de95#   Floride sont EXCLUES) ; chaque page /property/<slug>/ donne l'adresse,96#   la description, les caractéristiques (ul) et le contact. AUCUN prix ni97#   inventaire par unité publié (le lien securecafe/Yardi n'est que le98#   portail des résidents) → une annonce par immeuble, comme brochu.py.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing108from .base import BaseConnector109110BASE = "https://tramsmgmt.com"111LIST_URL = f"{BASE}/residential-properties-for-rent/"112113QC_RE = re.compile(r",\s*(?:QC|Qu[ée]bec)\b", re.I)114CITY_RE = re.compile(r"([A-Za-zÀ-ÿ'’.\- ]{3,40}),\s*(?:QC|Qu[ée]bec)\b")115IMG_RE = re.compile(r"https://tramsmgmt\.com/wp-content/uploads/"116                    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)117118119class TramsConnector(BaseConnector):120    source_id = "trams"121    request_delay = 0.7122123    def fetch(self) -> list[Listing]:124        listings: list[Listing] = []125        try:126            html = self.get(LIST_URL).text127        except Exception:128            return listings129        soup = BeautifulSoup(html, "html.parser")130131        seen: set[str] = set()132        for a in soup.select('a[href*="/property/"]'):133            url = (a.get("href") or "").split("?")[0]134            slug = url.rstrip("/").split("/")[-1]135            if not slug or slug in seen:136                continue137            # carte englobante : ne garder que les immeubles québécois138            card = a139            for _ in range(5):140                if card.parent is None:141                    break142                card = card.parent143                if len(card.select('a[href*="/property/"]')) > 3:144                    card = None145                    break146                text = card.get_text(" ", strip=True)147                if QC_RE.search(text):148                    break149            else:150                continue151            if card is None or not QC_RE.search(152                    card.get_text(" ", strip=True)):153                continue154            seen.add(slug)155            card_key = hashlib.sha1(156                card.get_text(" ", strip=True).encode("utf-8")).hexdigest()157            try:158                d = self.detail(slug, card_key,159                                lambda url=url: self._fetch_detail(url))160            except Exception:161                continue162            if not d.get("title"):163                continue164            city = d.get("city", "")165            listings.append(Listing(166                source=self.source_id,167                external_id=slug,168                url=url,169                title=f"{d['title']} — appartements à louer"170                      f"{' (' + city + ')' if city else ''}",171                address=d.get("address", ""),172                city=city,173                availability="Prix et visites : communiquer avec l'immeuble",174                description=d.get("description", ""),175                amenities=d.get("amenities") or [],176                details={"contact": d["contact"]} if d.get("contact") else {},177                images=d.get("images") or [],178            ))179        return listings180181    def _fetch_detail(self, url: str) -> dict:182        out: dict = {}183        html = self.get(url).text184        soup = BeautifulSoup(html, "html.parser")185        article = soup.find("article") or soup186187        h1 = article.find("h1")188        if h1:189            out["title"] = h1.get_text(" ", strip=True)190191        # bloc adresse sous le titre (rue / ville, QC / code postal)192        addr_div = article.select_one("div.text-center.pb-1")193        if addr_div:194            addr = re.sub(r"\s+", " ",195                          addr_div.get_text(", ", strip=True))196            out["address"] = re.sub(r"\s*,\s*(,\s*)+", ", ", addr).strip(" ,")197            m = CITY_RE.search(out["address"])198            if m:199                out["city"] = m.group(1).strip()200201        # description : paragraphes substantiels ; caractéristiques : 1re liste202        paras = [p.get_text(" ", strip=True) for p in article.find_all("p")203                 if len(p.get_text(strip=True)) > 60204                 and "call" not in p.get_text().lower()[:40]]205        out["description"] = re.sub(r"\s+", " ",206                                    " ".join(paras[:3])).strip()[:1200]207        amenities: list[str] = []208        for li in article.select("ul li"):209            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True)).rstrip(".")210            if 0 < len(t) <= 80 and t not in amenities:211                amenities.append(t)212        out["amenities"] = amenities[:15]213214        contact: dict = {}215        m = re.search(r'href="tel:([\d\- ()]{7,})"', html)216        if m:217            contact["phone"] = m.group(1).strip()218        m = re.search(r'href="mailto:([^"?]+)"', html)219        if m:220            contact["email"] = m.group(1).strip().lower()221        out["contact"] = contact222223        out["images"] = [224            u for u in dict.fromkeys(IMG_RE.findall(html))225            if not re.search(r"logo|icon|favicon|cropped-|-\d{2,3}x\d{2,3}\.",226                             u, re.I)][:20]227        return out228
Files main
Menu

Theme