SPB Git

Repository Public

laberge.py 16.1 KB 381 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/laberge.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/laberge.py : connecteur Gestion immobilière Laberge (laberge.qc.ca)91#   Site rendu serveur. La page /recherche liste tous les complexes avec, pour92#   chacun, un tableau des types d'unités ; les lignes cliquables93#   (data-href="/complexe/{slug}/appartement/{code}") sont les unités94#   disponibles. Une annonce par unité disponible ; la fiche unité fournit95#   les photos, le secteur, la superficie, la description et les inclusions.96#   Région retenue : Québec / Lévis / L'Ancienne-Lorette (les complexes de la97#   région de Montréal — Côte St-Luc, LaSalle, Pierrefonds, etc. — sont exclus).98#   Les fiches unités sont visitées via self.detail() (cache BD, max99#   max_details nouveaux fetchs par synchronisation).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105from urllib.parse import urljoin106107from bs4 import BeautifulSoup108109from ..schema import Listing, infer_city, normalize_unit_type, parse_price, strip_accents110from .base import BaseConnector111112BASE = "https://www.laberge.qc.ca"113SEARCH_URL = f"{BASE}/recherche"114115# villes de la région Québec/Lévis retenues (normalisées sans accents)116ALLOWED_CITIES = {117    "quebec", "levis", "l'ancienne-lorette", "ancienne-lorette",118    "saint-augustin-de-desmaures", "st-augustin-de-desmaures",119}120121IMG_RE = re.compile(r"^/image/\d+/\d+/")122EXCLUDE_UNIT_RE = re.compile(r"stationnement|parking|rangement|commercial|garage", re.I)123124# pictogrammes dont le libellé texte est générique ("Inclus")125_PICTO_NAMES = {126    "poele--frigo": "Poêle et réfrigérateur",127    "entree_laveuse_secheuse": "Entrée laveuse-sécheuse",128    "laveuse_secheuse": "Laveuse-sécheuse",129    "lave-vaisselle": "Lave-vaisselle",130    "lv": "Lave-vaisselle",131    "micro-onde": "Micro-ondes",132    "air_climatise": "Air climatisé",133}134135136class _DetailBudget(Exception):137    """Budget de fiches unités atteint pour cette synchronisation."""138139140class LabergeConnector(BaseConnector):141    source_id = "laberge"142    request_delay = 0.6143    max_details = 150         # garde-fou : nb max de fiches unités visitées144    max_images = 25145146    # -- helpers ---------------------------------------------------------------147    @staticmethod148    def _card_address_city(card) -> tuple[str, str]:149        """Adresse civique + ville depuis la carte complexe de /recherche."""150        p = card.select_one(".bg-white p")151        if not p:152            return "", ""153        for a in p.find_all("a"):          # retirer le lien téléphone154            a.decompose()155        addr = p.get_text(" ", strip=True)156        # ex. « 224, rue seigneuriale, Québec, G1E 0M8 »157        m = re.search(r"^(.*?),\s*([^,]+?),?\s*[A-Z]\d[A-Z]\s*\d[A-Z]\d", addr)158        if m:159            return m.group(1).strip(), m.group(2).strip()160        parts = [x.strip() for x in addr.split(",") if x.strip()]161        if len(parts) >= 2:162            return ", ".join(parts[:-1]), parts[-1]163        return addr, ""164165    @staticmethod166    def _picto_labels(container) -> list[str]:167        """Libellés des pictogrammes non grisés (grisé = exclu/absent)."""168        labels: list[str] = []169        for cell in container.select("div.text-center"):170            p = cell.find("p")171            img = cell.find("img")172            if p is None:173                continue174            style = p.get("style") or ""175            src = (img.get("src") or "") if img else ""176            if "#ccc" in style or "_off." in src:177                continue  # service exclu (picto grisé)178            label = p.get_text(" ", strip=True)179            if not label or label.lower() == "inclus":180                stem = src.rsplit("/", 1)[-1].rsplit(".", 1)[0]181                label = _PICTO_NAMES.get(stem, stem.replace("_", " ")182                                         .replace("--", " ").replace("-", " ")183                                         .strip().capitalize())184            if label and label not in labels:185                labels.append(label)186        return labels187188    def _fetch_detail(self, url: str) -> dict:189        """Fiche unité -> payload JSON-sérialisable (mis en cache BD)."""190        html = self.get(url).text191        soup = BeautifulSoup(html, "html.parser")192        payload: dict = {}193194        # secteur depuis le <title> : « Appartement - Beauport - Le 224 #… »195        if soup.title:196            parts = soup.title.get_text(strip=True).split(" - ")197            if len(parts) >= 2 and parts[0].lower().startswith("appartement"):198                payload["sector"] = parts[1].strip()199200        # photos de l'unité (URLs absolues)201        imgs = []202        for img in soup.find_all("img"):203            src = img.get("src") or img.get("data-src") or ""204            if IMG_RE.match(src):205                imgs.append(urljoin(BASE, src))206        payload["images"] = list(dict.fromkeys(imgs))[: self.max_images]207208        # bloc « Grandeur / Étage / Disponibilité / Superficie / Débutant » :209        # paires h3 -> p structurées de la fiche210        for block in soup.select(".caracteristiques-appart.description-appart"):211            for h3 in block.find_all("h3"):212                label = h3.get_text(" ", strip=True).lower()213                val_el = h3.find_next_sibling("p")214                if not val_el:215                    continue216                val = " ".join(val_el.get_text(" ", strip=True).split())217                if label.startswith("superficie"):218                    m = re.search(r"([\d\s.,]+?)\s*pi", val)219                    if m:220                        try:221                            payload["area_sqft"] = float(222                                m.group(1).replace(" ", "").replace(",", "."))223                        except ValueError:224                            pass225                elif label.startswith("étage") or label.startswith("etage"):226                    if val.isdigit():227                        payload["floor"] = int(val)228                elif label.startswith("disponibilit"):229                    payload["availability"] = val230231        # description (paragraphe sous le h2 « Description »)232        for h2 in soup.find_all("h2"):233            if h2.get_text(strip=True).lower().startswith("description"):234                sib = h2.find_next("p")235                if sib:236                    desc = sib.get_text(" ", strip=True)237                    if len(desc) > 40:238                        payload["description"] = desc[:600]239                        break240241        amenities: list[str] = []242        # inclusions de l'unité (pictos non grisés = inclus)243        for block in soup.select(".caracteristiques-appart"):244            for label in self._picto_labels(block):245                if label not in amenities:246                    amenities.append(label)247            # caractéristiques en liste (« Entrée laveuse, sécheuse »,248            # « Balcon privé : 1 », « Stationnement extérieur : … »)249            for li in block.select("ul li"):250                label = " ".join(li.get_text(" ", strip=True).split())251                if label and label not in amenities:252                    amenities.append(label)253254        # services de l'immeuble + dispositifs de sécurité (pictos non grisés)255        for h2 in soup.find_all("h2"):256            titre = h2.get_text(strip=True).lower()257            if titre.startswith(("services de l", "dispositifs de s")):258                parent = h2.find_parent("div")259                row = parent.parent if parent else None260                if row is None:261                    continue262                for label in self._picto_labels(row):263                    if label not in amenities:264                        amenities.append(label)265        payload["amenities"] = amenities266267        # adresse complète de l'immeuble (avec code postal) : h3 « Adresse »268        for h3 in soup.find_all("h3"):269            if h3.get_text(strip=True).lower() == "adresse":270                p = h3.find_next_sibling("p")271                if p:272                    for a in p.find_all("a"):   # lien « Autres adresses »273                        a.decompose()274                    lignes = [" ".join(x.split()) for x in p.stripped_strings]275                    if lignes:276                        payload["address"] = ", ".join(lignes)277                break278        return payload279280    def _enrich_from_detail(self, lst: Listing) -> None:281        """Complète l'annonce avec la fiche unité (via cache self.detail)."""282        key = hashlib.sha1(283            f"{lst.unit_type}|{lst.price_label}|{lst.availability}"284            .encode("utf-8")).hexdigest()285286        def fetch_fn():287            if self._detail_fetches >= self.max_details:288                raise _DetailBudget()289            self._detail_fetches += 1290            return self._fetch_detail(lst.url)291292        try:293            payload = self.detail(lst.external_id, key, fetch_fn)294        except _DetailBudget:295            return296        if not payload:297            return298299        if payload.get("sector"):300            lst.sector = payload["sector"]301            lst.city = infer_city(lst.sector, default=lst.city or "Québec")302        if payload.get("images"):303            lst.images = payload["images"]304        if payload.get("address"):305            lst.address = payload["address"]306        if payload.get("description"):307            lst.description = payload["description"]308        if payload.get("amenities"):309            lst.amenities = payload["amenities"]310        if payload.get("area_sqft"):311            lst.area_sqft = payload["area_sqft"]   # structuré à la source312        if payload.get("floor"):313            lst.details["floor"] = payload["floor"]314        if payload.get("availability") and not lst.availability:315            lst.availability = payload["availability"]316317    # -- contrat ---------------------------------------------------------------318    def fetch(self) -> list[Listing]:319        html = self.get(SEARCH_URL).text320        soup = BeautifulSoup(html, "html.parser")321322        listings: dict[str, Listing] = {}323        for card in soup.select(".un-appart"):324            try:325                link = card.select_one("a.title-link")326                if not link or not link.get("href"):327                    continue328                slug = link["href"].rstrip("/").rsplit("/", 1)[-1]329                name_el = link.find(["h2", "h3"])330                complex_name = (name_el.get_text(" ", strip=True)331                                if name_el else slug.replace("-", " ").title())332333                address, city = self._card_address_city(card)334                city_key = strip_accents(city.lower().strip())335                if city_key not in ALLOWED_CITIES:336                    continue  # hors région Québec/Lévis (ex. Montréal)337338                # lignes cliquables du tableau = unités disponibles339                for row in card.select("tr.clickable-row[data-href]"):340                    cells = [td.get_text(" ", strip=True)341                             for td in row.find_all("td")]342                    if len(cells) < 3:343                        continue344                    unit_type_raw, price_raw, avail_raw = cells[0], cells[1], cells[2]345                    if EXCLUDE_UNIT_RE.search(unit_type_raw):346                        continue347                    href = row["data-href"]348                    unit_code = href.rstrip("/").rsplit("/", 1)[-1]349                    ext_id = f"{slug}-{unit_code}"350                    if ext_id in listings:351                        continue352                    avail = re.sub(r"\s*chevron_right\s*$", "",353                                   avail_raw).strip()354                    listings[ext_id] = Listing(355                        source=self.source_id,356                        external_id=ext_id,357                        url=urljoin(BASE, href),358                        title=f"{complex_name} — {unit_type_raw} (#{unit_code})",359                        address=address,360                        sector="",361                        city=city,362                        unit_type=normalize_unit_type(unit_type_raw),363                        price=parse_price(price_raw),364                        price_label=price_raw,365                        availability=avail,366                    )367            except Exception:368                continue  # carte malformée : on passe à la suivante369370        # fiches détaillées (photos, secteur, description, inclusions) —371        # via self.detail() : seules les unités nouvelles/modifiées sont372        # réellement visitées (max self.max_details par synchronisation)373        self._detail_fetches = 0374        for lst in listings.values():375            try:376                self._enrich_from_detail(lst)377            except Exception:378                continue379380        return list(listings.values())381
Files main
Menu

Theme