SPB Git

Repository Public

lameer.py 10.6 KB 264 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lameer.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/lameer.py : connecteur Gestion Lameer (lameer.ca, 2300+ unités)91#   Site Webflow rendu serveur : /properties liste les immeubles (cartes92#   a.properties_item-link), chaque fiche /properties/<slug> expose un tableau93#   « overview » (Neighbourhood, Postal Code, Bedrooms « 2.5 to 4.5 »,94#   Starting Price, Appliances/Laundry/Heating/Hydro/Parking) + description et95#   galerie (cdn.prod.website-files.com). Immeubles résidentiels seulement96#   (Building Type = Residential). Une annonce par immeuble, prix « à partir97#   de » ; external_id = slug de la fiche. Fiches via le cache détail (clé =98#   hash du texte de la carte).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price, strip_accents108from .base import BaseConnector109110BASE = "https://www.lameer.ca"111LIST_URL = f"{BASE}/properties"112113BEDS_RANGE_RE = re.compile(r"([\d.]+)\s*to\s*([\d.]+)")114IMG_BAD_RE = re.compile(r"logo|chevron|icon|favicon|\.svg", re.I)115116# Neighbourhood (site anglophone) -> (secteur, ville)117_HOODS = {118    "montreal": ("", "Montréal"),119    "lachine": ("Lachine", "Montréal"),120    "verdun": ("Verdun", "Montréal"),121    "lasalle": ("LaSalle", "Montréal"),122    "cote saint-luc": ("", "Côte Saint-Luc"),123    "pointe-claire": ("", "Pointe-Claire"),124    "mount royal": ("", "Mont-Royal"),125}126127# lignes du tableau overview reprises comme commodités (valeur informative)128_AMENITY_ROWS = ("Appliances", "Laundry", "Heating / Hot Water", "Hydro",129                 "Parking")130_AMENITY_FR = {131    "Appliances": "Électroménagers",132    "Laundry": "Buanderie",133    "Heating / Hot Water": "Chauffage / eau chaude",134    "Hydro": "Électricité",135    "Parking": "Stationnement",136}137_VALUE_FR = {"included": "incluse(s)", "in-suite": "dans l'unité",138             "available": "disponible", "not included": "non incluse(s)",139             "on-site": "sur place"}140141142class LameerConnector(BaseConnector):143    source_id = "lameer"144    request_delay = 0.7145146    def fetch(self) -> list[Listing]:147        html = self.get(LIST_URL).text148        soup = BeautifulSoup(html, "html.parser")149        listings: list[Listing] = []150        for card in soup.select("a.properties_item-link[href]"):151            try:152                href = card["href"]153                slug = href.rstrip("/").rsplit("/", 1)[-1]154                card_text = card.get_text(" | ", strip=True)155                if not card_text.startswith("Residential"):156                    continue                 # immeubles commerciaux exclus157                # photo de couverture de la carte : repli si la fiche n'a158                # pas de galerie (certaines n'ont que logo/chevrons)159                cover = ""160                img = card.find("img")161                if img:162                    u = img.get("src") or img.get("data-src") or ""163                    if u.startswith("http") and not IMG_BAD_RE.search(u):164                        cover = u165                key = hashlib.sha1(card_text.encode("utf-8")).hexdigest()166                d = self.detail(slug, key,167                                lambda h=href: self._property(f"{BASE}{h}"))168                if cover and not d.get("images"):169                    d = dict(d, images=[cover])170                lst = self._listing(slug, f"{BASE}{href}", d)171                if lst:172                    listings.append(lst)173            except Exception:174                continue175        return listings176177    def _property(self, url: str) -> dict:178        """Scrape la fiche immeuble : tableau overview, description, photos."""179        out: dict = {"title": "", "rows": {}, "desc": "", "images": []}180        page = self.get(url).text181        soup = BeautifulSoup(page, "html.parser")182        if soup.h1:183            out["title"] = soup.h1.get_text(" ", strip=True)184        for row in soup.select(".overview-table_row"):185            cells = [c.get_text(" ", strip=True)186                     for c in row.find_all("div", recursive=False)]187            if len(cells) >= 2 and cells[0]:188                out["rows"][cells[0]] = cells[1]189        for p in soup.find_all("p"):190            t = p.get_text(" ", strip=True)191            # premier paragraphe substantiel = description de l'immeuble192            # (on écarte le boilerplate « management services » du pied de page)193            if len(t) > 80 and "management services" not in t:194                out["desc"] = t[:800]195                break196        images = []197        for img in soup.find_all("img"):198            u = img.get("src") or ""199            if u.startswith("https://cdn.prod.website-files.com") \200                    and not IMG_BAD_RE.search(u) and u not in images:201                images.append(u)202        out["images"] = images[:15]203        return out204205    def _listing(self, slug: str, url: str, d: dict) -> Listing | None:206        rows = d.get("rows", {})207        title = d.get("title") or slug.replace("-", " ").title()208        hood = (rows.get("Neighbourhood") or "").strip()209        sector, city = _HOODS.get(strip_accents(hood.lower()),210                                  (hood, "Montréal"))211        postal = (rows.get("Postal Code") or "").strip()212        address = title + (f", {city}" if city else "")213        if postal:214            address += f", QC {postal}"215216        price = None217        price_label = ""218        sp = (rows.get("Starting Price") or "").strip()219        if sp:220            price_label = f"À partir de {sp} $"221            price = parse_price(price_label)222223        # « 2.5 to 4.5 » : gamme de types ; type = borne basse224        unit_type = ""225        beds = (rows.get("Bedrooms") or "").strip()226        amenities: list[str] = []227        m = BEDS_RANGE_RE.search(beds)228        if m:229            lo, hi = m.group(1), m.group(2)230            unit_type = normalize_unit_type(lo.replace(".5", " 1/2"))231            try:232                borne_ok = float(hi) >= float(lo)233            except ValueError:234                borne_ok = False235            if borne_ok:                     # coquilles source (« 2.5 to .5 »)236                amenities.append(f"Unités de {lo.replace('.5', '½')} "237                                 f"à {hi.replace('.5', '½')}")238            else:239                amenities.append(f"Unités de {lo.replace('.5', '½')} et plus")240        elif beds:241            unit_type = normalize_unit_type(beds.replace(".5", " 1/2"))242        for k in _AMENITY_ROWS:243            v = (rows.get(k) or "").strip()244            if v:245                amenities.append(246                    f"{_AMENITY_FR.get(k, k)} : {_VALUE_FR.get(v.lower(), v)}")247248        return Listing(249            source=self.source_id,250            external_id=slug,251            url=url,252            title=title,253            address=address,254            sector=sector,255            city=city,256            unit_type=unit_type,257            price=price,258            price_label=price_label,259            availability="",260            description=d.get("desc", ""),261            amenities=amenities,262            images=d.get("images", []),263        )264
Files main
Menu

Theme