SPB Git

Repository Public

trylon.py 10.0 KB 247 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/trylon.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/trylon.py : connecteur Trylon Montréal (trylonmontreal.com)91#   Immeuble unique au 1400, avenue des Pins Ouest (centre-ville, au pied92#   du Mont-Royal). WordPress/Elementor rendu serveur : la page /fr/des-pins/93#   liste les unités disponibles sous forme de sections « Semi-Meublé - <mois>94#   <année> » suivies de cartes (type, prix $/mo, étage, surface, inclusions).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99100from bs4 import BeautifulSoup101102from ..schema import Listing, normalize_unit_type103from .base import BaseConnector104105BASE = "https://trylonmontreal.com"106PAGE_URL = f"{BASE}/fr/des-pins/"107108ADDRESS = "1400, avenue des Pins Ouest, Montréal"109BUILDING_AMENITIES = ["Piscine chauffée intérieure", "Salle d'entraînement",110                      "Terrasse sur le toit"]111112IMG_RE = re.compile(113    r"https://trylonmontreal\.com/wp-content/uploads/"114    r"[^\"\s\\]+?\.(?:jpg|jpeg|png|webp)", re.I)115116AVAIL_RE = re.compile(117    r"^(?:Semi-)?(?:Non-)?Meubl[ée]\s*[-–]\s*\w+\s*\d{4}$|"118    r"^Disponible[\w\s]*$|^Libre[\w\s]*$", re.I)119UNIT_RE = re.compile(r"^Appartement\s+\d\s*(?:1/2|½)", re.I)120PRICE_RE = re.compile(r"\$\s*([\d\s,]+)\s*/\s*mo", re.I)121122123class TrylonConnector(BaseConnector):124    source_id = "trylon"125    request_delay = 0.6126127    def fetch(self) -> list[Listing]:128        listings: list[Listing] = []129        try:130            html = self.get(PAGE_URL).text131        except Exception:132            return listings133        soup = BeautifulSoup(html, "html.parser")134135        # Photos de l'immeuble (les cartes d'unités n'ont pas de galerie propre)136        images = [u for u in dict.fromkeys(IMG_RE.findall(html))137                  if not re.search(r"logo|icon|favicon|-\d+x\d+\.", u, re.I)][:20]138139        # Parcours en ordre du document : un en-tête « Semi-Meublé - <mois> »140        # définit la disponibilité des cartes qui suivent.141        availability = ""142        current: dict | None = None143        seen: dict[str, int] = {}144145        # Contact de l'immeuble (liens mailto:/tel: structurés dans la page)146        contact: dict = {}147        m = re.search(r'href="mailto:([^"?]+)"', html)148        if m:149            contact["email"] = m.group(1).strip().lower()150        m = re.search(r'href="tel:\+?1?(\d{3})(\d{3})(\d{4})"', html)151        if m:152            contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"153154        def flush():155            nonlocal current156            if not current or not current.get("unit_type"):157                current = None158                return159            ut = current["unit_type"]160            price = current.get("price")161            floor = current.get("floor", "")162            base_id = re.sub(r"[^\w.\-]", "",163                             f"despins-{ut.replace('½', '.5')}-{floor}"164                             f"-{int(price) if price else 'na'}")165            seen[base_id] = seen.get(base_id, 0) + 1166            ext_id = base_id if seen[base_id] == 1 else f"{base_id}-{seen[base_id]}"167            desc_bits = [b for b in (168                f"Étage : {floor}" if floor else "",169                f"Surface : {current.get('sqft', '')}" if current.get("sqft") else "",170                current.get("furnished", ""),171            ) if b]172            # Étage/surface aussi en commodités : la normalisation dérive173            # details.floor et area_sqft depuis les items de liste.174            extras = [b for b in desc_bits if not b.startswith("Semi")175                      and not b.startswith("Non") and not b.startswith("Meubl")]176            listings.append(Listing(177                source=self.source_id,178                external_id=ext_id,179                url=PAGE_URL,180                title=f"Appartement {ut} — 1400 des Pins",181                address=ADDRESS,182                sector="Centre-ville",183                city="Montréal",184                unit_type=ut,185                price=price,186                price_label=current.get("price_label", ""),187                availability=current.get("availability", ""),188                description=" | ".join(desc_bits)[:600],189                amenities=list(dict.fromkeys(190                    current.get("inclusions", []) + extras + BUILDING_AMENITIES)),191                details={"contact": dict(contact)} if contact else {},192                images=images,193            ))194            current = None195196        widgets = soup.select(".elementor-widget-heading .elementor-heading-title,"197                              " .elementor-widget-text-editor"198                              " .elementor-widget-container")199        for w in widgets:200            try:201                text = w.get_text(" ", strip=True)202            except Exception:203                continue204            if not text:205                continue206            if AVAIL_RE.match(text):207                flush()208                availability = text209                continue210            if UNIT_RE.match(text):211                flush()212                furnished = ""213                m = re.match(r"(Semi-|Non-)?Meubl[ée]", availability, re.I)214                if m:215                    furnished = m.group(0)216                current = {217                    "unit_type": normalize_unit_type(text),218                    "availability": availability,219                    "furnished": furnished,220                }221                continue222            if current is not None:223                m = PRICE_RE.search(text)224                if m and "price" not in current:225                    num = m.group(1).replace(" ", "").replace(" ", "").replace(",", "")226                    try:227                        val = float(num)228                        if 100 <= val <= 20000:229                            current["price"] = val230                            current["price_label"] = m.group(0)231                    except ValueError:232                        pass233                    continue234                m = re.search(r"Étage\s*:\s*([\w]+)", text)235                if m:236                    current["floor"] = m.group(1)237                m = re.search(r"Surface\s*:\s*([\d\s]+\s*pc)", text)238                if m:239                    current["sqft"] = m.group(1).strip()240                m = re.search(r"Inclusions?\s*:\s*(.+?)(?:$|CONTACTER)", text)241                if m:242                    current["inclusions"] = [243                        a.strip(" .").capitalize()244                        for a in re.split(r",| et ", m.group(1)) if a.strip(" .")]245        flush()246        return listings247
Files main
Menu

Theme