SPB Git

Repository Public

apero.py 12.7 KB 313 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/apero.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/apero.py : connecteur Apéro Appartement (aperoappartement.com)91#   Trois immeubles locatifs neufs : Apéro Teasdale (900 boul. Lucille-92#   Teasdale, Terrebonne), Apéro Charlemagne (115 boul. Céline-Dion,93#   Charlemagne) et Apéro LaSalle (Montréal, arrondissement LaSalle).94#   Site Webflow ; la gestion est sur Building Stack (app.buildingstack.com,95#   portail résident sans annonces publiques). L'inventaire vient de :96#     - le CMS Webflow exposé via le proxy de l'agence Momentumm97#       (tools.momentumm.ca/webflow_cms_new.php?collection_id=<id>) : une98#       entrée par unité (numero stable « ter101 » / « char1228 », étage,99#       typologie, superficie, chambres, sdb, drapeau disponibilite) — la100#       collection et le code d'immeuble (« ter » / « char ») sont lus dans101#       les blocs cachés #units-collection-id / #building-code des pages ;102#     - les pages /terrebonne /charlemagne /lasalle : prix plancher par103#       typologie (« À partir de 1250$ ») et photos — le CMS n'a pas de prix104#       par unité (champs prix/braquette vides pour les unités disponibles).105#   Granularité : unité pour Terrebonne/Charlemagne ; typologie pour LaSalle106#   (aucune collection d'unités sur cette page). Location résidentielle107#   longue durée (bail standard), pas de meublé court terme.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import json112import re113114from bs4 import BeautifulSoup115116from ..schema import Listing117from .base import BaseConnector118119SITE = "https://www.aperoappartement.com"120CMS = ("https://tools.momentumm.ca/webflow_cms_new.php"121       "?api_key=j3$jre$3jd$5k76%&webflow_api_key=1&collection_id={cid}")122123# pages d'immeuble : (chemin, ville, secteur, adresse civique — vérifiée sur124# la page : JSON-LD (Terrebonne) et texte de présentation (Charlemagne))125BUILDINGS = {126    "terrebonne": ("Terrebonne", "Lachenaie",127                   "900 Boulevard Lucille-Teasdale, Terrebonne"),128    "charlemagne": ("Charlemagne", "",129                    "115 Boulevard Céline-Dion, Charlemagne"),130    "lasalle": ("Montréal", "LaSalle", ""),131}132133_WS_RE = re.compile(r"\s+")134_PRICE_CARD_RE = re.compile(135    r"(Studio|\d\s*1/2)\s*À partir de\s*(\d[\d\s]*)\$", re.I)136_IMG_RE = re.compile(137    r'https://cdn\.prod\.website-files\.com/[^"\s]+\.(?:jpe?g|webp|png)',138    re.I)139_SKIP_IMG_RE = re.compile(r"logo|icon|favicon|arrow|plan|svg|p-500|p-800", re.I)140141142def _typologie(raw: str) -> str:143    """'4 1/2' -> '4½', 'Studio' -> 'Studio'."""144    s = (raw or "").strip()145    if not s:146        return ""147    if "studio" in s.lower():148        return "Studio"149    m = re.match(r"(\d)\s*1/2", s)150    return f"{m.group(1)}½" if m else s151152153class AperoConnector(BaseConnector):154    source_id = "apero"155    request_delay = 0.6156    max_images = 10157158    # -- page d'immeuble : prix plancher par typologie + photos + config CMS ----159    def _page(self, path: str) -> dict:160        html = self.get(f"{SITE}/{path}").text161        soup = BeautifulSoup(html, "html.parser")162        prices: dict[str, str] = {}       # '3½' -> 'À partir de 1540$'163        for wrap in soup.select(".unit-nfo_txt-wrapper"):164            txt = _WS_RE.sub(" ", wrap.get_text(" ", strip=True))165            m = _PRICE_CARD_RE.search(txt)166            if m:167                amount = m.group(2).replace(" ", "").replace(" ", "")168                prices[_typologie(m.group(1))] = f"À partir de {amount}$"169        cid = soup.select_one("#units-collection-id")170        code = soup.select_one("#building-code")171        imgs = [u for u in dict.fromkeys(_IMG_RE.findall(html))172                if not _SKIP_IMG_RE.search(u)]173        return {174            "prices": prices,175            "collection_id": cid.get_text(strip=True) if cid else "",176            "building_code": (code.get_text(strip=True).lower()177                              if code else ""),178            "images": imgs[: self.max_images],179        }180181    # -- collection CMS Webflow (toutes les unités, tous immeubles) -------------182    def _cms_units(self, cid: str) -> list[dict]:183        data = self.get(CMS.format(cid=cid)).json()184        return [x.get("fieldData") or {} for x in data185                if isinstance(x, dict)]186187    def fetch(self) -> list[Listing]:188        pages = {}189        for path in BUILDINGS:190            try:191                pages[path] = self._page(path)192            except Exception:193                pages[path] = {}194195        # collection d'unités (une seule collection pour tous les immeubles)196        cids = [p.get("collection_id") for p in pages.values()197                if p.get("collection_id")]198        units: list[dict] = []199        if cids:200            try:201                units = self._cms_units(cids[0])202            except Exception:203                units = []204205        listings: list[Listing] = []206        for path, (city, sector, address) in BUILDINGS.items():207            page = pages.get(path) or {}208            code = page.get("building_code")209            url = f"{SITE}/{path}"210            prices = page.get("prices") or {}211            images = page.get("images") or []212            if code:                      # granularité unité (ter / char)213                for f in units:214                    numero = str(f.get("numero") or "").strip()215                    if not numero.lower().startswith(code):216                        continue217                    if not f.get("disponibilite"):218                        continue219                    listings.append(self._unit_listing(220                        f, numero, url, city, sector, address,221                        prices, images))222            else:                         # LaSalle : typologie seulement223                for utype, label in prices.items():224                    slug = (utype.replace("½", "-et-demi")225                            .lower().replace(" ", ""))226                    listings.append(Listing(227                        source=self.source_id,228                        external_id=f"{path}-{slug}",229                        url=url,230                        title=f"Apéro {path.capitalize()} — {utype}",231                        address=address,232                        sector=sector,233                        city=city,234                        unit_type=utype,235                        price_label=label,236                        availability="Disponible",237                        description=(f"Appartement {utype} dans l'immeuble "238                                     f"Apéro {path.capitalize()} — {label}."),239                        images=list(images),240                    ))241242        # dédup par external_id (sécurité)243        uniq: dict[str, Listing] = {}244        for lst in listings:245            uniq.setdefault(lst.external_id, lst)246        return list(uniq.values())247248    # -- une annonce par unité disponible (Terrebonne / Charlemagne) -----------249    def _unit_listing(self, f: dict, numero: str, url: str, city: str,250                      sector: str, address: str, prices: dict[str, str],251                      images: list[str]) -> Listing:252        utype = _typologie(str(f.get("typeoutput") or ""))253        num_out = str(f.get("numerooutput") or numero).strip()254255        def _num(v) -> float | None:256            try:257                return float(str(v).strip().replace(",", "."))258            except (TypeError, ValueError):259                return None260261        beds = _num(f.get("chambres"))262        baths = _num(f.get("salledebains"))263        area = _num(f.get("superficie-2"))264        if area is not None and not 80 <= area <= 20000:265            area = None266267        # prix : champ CMS de l'unité si présent, sinon plancher de typologie268        price = _num(f.get("prix"))269        price_label = prices.get(utype, "")270        if price and not 100 <= price <= 20000:271            price = None272273        details: dict = {}274        etage = str(f.get("etage") or "").strip()275        if etage.isdigit():276            details["floor"] = int(etage)277        if beds is not None:278            details["bedrooms"] = int(beds)279        if baths is not None:280            details["bathrooms"] = int(baths)281282        desc = " — ".join(x for x in [283            f"Modèle {f['modele']}" if f.get("modele") else "",284            f"{area:g} pi²" if area else "",285            f"étage {etage}" if etage else "",286            f"{int(beds)} chambre(s)" if beds else "",287            f"{int(baths)} salle(s) de bain" if baths else ""] if x)288289        imgs = list(images)290        plan = str(f.get("planurl") or "")291        if plan.startswith("http"):292            imgs.insert(0, plan)293294        bname = url.rstrip("/").rsplit("/", 1)[-1].capitalize()295        return Listing(296            source=self.source_id,297            external_id=numero,           # slug CMS stable (ter101, char1228)298            url=url,299            title=f"Apéro {bname} — Unité {num_out}",300            address=address,301            sector=sector,302            city=city,303            unit_type=utype,304            bedrooms=beds,305            bathrooms=baths,306            price=price,307            price_label=price_label,308            availability="Disponible",309            area_sqft=area,310            description=desc[:600],311            images=imgs[: self.max_images + 1],312        )313
Files main
Menu

Theme