SPB Git

Repository Public

lokalia.py 15.3 KB 367 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lokalia.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/lokalia.py : connecteur Espaces Lokalia (espaceslokalia.ca)91#   Le gestionnaire couvre plusieurs régions (Québec/Lévis + Grand Montréal :92#   Laval, Longueuil/Rive-Sud, Montérégie, Rive-Nord proche...)93#   -> on interroge l'endpoint AJAX WordPress `get_immeubles_map_data`94#   région par région (slugs découverts dans le filtre du site), ce qui donne95#   la ville par défaut ET les lat/lng structurés de chaque immeuble.96#   Page immeuble : adresse structurée (lien Google Maps sous le H1),97#   accordéons Inclusions / Équipements & sécurité / Aires communes,98#   description (paragraphes réels + promotion + « N unités • N étages »),99#   téléphone du bureau de location, grille « Prix et types d'unités ».100#   Une annonce par type d'unité offert dans chaque immeuble (les variantes101#   « + DEN » ou avec parenthèse gardent leur propre annonce).102#   Ni disponibilité ni superficie ne sont publiées par la source.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import re108import time109110from bs4 import BeautifulSoup111112from ..schema import Listing, infer_city, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://www.espaceslokalia.ca"116AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"117# slug de région (filtre du site) -> ville par défaut des immeubles118REGIONS = {119    # Région de Québec / Lévis120    "quebec": "Québec",121    "levis": "Lévis",122    # Laval123    "laval": "Laval",124    # Longueuil / Rive-Sud / Montérégie125    "longueuil": "Longueuil",126    "saint-hubert": "Longueuil",127    "brossard": "Brossard",128    "saint-lambert": "Saint-Lambert",129    "boucherville": "Boucherville",130    "saint-basile-le-grand": "Saint-Basile-le-Grand",131    "sainte-julie": "Sainte-Julie",132    "chambly": "Chambly",133    "saint-constant": "Saint-Constant",134    "delson": "Delson",135    "candiac": "Candiac",136    "chateauguay": "Châteauguay",137    "beauharnois": "Beauharnois",138    "salaberry-de-valleyfield": "Salaberry-de-Valleyfield",139    "granby": "Granby",140    # Rive-Nord proche141    "lachenaie": "Terrebonne",142    "terrebonne": "Terrebonne",143    "mascouche": "Mascouche",144    "saint-jerome": "Saint-Jérôme",145}146147# repli si le lien Google Maps sous le H1 est absent148ADDR_RE = re.compile(149    r"(?<![\d\)])\b\d{1,5}\s+(?:rue|route|rte|boulevard|bd\.?|avenue|av\.|"150    r"chemin|place|mont[ée]e|all[ée]e)\s[^,<>]{1,50},\s*[^,<>]{2,40},\s*"151    r"(?:QC|Qu[ée]bec)[^,<>]{0,12}(?:,\s*Canada)?", re.I)152IMG_RE = re.compile(r"https://www\.espaceslokalia\.ca/wp-content/uploads/"153                    r'[^"\s\\)]+\.(?:jpe?g|webp)', re.I)154155156def _slugify(s: str) -> str:157    return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-",158                                     s.lower().replace("½", ".5"))).strip("-")159160161class LokaliaConnector(BaseConnector):162    source_id = "lokalia"163    request_delay = 0.6164    max_buildings = 60       # garde-fou de crawl (toutes régions)165166    def _buildings(self) -> list[tuple[str, str, float | None, float | None]]:167        """Endpoint AJAX interrogé région par région168        -> [(url immeuble, ville par défaut, lat, lng), ...] dédupliqués."""169        out: list[tuple[str, str, float | None, float | None]] = []170        seen: set[str] = set()171        for region, city in REGIONS.items():172            try:173                time.sleep(self.request_delay)   # politesse (POST direct)174                resp = self.session.post(175                    AJAX_URL,176                    data={"action": "get_immeubles_map_data",177                          "regions": json.dumps([region])},178                    timeout=self.timeout,179                )180                resp.raise_for_status()181                items = resp.json()182            except Exception:183                continue184            for item in items:185                content = (item.get("list_content") or "") + \186                          (item.get("popup_content") or "")187                m = re.search(r'href="(https://www\.espaceslokalia\.ca/'188                              r'immeuble/[^"]+)"', content)189                if not m or m.group(1) in seen:190                    continue191                seen.add(m.group(1))192                # lat/lng structurés fournis par la carte193                lat = lng = None194                try:195                    lat = float(item.get("lat"))196                    lng = float(item.get("lng"))197                except (TypeError, ValueError):198                    lat = lng = None199                out.append((m.group(1), city, lat, lng))200        return out201202    def fetch(self) -> list[Listing]:203        listings: list[Listing] = []204        for url, default_city, lat, lng in self._buildings()[: self.max_buildings]:205            try:206                html = self.get(url).text207            except Exception:208                continue209            try:210                listings.extend(211                    self._parse_building(url, html, default_city, lat, lng))212            except Exception:213                continue214        return listings215216    def _parse_building(self, url: str, html: str, default_city: str = "Québec",217                        lat: float | None = None,218                        lng: float | None = None) -> list[Listing]:219        soup = BeautifulSoup(html, "html.parser")220        slug = url.rstrip("/").split("/")[-1]221        h1 = soup.find("h1")222        title = h1.get_text(" ", strip=True) if h1 else slug223        # « Appartements à louer à Lévis - Vivaxcès Le Nicolas » -> nom court224        name = title.split(" - ")[-1].split("│")[-1].strip() or slug225226        # Adresse structurée : lien Google Maps sous le H1227        address = ""228        wrap = soup.select_one(".category-wrapper a.description[href*='maps.google']")229        if wrap:230            address = re.sub(r"\s+", " ", wrap.get_text(" ", strip=True)).strip()231        if not address:232            text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))233            m = ADDR_RE.search(text)234            address = m.group(0).strip() if m else ""235        # étiquettes de la fiche (« Nouveau », « Promotion »)236        tags = [t.get_text(strip=True)237                for t in soup.select(".category-wrapper span.category")]238239        # secteur / ville : « 89 Rue du Doré-Jaune, Lachenaie, Terrebonne, QC »240        sector = ""241        city = default_city242        if address:243            parts = [p.strip() for p in address.split(",")]244            if len(parts) >= 2:245                sector = parts[1]246        city = infer_city(sector, default=city)247        if not sector and "Lévis" in title:248            city = "Lévis"249        if sector and sector.lower() == city.lower():250            sector = ""              # éviter secteur == ville (redondant)251252        # Description : paragraphes réels de la fiche + « N unités • N étages »253        # + promotion, sinon og:description en repli254        desc_bits: list[str] = []255        promo = soup.select_one(".promotion-main h2")256        if promo:257            desc_bits.append("Promotion : "258                             + promo.get_text(" ", strip=True))259        elif "Promotion" in tags:260            desc_bits.append("Promotion en cours")261        paras = [p.get_text(" ", strip=True)262                 for p in soup.select(".wx-single-description .description-left p")263                 if "wx-disclaimer" not in (p.get("class") or [])]264        if paras:265            desc_bits.append(" ".join(t for t in paras if t))266        size = soup.select_one(".wx-single-description .category-wrap span")267        if size:268            desc_bits.append(re.sub(r"\s+", " ", size.get_text(" ", strip=True)))269        if not desc_bits:270            og = soup.find("meta", attrs={"property": "og:description"})271            if og and og.get("content"):272                desc_bits.append(og["content"].strip())273        desc = " — ".join(b for b in desc_bits if b)[:700]274275        # Commodités : inclusions (icônes avec attribut title) + accordéons276        # « Équipements & sécurité » et « Aires communes » (items <li>)277        amenities = [el.get("title").strip()278                     for el in soup.select("div.icon-box[title]")279                     if el.get("title")]280        for acc_cls in ("equipment", "aires"):281            for li in soup.select(f"li.wx-single-accordion.{acc_cls} ul li"):282                t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))283                if t:284                    amenities.append(t)285        amenities = list(dict.fromkeys(a for a in amenities if a))[:30]286287        # Téléphone du bureau de location (lien tel:)288        details: dict = {}289        tel = soup.select_one('a[href^="tel:"]')290        if tel:291            num = re.sub(r"\D", "", tel.get("href", ""))292            num = num[1:] if len(num) == 11 and num.startswith("1") else num293            if len(num) == 10:294                details["contact"] = {"phone": f"{num[:3]}-{num[3:6]}-{num[6:10]}"}295296        # Photos (exclure icônes .png des inclusions)297        images = [u for u in dict.fromkeys(IMG_RE.findall(html))298                  if not re.search(r"logo|icon|favicon|-150x150", u, re.I)][:25]299300        # Types d'unités + prix : blocs .square-box (h5 = type, p = prix).301        # Dédupliqués par libellé BRUT : « 4 1/2 » et « 4 1/2 + DEN » restent302        # deux annonces (l'id de la 1re occurrence d'un type normalisé garde303        # son schéma historique ; les variantes reçoivent un suffixe du libellé).304        results: list[Listing] = []305        seen_raw: set[str] = set()306        seen_norm: set[str] = set()307        for box in soup.select("div.square-box"):308            h5 = box.find("h5")309            if not h5:310                continue311            unit_raw = re.sub(r"\s+", " ", h5.get_text(" ", strip=True)).strip()312            unit_type = normalize_unit_type(unit_raw)313            raw_key = _slugify(unit_raw)314            if not unit_type or not raw_key or raw_key in seen_raw:315                continue316            seen_raw.add(raw_key)317            if unit_type not in seen_norm:318                seen_norm.add(unit_type)319                ext_id = f"{slug}-{unit_type.replace('½', '.5')}"320            else:                     # variante (« + DEN », parenthèse…)321                ext_id = f"{slug}-{raw_key}"322            price_label = re.sub(r"\s+", " ",323                                 box.get_text(" ", strip=True)324                                 .replace(unit_raw, "", 1)).strip()325            pm = re.search(r"(?:À partir de\s*)?([\d\s]+)\$\s*/?\s*mois",326                           price_label)327            price_label = (f"À partir de {pm.group(1).strip()}$/mois"328                           if pm else price_label[:60])329            results.append(Listing(330                source=self.source_id,331                external_id=ext_id,332                url=url,333                title=f"{name} — {unit_raw}",334                address=address,335                sector=sector,336                city=city,337                unit_type=unit_type,338                price=parse_price(price_label),339                price_label=price_label,340                availability="",341                description=desc,342                amenities=amenities,343                details=dict(details),344                images=images,345                lat=lat,346                lng=lng,347            ))348349        # Immeuble sans grille de prix : annonce par immeuble quand même350        if not results:351            results.append(Listing(352                source=self.source_id,353                external_id=slug,354                url=url,355                title=name,356                address=address,357                sector=sector,358                city=city,359                description=desc,360                amenities=amenities,361                details=dict(details),362                images=images,363                lat=lat,364                lng=lng,365            ))366        return results367
Files main
Menu

Theme