SPB Git

Repository Public

lakle.py 18.2 KB 427 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lakle.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-1814#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/lakle.py : connecteur La Klé (lakle.ca)91#   Complexe de 559 appartements locatifs (4 phases) dans la Cité Verte92#   (Québec, secteur Saint-Sacrement). La page « disponibilité » expose :93#   1) le sélecteur de plans WordPress de la tour la plus récente (phase 4) :94#      unités en <polygon class="disponible" data-numero=...> + API REST95#      /wp-json/do-selecteur-plans/v1/unite?id=N (prix, type, superficie96#      habitable/terrasse, étage, style, date libre, plan) ;97#   2) des cartes <li> « Unité B16 - Phase 3 » pour les unités disponibles98#      des phases 2 et 3 (superficie, chambres, description, plan — AUCUN99#      prix publié pour ces unités chez la source : rien d'inventé).100#   La page /contact fournit l'adresse civique et le lat/lng de chaque phase101#   (marqueurs Google Map structurés). La page /appartements/ fournit les102#   photos types du complexe (piscine, intérieurs) — ajoutées à la galerie de103#   chaque unité, la source n'ayant qu'un plan/une photo par unité.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, parse_price112from .base import BaseConnector113114BASE = "https://lakle.ca"115PAGE_URL = f"{BASE}/phase-1-occupation-immediate/"116CONTACT_URL = f"{BASE}/contact/"117APPARTS_URL = f"{BASE}/appartements/"118PROJET_URL = f"{BASE}/la-kle-projet/"119API_URL = f"{BASE}/wp-json/do-selecteur-plans/v1/unite"120SECTOR = "Cité Verte (Saint-Sacrement)"121CITY = "Québec"122123# le sélecteur de plans correspond à la tour phase 4 (calendly « la-kle-phase-4 »,124# visuels « phase-4 » — le slug « phase-1 » de l'URL est historique)125SELECTOR_PHASE = 4126127# adresses par phase (page /contact) — repli si la page devient inaccessible128_FALLBACK_PHASES: dict[int, dict] = {129    1: {"address": "1190, Louis-Adolphe-Robitaille, Québec, G1S 0C2"},130    2: {"address": "1180, Louis-Adolphe Robitaille, Québec, G1S 0C7"},131    3: {"address": "475, avenue Ernest-Gagnon, Québec, G1S 0E4"},132    4: {"address": "Avenue Ernest-Gagnon, Québec, G1S 0E4"},133}134135# inclusions du complexe (« Toutes les unités incluent », lakle.ca accueil)136_BUILDING_AMENITIES = [137    "Électroménagers inclus",138    "Électricité incluse",139    "Chauffage et climatisation centrale",140    "Accès à la piscine intérieure",141    "Accès à la salle d'entraînement",142    "Toiles solaires dans les fenêtres",143    "Espaces à vélos intérieurs sécurisés",144    "Stationnement intérieur sécurisé (en option)",145    "Interphone à l'entrée de l'immeuble",146    "Accès avec puce électronique",147    "Caméras de surveillance",148]149150151class LaKleConnector(BaseConnector):152    source_id = "lakle"153    request_delay = 0.5154    max_units = 120           # garde-fou155156    # -- adresses / coordonnées par phase (page contact) -----------------------157    def _phase_info(self) -> dict[int, dict]:158        """{phase: {address, lat, lng}} depuis les marqueurs de /contact."""159        info = {k: dict(v) for k, v in _FALLBACK_PHASES.items()}160        try:161            soup = BeautifulSoup(self.get(CONTACT_URL).text, "html.parser")162        except Exception:163            return info164        for mk in soup.select(".ts-advanced-google-map-marker-single"):165            m = re.search(r"phase\s*(\d)", mk.get("data-title") or "", re.I)166            if not m:167                continue168            phase = int(m.group(1))169            entry = info.setdefault(phase, {})170            try:171                entry["lat"] = float(mk["data-latitude"])172                entry["lng"] = float(mk["data-longitude"])173            except (KeyError, ValueError):174                pass175            # contenu du popup : « Phase 3 | 475 Ernest-Gagnon | Ville de176            # Québec | QC G1S 0E4 »177            lignes = [t for t in mk.stripped_strings178                      if not re.match(r"phase\s*\d", t, re.I)]179            if lignes:180                addr = ", ".join(lignes)181                addr = addr.replace("Ville de Québec", "Québec")182                addr = re.sub(r"\bQC\s+", "", addr)183                entry["address"] = addr184        return info185186    # -- photos types du complexe (page /appartements/) -------------------------187    def _complex_photos(self) -> list[str]:188        try:189            html = self.get(APPARTS_URL).text190        except Exception:191            return []192        photos: list[str] = []193        for u in re.findall(r'(?:src|href)="((?:https:)?//lakle\.ca'194                            r'/wp-content/uploads/[^"]+\.(?:jpg|jpeg|webp))"',195                            html, re.I):196            if u.startswith("//"):197                u = "https:" + u198            u = re.sub(r"-\d{2,4}x\d{2,4}(?=\.\w+$)", "", u)199            if re.search(r"logo|favicon|icon", u, re.I):200                continue201            if u not in photos:202                photos.append(u)203        return photos[:6]204205    # -- prose de présentation du complexe (page /la-kle-projet/) ---------------206    def _project_blurb(self) -> str:207        try:208            soup = BeautifulSoup(self.get(PROJET_URL).text, "html.parser")209        except Exception:210            return ""211        paras: list[str] = []212        for p in soup.find_all("p"):213            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))214            if 120 < len(t) < 600 and "Cromwell" not in t and t not in paras:215                paras.append(t)216            if len(paras) >= 2:217                break218        return " ".join(paras)[:600]219220    # -- unités du sélecteur de plans (tour phase 4) ---------------------------221    def _selector_listings(self, html: str, phases: dict) -> list[Listing]:222        units: list[dict] = []223        for poly in re.findall(r"<polygon[^>]*>", html):224            if 'class="disponible"' not in poly:225                continue226            attrs = dict(re.findall(r'data-([a-z-]+)="([^"]*)"', poly))227            if attrs.get("numero"):228                units.append(attrs)229230        loc = phases.get(SELECTOR_PHASE, {})231        listings: list[Listing] = []232        seen: set[str] = set()233        for attrs in units[:self.max_units]:234            uid = attrs["numero"]235            if uid in seen:236                continue237            seen.add(uid)238            try:239                data = self.get(API_URL, params={"id": uid}).json()240            except Exception:241                data = {}242            try:243                if data.get("etat") not in ("disponible", None):244                    continue245                unit_no = data.get("unite") or uid246                raw_type = data.get("type") or attrs.get("type", "")247                unit_type = normalize_unit_type(raw_type)248249                price_label = (data.get("montant") or "").strip()250                if data.get("montant_suffixe"):251                    price_label = f"{price_label} {data['montant_suffixe']}".strip()252                price = parse_price(price_label)253                if price is None and attrs.get("prix"):254                    price = parse_price(attrs["prix"] + "$")255                    price_label = price_label or f"{attrs['prix']}$"256257                availability = (data.get("a_partir")258                                or data.get("date_libre")259                                or data.get("etat_titre")260                                or "Disponible")261262                # superficie habitable structurée (l'API distingue la terrasse)263                area_sqft = None264                try:265                    area_sqft = float(str(data.get("superficie_habitable"))266                                      .replace(" ", "").replace(",", "."))267                except (TypeError, ValueError):268                    pass269270                details: dict = {}271                etage = attrs.get("etage")272                if etage and etage.isdigit():273                    details["floor"] = int(etage)274275                desc_parts = []276                if data.get("nb_chambres"):277                    desc_parts.append(f"{data['nb_chambres']} chambre(s)")278                if data.get("superficie_habitable"):279                    desc_parts.append(280                        f"Superficie {data['superficie_habitable']} "281                        f"{data.get('superficie_suffixe', 'pi²')}")282                if data.get("superficie_terrasse"):283                    desc_parts.append(284                        f"{data.get('type_balcon', 'balcon').capitalize()} "285                        f"{data['superficie_terrasse']} "286                        f"{data.get('superficie_suffixe', 'pi²')}")287                if data.get("style"):288                    desc_parts.append(f"Style {data['style']}")289                if etage:290                    desc_parts.insert(0, f"Étage {etage}")291                if data.get("pdf"):292                    desc_parts.append(f"Plan PDF : {data['pdf']}")293294                amenities = list(_BUILDING_AMENITIES)295                promo = data.get("promotion") or attrs.get("promotion")296                if promo:297                    amenities.append(f"Promotion : {promo}")298299                images = [u for u in (data.get("gallery") or [])300                          if isinstance(u, str)301                          and re.search(r"\.(?:jpg|jpeg|png|webp)$", u, re.I)]302                images += [u for u in self._photos if u not in images]303304                listings.append(Listing(305                    source=self.source_id,306                    external_id=str(uid),307                    url=PAGE_URL,308                    title=f"La Klé — Unité {unit_no}"309                          f"{' (' + unit_type + ')' if unit_type else ''}",310                    address=loc.get("address", "Cité Verte, Québec"),311                    sector=SECTOR,312                    city=CITY,313                    unit_type=unit_type,314                    price=price,315                    price_label=price_label,316                    availability=availability,317                    area_sqft=area_sqft,318                    description=(" | ".join(desc_parts)319                                 + (f"\n{self._blurb}" if self._blurb else "")),320                    amenities=amenities,321                    details=details,322                    images=images,323                    lat=loc.get("lat"),324                    lng=loc.get("lng"),325                ))326            except Exception:327                continue328        return listings329330    # -- cartes des phases 2 et 3 (« Unité B16 - Phase 3 ») --------------------331    def _card_listings(self, soup: BeautifulSoup, phases: dict) -> list[Listing]:332        listings: list[Listing] = []333        ul = soup.select_one("ul.liste-unite-disponible")334        if ul is None:335            return listings336        for li in ul.find_all("li", recursive=False):337            try:338                h4 = li.select_one(".informations-unite h4")339                if not h4:340                    continue341                strong = h4.find("strong")342                name = strong.get_text(" ", strip=True) if strong else ""343                name = re.sub(r"^Unité\s+", "", name).strip()344                if not name:345                    continue346                span = h4.find("span")347                phase = None348                if span:349                    m = re.search(r"phase\s*(\d)", span.get_text(), re.I)350                    if m:351                        phase = int(m.group(1))352                loc = phases.get(phase, {}) if phase else {}353354                # « 1214pi² - 3 chambres »355                tech_el = li.select_one(".informations-technique")356                tech = " ".join(tech_el.get_text(" ", strip=True).split()) \357                    if tech_el else ""358                unit_type = normalize_unit_type(tech)359360                # description : « Disponible en octobre … » + texte marketing361                desc_lines: list[str] = []362                availability = ""363                p = li.select_one(".informations-unite p")364                if p:365                    for seg in p.stripped_strings:366                        seg = " ".join(seg.split())367                        if not availability and re.match(r"disponible\b", seg, re.I):368                            availability = seg.rstrip("!").strip()369                        desc_lines.append(seg)370                desc_parts = ([tech] if tech else []) + desc_lines371                plan = li.select_one("a.btn-voir-plan[href]")372                if plan:373                    desc_parts.append(f"Plan PDF : {plan['href']}")374375                images = []376                gal = li.select_one("a[data-gallery], .image-apercu a[href]")377                if gal:378                    for u in re.split(r"[,\s]+", gal.get("data-gallery")379                                      or gal.get("href") or ""):380                        if re.search(r"\.(?:jpg|jpeg|png|webp)$", u, re.I):381                            images.append(u)382                images += [u for u in self._photos if u not in images]383384                slug = re.sub(r"-+", "-",385                              re.sub(r"[^a-z0-9]+", "-", name.lower())).strip("-")386                titre_phase = f" (Phase {phase})" if phase else ""387                listings.append(Listing(388                    source=self.source_id,389                    external_id=f"p{phase or 'x'}-{slug}",390                    url=PAGE_URL,391                    title=f"La Klé — Unité {name}{titre_phase}",392                    address=loc.get("address", "Cité Verte, Québec"),393                    sector=SECTOR,394                    city=CITY,395                    unit_type=unit_type,396                    price=None,               # aucun prix affiché pour ces unités397                    price_label="",398                    # la liste s'intitule « Découvrez nos unités disponibles »399                    availability=availability or "Disponible",400                    description=(" | ".join(desc_parts)401                                 + (f"\n{self._blurb}" if self._blurb else "")),402                    amenities=list(_BUILDING_AMENITIES),403                    images=list(dict.fromkeys(images)),404                    lat=loc.get("lat"),405                    lng=loc.get("lng"),406                ))407            except Exception:408                continue409        return listings410411    # -- contrat ---------------------------------------------------------------412    def fetch(self) -> list[Listing]:413        html = self.get(PAGE_URL).text414        soup = BeautifulSoup(html, "html.parser")415        phases = self._phase_info()416        self._photos = self._complex_photos()417        self._blurb = self._project_blurb()418419        listings = self._selector_listings(html, phases)420        listings.extend(self._card_listings(soup, phases))421422        # dédup par uid (prudence si une unité apparaît deux fois)423        uniq: dict[str, Listing] = {}424        for lst in listings:425            uniq.setdefault(lst.external_id, lst)426        return list(uniq.values())427
Files main
Menu

Theme