SPB Git

Repository Public

lobato.py 10.0 KB 248 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lobato.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/lobato.py : connecteur Groupe Lobato (groupelobato.com —91#   promoteur/gestionnaire de la vallée du Richelieu : Beloeil,92#   McMasterville, Mont-Saint-Hilaire, Saint-Jean-sur-Richelieu).93#   WordPress (thème Vortex Solution) rendu serveur : chaque page94#   /project/<slug>/ contient un tableau HTML des unités (Unit | Bed. |95#   S.F | Price | Availability | Plan). Seules les lignes « Available »96#   sont retenues ; les locaux « Commercial » du Carrefour Laurier sont97#   exclus. Granularité = UNITÉ. external_id = <slug-projet>-<slug-unité>98#   (slug du lien /unit/ si présent, sinon nom affiché slugifié).99#   Colonne Bed. hétérogène : « 1 », « 2 », « 3 », « 1 + den », « 4 1/2 ».100#   Photos servies via le proxy PhastPress (phast.php/<base64>.q.jpg) —101#   on décode le base64 pour retrouver l'URL wp-content/uploads originale.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import base64106import html as _html107import re108from urllib.parse import unquote109110from ..schema import Listing111from .base import BaseConnector112113BASE = "https://groupelobato.com"114115# (slug de page projet, nom du projet, adresse, ville)116PROJECTS: tuple[tuple[str, str, str, str], ...] = (117    ("beloeil-faubourg-du-richelieu", "Le Faubourg du Richelieu",118     "2000, rue Richelieu, Beloeil", "Beloeil"),119    ("carrefour-laurier", "Carrefour Laurier",120     "831, boulevard Laurier, McMasterville", "McMasterville"),121    ("mont-st-hilaire-condos-a-louer-2", "Condos rue de la Sucrerie",122     "rue de la Sucrerie, Mont-Saint-Hilaire", "Mont-Saint-Hilaire"),123    ("mcmasterville-rue-constable", "781-783, rue Constable",124     "781-783, rue Constable, McMasterville", "McMasterville"),125    ("havre-du-richelieu-condos-a-louer", "Havre du Richelieu",126     "81-83, rue Richelieu, Saint-Jean-sur-Richelieu",127     "Saint-Jean-sur-Richelieu"),128)129130ROW_RE = re.compile(r"<tr[^>]*>[\s\S]*?</tr>", re.I)131CELL_RE = re.compile(r"<td[^>]*>([\s\S]*?)</td>", re.I)132UNIT_LINK_RE = re.compile(r'href="https://groupelobato\.com/unit/([^/"]+)/?"')133PDF_RE = re.compile(134    r'href="(https://groupelobato\.com/wp-content/uploads/[^"]+\.pdf)"', re.I)135TAG_RE = re.compile(r"<[^>]+>")136PHAST_RE = re.compile(r"phast\.php/([A-Za-z0-9_=-]+)\.q\.(?:jpe?g|png|webp)",137                      re.I)138SIZE_SUFFIX_RE = re.compile(r"-\d+x\d+(\.(?:jpe?g|png|webp))$", re.I)139140141def _clean(txt: str) -> str:142    return re.sub(r"\s+", " ", _html.unescape(TAG_RE.sub(" ", txt))).strip()143144145def _slug(txt: str) -> str:146    return re.sub(r"[^a-z0-9]+", "-", txt.lower()).strip("-")147148149def _images(html: str) -> list[str]:150    """Décode les URLs PhastPress -> originaux wp-content/uploads (photos)."""151    urls: list[str] = []152    for tok in dict.fromkeys(PHAST_RE.findall(html)):153        try:154            raw = base64.urlsafe_b64decode(155                tok + "=" * (-len(tok) % 4)).decode("utf-8", "replace")156        except Exception:157            continue158        m = re.search(r"src=([^&]+)", raw)159        if not m:160            continue161        u = unquote(m.group(1))162        if "/wp-content/uploads/" not in u:163            continue                          # images de thème/icônes164        if re.search(r"logo|icon|favicon", u, re.I):165            continue166        u = SIZE_SUFFIX_RE.sub(r"\1", u)      # variante -WxH -> original167        if u not in urls:168            urls.append(u)169    return urls[:10]170171172class LobatoConnector(BaseConnector):173    source_id = "lobato"174    request_delay = 0.8175176    def fetch(self) -> list[Listing]:177        listings: list[Listing] = []178        seen: set[str] = set()179        for slug, name, address, city in PROJECTS:180            url = f"{BASE}/project/{slug}/"181            try:182                html = self.get(url).text183            except Exception:184                continue185            images = _images(html)186            for row in ROW_RE.finditer(html):187                chunk = row.group(0)188                cells = CELL_RE.findall(chunk)189                if len(cells) < 5:190                    continue191                unit = _clean(cells[0])192                beds_txt = _clean(cells[1])193                sf_txt = _clean(cells[2])194                price_txt = _clean(cells[3])195                avail_txt = _clean(cells[4])196                if not unit or "commercial" in unit.lower():197                    continue                      # local commercial exclu198                if not re.search(r"\bAvailable\b", avail_txt, re.I):199                    continue                      # unité louée (Leased)200201                lm = UNIT_LINK_RE.search(cells[0])202                ext_id = f"{slug}-{lm.group(1) if lm else _slug(unit)}"203                if ext_id in seen:204                    continue205                seen.add(ext_id)206207                price = None208                pm = re.search(r"(\d[\d\s  ]{2,8})\$", price_txt)209                if pm:210                    price = float(re.sub(r"[\s  ]", "", pm.group(1)))211                area = None212                am = re.search(r"(\d{3,5})", sf_txt.replace(" ", ""))213                if am:214                    area = float(am.group(1))215216                bedrooms = None217                unit_type = ""218                bm = re.match(r"^(\d+)(?:\s*\+\s*den)?$", beds_txt, re.I)219                if bm:220                    bedrooms = float(bm.group(1))221                    if "den" in beds_txt.lower():222                        unit_type = f"{bm.group(1)} ch. + den"223                elif re.match(r"^\d+\s*1/2$", beds_txt):224                    unit_type = beds_txt          # « 4 1/2 » -> finalize225226                pdf = PDF_RE.search(chunk)227228                listings.append(Listing(229                    source=self.source_id,230                    external_id=ext_id,231                    url=url,232                    title=f"{name} — unité {unit}",233                    address=address,234                    city=city,235                    unit_type=unit_type,236                    bedrooms=bedrooms,237                    price=price,238                    price_label=price_txt if price else "",239                    availability="Disponible",240                    area_sqft=area,241                    description=f"Unité {unit} au {name} ({address}) — "242                                "immeuble locatif du Groupe Lobato, "243                                "promoteur de la vallée du Richelieu.",244                    details={"plan_pdf": pdf.group(1)} if pdf else {},245                    images=images,246                ))247        return listings248
Files main
Menu

Theme