SPB Git

Repository Public

la_cour.py 12.7 KB 299 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/la_cour.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# 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/la_cour.py : connecteur La Cour Appartements (lacourappartements.com)91#   155, rue du Prince-Édouard, Saint-Roch (Québec) — 159 unités sur 8 étages.92#   Site WordPress avec le plugin « do-selecteur-plans » (même plateforme que93#   le1070.ca / kwayaweh.ca côté Immostar, et que AULA Lévis) :94#     - page /plans/ : polygones SVG par unité (class disponible/indisponible,95#       data-nom = n° d'unité, data-etage, data-type, data-prix, data-promotion)96#     - REST /wp-json/do-selecteur-plans/v1/unite?id=<data-numero> : montant,97#       superficie habitable/terrasse, date de libération, inclusions par unité,98#       plan (galerie PNG + PDF)99#   La carte SVG (attributs data-*) sert de clé de cache BD (self.detail) : le100#   REST n'est re-frappé que si l'unité a changé depuis la dernière sync.101#   La classe est PARTAGÉE : AulaConnector (aula.py) en hérite et ne change102#   que les constantes du projet — le parsing est identique.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import hashlib107import json108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, infer_city, parse_price113from .base import BaseConnector114115# photos du projet dans wp-content/uploads (jamais les logos, icônes, plans,116# lettrages décoratifs ni les variantes redimensionnées -1536x864 etc.)117_IMG_RE = re.compile(118    r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+\.(?:jpg|jpeg|webp)',119    re.I)120_SKIP_IMG = re.compile(121    r"logo|icon|favicon|plan|selecteur|doodle|lettre|-\d{2,4}x\d{2,4}\.", re.I)122123124class LaCourConnector(BaseConnector):125    source_id = "la_cour"126    request_delay = 0.6127    max_rest_units = 90          # garde-fou : appels REST max par sync128    max_images = 10129130    # -- constantes du projet (surchargées par AulaConnector) ------------------131    BASE = "https://lacourappartements.com"132    PLANS_PATH = "plans/"133    NAME = "La Cour Appartements"134    ADDRESS = "155, rue du Prince-Édouard, Québec, G1K 5V6"135    SECTOR = "Saint-Roch"136    CITY = "Québec"137    PHOTO_PAGES = ("projet/",)   # pages crawlées pour les photos du projet138    AMENITY_PAGES = ()           # pages avec commodités (widgets Elementor/Jet)139140    # -- helpers ---------------------------------------------------------------141    def _site_images(self) -> list[str]:142        """Photos du projet (uploads jpg/webp des pages PHOTO_PAGES)."""143        imgs: list[str] = []144        for page in self.PHOTO_PAGES:145            try:146                html = self.get(f"{self.BASE}/{page}").text147            except Exception:148                continue149            for u in dict.fromkeys(_IMG_RE.findall(html)):150                if not _SKIP_IMG.search(u) and u not in imgs:151                    imgs.append(u)152        return imgs[: self.max_images]153154    def _project_amenities(self) -> list[str]:155        """Commodités du projet : items Jet Engine156        (.jet-listing-dynamic-repeater__item) des pages AMENITY_PAGES, plus les157        titres h6 Elementor de la première page (espaces communs). Les notes158        du genre « Disponible sur les étages… » sont ignorées."""159        items: list[str] = []160        for i, page in enumerate(self.AMENITY_PAGES):161            try:162                html = self.get(f"{self.BASE}/{page}").text163            except Exception:164                continue165            soup = BeautifulSoup(html, "html.parser")166            sel = ".jet-listing-dynamic-repeater__item"167            if i == 0:168                sel += ", h6.elementor-heading-title"169            for el in soup.select(sel):170                t = re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()171                if (3 <= len(t) <= 90 and t not in items172                        and not t.lower().startswith("disponible sur")):173                    items.append(t)174        return items[:30]175176    def _svg_cards(self, html: str) -> list[tuple[str, str, dict]]:177        """Unités disponibles du sélecteur SVG : (n° d'unité, post-id, data-*).178179        Chaque unité apparaît deux fois (polygone + bouton mobile) : dédup par180        n° d'unité. Les classes « indisponible » et « attente » sont exclues.181        """182        soup = BeautifulSoup(html, "html.parser")183        cards: list[tuple[str, str, dict]] = []184        seen: set[str] = set()185        for el in soup.select("[data-numero]"):186            cls = " ".join(el.get("class") or [])187            if not re.search(r"\bdisponible\b", cls) \188                    or re.search(r"indisponible|attente", cls):189                continue190            nom = (el.get("data-nom") or "").strip()191            pid = (el.get("data-numero") or "").strip()192            if not nom or not pid or nom in seen:193                continue194            seen.add(nom)195            attrs = {k: str(v) for k, v in el.attrs.items()196                     if k.startswith("data-")}197            attrs["class"] = cls198            cards.append((nom, pid, attrs))199        return cards200201    # -- fetch -----------------------------------------------------------------202    def fetch(self) -> list[Listing]:203        html = self.get(f"{self.BASE}/{self.PLANS_PATH}").text204        cards = self._svg_cards(html)205        images = self._site_images()206        project_amenities = self._project_amenities()207        rest_calls = 0208209        out: list[Listing] = []210        for nom, pid, attrs in cards[: self.max_rest_units]:211            def _fetch(p=pid):212                nonlocal rest_calls213                if rest_calls >= self.max_rest_units:214                    raise RuntimeError("budget de requêtes REST atteint")215                rest_calls += 1216                return self.get(217                    f"{self.BASE}/wp-json/do-selecteur-plans/v1/unite",218                    params={"id": p}).json()219            try:220                # clé de cache BD = attributs SVG (prix/type/promo/état) : le221                # REST n'est appelé que si l'unité est nouvelle ou modifiée222                key = hashlib.sha1(json.dumps(223                    attrs, sort_keys=True).encode()).hexdigest()[:20]224                data = self.detail(nom, key, _fetch)225            except Exception:226                continue227            if not data or data.get("etat") != "disponible":228                continue229230            t = str(data.get("type") or attrs.get("data-type") or "")231            sup = str(data.get("superficie_habitable") or "").strip()232            terrasse = str(data.get("superficie_terrasse") or "").strip()233            etage = (attrs.get("data-etage") or "").strip()234235            # disponibilité : date de libération (« | Janvier 2027 ») sinon236            # le libellé « a_partir » (« Libre le 8 août 2026 » / « Libre »)237            date_libre = str(data.get("date_libre") or "").strip(" |")238            a_partir = str(data.get("a_partir") or "").strip()239            avail = (f"Libre {date_libre}" if date_libre240                     else a_partir or "Disponible")241242            # prix : montant REST (« 1 453 $ »), repli sur data-prix du SVG243            montant = str(data.get("montant") or "").strip()244            if not montant and (attrs.get("data-prix") or "").strip():245                montant = f"{attrs['data-prix'].strip()} $"246            price_label = f"{montant} par mois" if montant else ""247248            desc = " — ".join(x for x in [249                t, f"{sup} pi²" if sup else "",250                f"terrasse {terrasse} pi²" if terrasse else "",251                f"étage {etage}" if etage else ""] if x)252253            # inclusions par unité (La Cour) + commodités du projet (AULA)254            amenities = [str(a).strip() for a in (data.get("inclusion") or [])255                         if str(a).strip()]256            amenities += [a for a in project_amenities if a not in amenities]257258            # plan de l'unité (galerie REST) en tête des photos du projet259            imgs = list(images)260            for g in reversed(data.get("gallery") or []):261                gu = g.get("url") if isinstance(g, dict) else str(g or "")262                if gu.startswith("http") and gu not in imgs:263                    imgs.insert(0, gu)264265            details: dict = {}266            if etage.isdigit():267                details["floor"] = int(etage)268            pdf = str(data.get("pdf") or "")269            if pdf.startswith("http"):270                details["plan_pdf"] = pdf271272            sup_val = None273            try:274                v = float(sup.replace(" ", "").replace(",", "."))275                if 80 <= v <= 20000:276                    sup_val = v277            except ValueError:278                pass279280            out.append(Listing(281                source=self.source_id,282                external_id=nom,283                url=f"{self.BASE}/{self.PLANS_PATH}#unite-{nom}",284                title=f"{self.NAME} — Unité {nom}",285                address=self.ADDRESS,286                sector=self.SECTOR,287                city=infer_city(self.SECTOR, default=self.CITY),288                unit_type=t,289                price=parse_price(montant),290                price_label=price_label,291                availability=avail,292                area_sqft=sup_val,293                description=desc[:600],294                amenities=amenities[:30],295                details=details,296                images=imgs[: self.max_images + 3],297            ))298        return out299
Files main
Menu

Theme