SPB Git

Repository Public

logiluxx.py 11.5 KB 269 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/logiluxx.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-09-0714#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/logiluxx.py : connecteur Logiluxx / Investissements Cleary91#   (logiluxx.com — habitations locatives tout inclus LEED, 50 ans et mieux).92#   Trois immeubles, chacun avec son mini-site statique (HTML iso-8859-1) :93#   St-Hubert I et II (Faubourg Cousineau, Longueuil) et Boucherville.94#   Les sites St-Hubert affichent une table « PRIX » par typologie95#   (superficie @ superficie, loyer « à partir de X$ ») ; Boucherville n'a96#   que les plans (superficies) et fonctionne par liste d'attente.97#   Granularité : une annonce par immeuble × typologie.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type, parse_price106from .base import BaseConnector107108# (id, base URL, nom, secteur, ville) — les mini-sites existent aussi en109# sous-domaines (<id>.logiluxx.com) mais leur certificat TLS est invalide :110# on passe par les miroirs sur le domaine principal.111BUILDINGS = [112    ("sthubert", "https://logiluxx.com/sthubert/",113     "Logiluxx St-Hubert I", "Saint-Hubert", "Longueuil"),114    ("sthubert2", "https://logiluxx.com/sthubert2/",115     "Logiluxx St-Hubert II", "Saint-Hubert", "Longueuil"),116    ("boucherville", "https://logiluxx.com/boucherville/",117     "Logiluxx Boucherville", "", "Boucherville"),118]119120# ligne de la table PRIX : « 3 1/2  817 @ 1056  160  977 @ 1216  à partir de 1941$ »121PRICE_ROW_RE = re.compile(122    r"(\d)\s*1/2\s+([\d]+(?:\s*@\s*\d+)?)\s+(\d+)\s+[\d]+(?:\s*@\s*\d+)?\s+"123    r"[àa] partir de\s*([\d\s,]{3,9})\s*\$", re.I)124# ligne d'un plan : « 3 1/2  770  140  910 » (superficie, balcon, totale)125PLAN_ROW_RE = re.compile(r"(\d)\s*1/2\s+(\d{3,4})\s+(\d{2,3})\s+(\d{3,4})")126# typologies annoncées (« LA SUITE 3 1/2 », « LES PENTHOUSES 5 1/2 »)127SUITE_RE = re.compile(r"(?:SUITES?|PENTHOUSES?)\s+(\d)\s*1/2", re.I)128IMG_RE = re.compile(r'src="(images/projets/[^"]+\.(?:jpe?g|png))"', re.I)129INCLUSION_RE = re.compile(r"^-\s*(.{4,90})$")130PHONE_RE = re.compile(r"(\d{3})[.\s](\d{3})[.\s](\d{4})")131132PLAN_PAGE_OF = {"3": "plan3demi.html", "4": "plan4demi.html",133                "5": "plan5demi.html"}134135136class LogiluxxConnector(BaseConnector):137    source_id = "logiluxx"138    request_delay = 0.8139140    def _get_text(self, url: str) -> tuple[str, str]:141        """(html, texte aplati) — les mini-sites sont encodés iso-8859-1142        (mais un fetch de secours via proxy peut renvoyer de l'UTF-8)."""143        resp = self.get(url)144        try:145            html = resp.content.decode("utf-8")146        except UnicodeDecodeError:147            html = resp.content.decode("iso-8859-1", errors="replace")148        soup = BeautifulSoup(html, "html.parser")149        for tag in soup(["script", "style", "noscript"]):150            tag.decompose()151        return html, re.sub(r"\s+", " ", soup.get_text(" ", strip=True))152153    def fetch(self) -> list[Listing]:154        # échec HONNÊTE : une erreur réseau/parse sur un immeuble doit lever155        # (ok=0 dans sync_log) et non être avalée — un « 0 trouvé ok » déclenche156        # la dérive et menace les 9 annonces (vu le 2026-09-07 12:10)157        listings: list[Listing] = []158        for bid, base, name, sector, city in BUILDINGS:159            found = self._fetch_building(bid, base, name, sector, city)160            if not found:161                raise RuntimeError(162                    f"logiluxx : aucune typologie parsée sur {base} "163                    "(rendu partiel ou site restructuré)")164            listings.extend(found)165        return listings166167    def _fetch_building(self, bid: str, base: str, name: str,168                        sector: str, city: str) -> list[Listing]:169        html, text = self._get_text(base)170171        # inclusions (« - Chauffage, électricité et eau chaude », …)172        amenities = ["Formule tout inclus (chauffage, électricité, eau chaude)",173                     "5 électroménagers en acier inoxydable",174                     "Climatisation", "Immeuble LEED",175                     "Pour les 50 ans et mieux"]176        for kw, label in [177            (r"[Pp]iscine", "Piscine chauffée"),178            (r"entra[îi]nement", "Centre d'entraînement"),179            (r"[Aa]scenseur", "Ascenseurs"),180            (r"[Cc][âa]blodistribution", "Câblodistribution (base) incluse"),181        ]:182            if re.search(kw, text):183                amenities.append(label)184185        contact: dict = {}186        m = PHONE_RE.search(text)187        if m:188            contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"189        m = re.search(r"[\w.\-]+@logiluxx\.com", text)190        if m:191            contact["email"] = m.group(0).lower()192193        images = [base + u for u in dict.fromkeys(IMG_RE.findall(html))194                  if "logo" not in u.lower()][:12]195196        waitlist = bool(re.search(r"LISTE D.ATTENTE", text, re.I))197        availability = "Liste d'attente" if waitlist else ""198199        out: list[Listing] = []200        seen: set[str] = set()201202        # 1) table PRIX (St-Hubert) : typologie + superficies + loyer plancher203        for n, area_rng, balcon, price_txt in PRICE_ROW_RE.findall(text):204            if n in seen:205                continue206            seen.add(n)207            price_label = f"à partir de {price_txt.strip()}$"208            area_min = float(area_rng.split("@")[0].strip())209            out.append(self._listing(210                bid, base, name, sector, city, n, price_label, area_min,211                f"Superficie : {area_rng.strip()} pi² + balcon {balcon} pi²",212                availability, amenities, contact, images))213214        # 2) sinon (Boucherville) : typologies des sections « PLANS DES215        #    SUITES », superficies lues sur la page plan de chaque typologie216        if not out:217            for n in dict.fromkeys(SUITE_RE.findall(html)):218                if n in seen:219                    continue220                seen.add(n)221                area_min, area_note = None, ""222                page = PLAN_PAGE_OF.get(n)223                if page:224                    try:225                        _, ptext = self._get_text(base + page)226                        areas = [float(a) for t, a, _b, _tot227                                 in PLAN_ROW_RE.findall(ptext) if t == n]228                        if areas:229                            area_min = min(areas)230                            area_note = (f"Superficie : "231                                         f"{int(min(areas))}–{int(max(areas))} pi²"232                                         if len(set(areas)) > 1 else233                                         f"Superficie : {int(areas[0])} pi²")234                    except Exception:235                        pass236                out.append(self._listing(237                    bid, base, name, sector, city, n, "", area_min,238                    area_note, availability, amenities, contact, images))239        return out240241    def _listing(self, bid, base, name, sector, city, n, price_label,242                 area_min, area_note, availability, amenities, contact,243                 images) -> Listing:244        ut = normalize_unit_type(f"{n}½")245        penthouse = (n == "5")246        desc = (f"{name} — habitations locatives haut de gamme tout inclus "247                f"pour les 50 ans et mieux (Investissements Cleary), "248                f"certification LEED. "249                + ("Penthouse. " if penthouse else "")250                + (area_note or ""))251        return Listing(252            source=self.source_id,253            external_id=f"{bid}-{n}.5",254            url=base,255            title=f"{name} — {ut}" + (" (penthouse)" if penthouse else ""),256            address="",257            sector=sector,258            city=city,259            unit_type=ut,260            price=parse_price(price_label),261            price_label=price_label,262            availability=availability,263            area_sqft=area_min,264            description=desc.strip(),265            amenities=list(dict.fromkeys(amenities)),266            details={"contact": dict(contact)} if contact else {},267            images=images,268        )269
Files main
Menu

Theme