SPB Git

Repository Public

carre_legendes.py 9.1 KB 224 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/carre_legendes.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/carre_legendes.py : connecteur Carré des Légendes91#   (carredeslegendes.ca — Saint-Jean-sur-Richelieu, boul. Saint-Luc).92#   Condos locatifs haut de gamme (~7 bâtiments). WordPress rendu serveur :93#   la page /habitations/ embarque une carte SVG interactive (bâtiments →94#   niveaux → unités) dont TOUTES les données sont dans le HTML statique :95#   tooltip « disp / indisp » (Disponible, Réservée, Déjà louée) + bloc96#   « content level4 » (bâtiment, no d'unité, type | superficie, inclusions,97#   photos, plan PDF). Granularité : unité. Prix non publiés.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type106from .base import BaseConnector107108BASE = "https://carredeslegendes.ca"109PAGE_URL = f"{BASE}/habitations/"110111CITY = "Saint-Jean-sur-Richelieu"112113# « 4½ | 1240 pi. ca. »114TYPE_SQFT_RE = re.compile(r"([\dS][\d ½/]*)\s*\|\s*([\d\s]+)\s*pi", re.I)115BATIMENT_RE = re.compile(r"B[âa]timent\s*#?\s*(\d+)", re.I)116117118class CarreLegendesConnector(BaseConnector):119    source_id = "carre_legendes"120    request_delay = 0.6121122    def fetch(self) -> list[Listing]:123        listings: list[Listing] = []124        try:125            html = self.get(PAGE_URL).text126        except Exception:127            return listings128        soup = BeautifulSoup(html, "html.parser")129130        # 1) statut par unité : tooltips « ttip_<id> » (disp = encore offerte)131        status: dict[str, str] = {}132        for tip in soup.select("div.tooltip"):133            tid = (tip.get("id") or "").replace("ttip_", "")134            spans = [s.get_text(" ", strip=True) for s in tip.find_all("span")]135            if not tid or not spans or not spans[0].startswith("Unité"):136                continue137            classes = tip.get("class") or []138            if "disp" not in classes:139                continue          # « indisp » = déjà louée140            status[tid] = spans[1] if len(spans) > 1 else "Disponible"141142        # 2) fiches d'unités : blocs « content level4 » (content_<id>)143        for block in soup.select("div.content.level4"):144            bid = (block.get("id") or "").replace("content_", "")145            if bid not in status:146                continue147            try:148                infos = block.select_one("div.bottom_infos")149                if not infos:150                    continue151                h2 = infos.find("h2")152                unit_no = ""153                if h2:154                    m = re.search(r"(\d+)", h2.get_text(" ", strip=True))155                    if m:156                        unit_no = m.group(1)157                if not unit_no:158                    continue159                batiment = ""160                st = infos.select_one("p.sous-titre")161                if st:162                    m = BATIMENT_RE.search(st.get_text(" ", strip=True))163                    if m:164                        batiment = m.group(1)165166                unit_type, sqft = "", None167                h3 = block.find("h3")168                if h3:169                    m = TYPE_SQFT_RE.search(h3.get_text(" ", strip=True))170                    if m:171                        unit_type = normalize_unit_type(m.group(1))172                        try:173                            sqft = float(m.group(2).replace(" ", "")174                                         .replace(" ", ""))175                        except ValueError:176                            sqft = None177178                # inclusions de l'immeuble (paragraphe centré de la fiche)179                amenities: list[str] = []180                for p in infos.find_all("p"):181                    if "sous-titre" in (p.get("class") or []):182                        continue183                    txt = p.get_text("\n", strip=True)184                    amenities += [a.strip() for a in txt.split("\n")185                                  if 3 < len(a.strip()) < 80]186187                images = []188                for img in block.select("div.gallery img"):189                    src = img.get("src") or ""190                    if src.startswith("http"):191                        images.append(re.sub(r"-\d+x\d+(\.\w+)$", r"\1", src))192                plan = block.select_one("a.planpdf")193                details: dict = {}194                if plan and plan.get("href"):195                    details["plan_pdf"] = plan["href"]196                if batiment:197                    details["building"] = f"Bâtiment {batiment}"198199                ext_id = f"b{batiment or 'x'}-{unit_no}"200                listings.append(Listing(201                    source=self.source_id,202                    external_id=ext_id,203                    url=PAGE_URL,204                    title=f"Unité {unit_no} — Bâtiment {batiment}, "205                          f"Carré des Légendes" if batiment else206                          f"Unité {unit_no} — Carré des Légendes",207                    address="boulevard Saint-Luc, Saint-Jean-sur-Richelieu",208                    city=CITY,209                    unit_type=unit_type,210                    availability=status.get(bid, ""),211                    area_sqft=sqft,212                    amenities=list(dict.fromkeys(amenities))[:15],213                    details=details,214                    images=list(dict.fromkeys(images))[:15],215                ))216            except Exception:217                continue218219        # dédoublonner (le même content_<id> ne devrait sortir qu'une fois)220        uniq: dict[str, Listing] = {}221        for l in listings:222            uniq.setdefault(l.external_id, l)223        return list(uniq.values())224
Files main
Menu

Theme