SPB Git

Repository Public

logisma.py 13.2 KB 318 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/logisma.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/logisma.py : connecteur Logisma (logisma.ca)91#   Page de recherche /appartements-a-louer/ (boucle Elementor) : une carte92#   par unité disponible. Pages détail pour disponibilité, description,93#   promotion, liste « Détails : » (inclusions/animaux/fumeur), téléphone94#   (lien tel:) et toutes les images. L'API REST WP (/wp-json/wp/v2/location)95#   existe mais n'expose ni contenu ni ACF -> HTML seulement.96#   La section commerciale/industrielle est exclue.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, infer_city, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "https://logisma.ca"109LIST_URL = f"{BASE}/appartements-a-louer/"110111DETAIL_RE = re.compile(r"/appartements-a-louer/([a-z0-9\-]+)/?$")112IMG_RE = re.compile(113    r"https://logisma\.ca/wp-content/uploads/[^\"'\\\s\)]+"114    r"\.(?:jpg|jpeg|png|webp)", re.I)115IMG_NOISE_RE = re.compile(r"logo|favicon|icon|-\d+x\d+\.", re.I)116117118class _DetailBudget(Exception):119    """Plafond de vraies requêtes de pages détail atteint pour cette synchro."""120121122class LogismaConnector(BaseConnector):123    source_id = "logisma"124    request_delay = 0.6125    max_details = 60             # plafond de VRAIES requêtes détail par synchro126127    def __init__(self) -> None:128        super().__init__()129        self._detail_fetches = 0130131    def fetch(self) -> list[Listing]:132        html = self.get(LIST_URL).text133        soup = BeautifulSoup(html, "html.parser")134135        listings: dict[str, Listing] = {}136        # Cartes : <h3 class="... containsUrl" attr-url="...">137        #   <b>3 1/2</b> Québec, Ste-Foy<br>3 1/2 – 3003 avenue d'Entremont #5138        for h3 in soup.select("h3.containsUrl[attr-url]"):139            try:140                lst = self._parse_card(h3)141            except Exception:142                continue143            if lst and lst.external_id not in listings:144                listings[lst.external_id] = lst145146        # Pages détail (avec cache BD) : clé = contenu de la carte, versionnée147        for lst in listings.values():148            key = "v3:" + hashlib.sha1(" | ".join(149                [lst.title, lst.price_label, lst.sector, lst.address])150                .encode("utf-8")).hexdigest()151            try:152                payload = self.detail(lst.external_id, key,153                                      lambda u=lst.url: self._fetch_detail(u))154            except _DetailBudget:155                continue156            except Exception:157                continue158            self._apply_detail(lst, payload)159160        return list(listings.values())161162    def _parse_card(self, h3) -> Listing | None:163        url = h3.get("attr-url", "").split("?")[0]164        m = DETAIL_RE.search(url)165        if not m:166            return None167        slug = m.group(1)168169        b = h3.find("b")170        unit_raw = b.get_text(" ", strip=True) if b else ""171        lines = [t.strip() for t in h3.get_text("\n", strip=True).split("\n")172                 if t.strip()]173        # lines ~ ['3 1/2', 'Québec, Ste-Foy', '3 1/2 – 3003 avenue …, Ste-Foy']174        sector = ""175        title = lines[-1] if lines else slug176        # Ligne ville/secteur : « Québec, Ste-Foy » (exclure hors Québec/Lévis)177        for ln in lines:178            mm = re.match(r"^([A-Za-zÀ-ÿ\-'’ ]+)\s*,\s*([A-Za-zÀ-ÿ\-'’ ]+)$", ln)179            if mm and "–" not in ln:180                city_raw = mm.group(1).strip().lower()181                if city_raw not in ("québec", "quebec", "lévis", "levis"):182                    return None          # hors agglomération Québec/Lévis183                sector = mm.group(2).strip()184                break185        # Adresse : après le tiret du titre (« 3 1/2 – 3003 avenue … #5, Ste-Foy »)186        address = ""187        if "–" in title or " - " in title:188            rest = re.split(r"–|\s-\s", title, maxsplit=1)[-1].strip()189            segs = [s.strip() for s in rest.split(",")]190            if len(segs) > 1 and not re.search(r"\d", segs[-1]):191                segs = segs[:-1]         # retirer le secteur final192            address = ", ".join(s for s in segs if s)193194        # Prix : dans le conteneur de la carte (élément frère du titre)195        price_label = ""196        container = h3.find_parent(class_=re.compile(r"add-link-container")) or \197            h3.find_parent("div", attrs={"data-e-type": "container"})198        if container:199            mp = re.search(r"\d[\d\s ]*\$", container.get_text(" ", strip=True))200            if mp:201                price_label = mp.group(0).strip()202203        return Listing(204            source=self.source_id,205            external_id=slug,206            url=url,207            title=title,208            address=address,209            sector=sector,210            city=infer_city(sector),211            unit_type=normalize_unit_type(unit_raw),212            price=parse_price(price_label),213            price_label=price_label,214        )215216    def _fetch_detail(self, url: str) -> dict:217        if self._detail_fetches >= self.max_details:218            raise _DetailBudget(url)219        self._detail_fetches += 1220        resp = self.get(url)221        # lien mort : le site redirige vers la page liste -> garder la carte222        if resp.url.rstrip("/") != url.rstrip("/"):223            return {}224        html = resp.text225        soup = BeautifulSoup(html, "html.parser")226        body = soup.get_text(" ", strip=True)227        out: dict = {}228229        # Disponibilité : « Disponible le 1er juillet 2026 »230        m = re.search(r"[Dd]isponible\b(?!s)\s*(?:le|dès|en|maintenant|"231                      r"immédiatement|1er)[^.<,$]{0,50}", body)232        if m:233            avail = re.sub(r"\s+", " ", m.group(0)).strip()234            avail = re.split(r"\s+(?:UN MOIS|Description|Électro|Offre|Vous)",235                             avail)[0]236            out["availability"] = avail.strip()237238        # Prix de secours si absent de la carte (appliqué seulement si besoin)239        mp = re.search(r"(\d[\d\s ]*\$)\s*par mois", body)240        if mp:241            out["price_label"] = mp.group(1).strip()242243        # Liste « Détails : » (items <li> du widget Elementor — certaines pages244        # n'utilisent pas de puces « • » : extraction structurelle d'abord)245        amen: list[str] = []246        m = None247        mi = re.search(r"D[ée]tails\s*:?\s*</strong>", html)248        if mi:249            # le <ul> doit suivre de près (sinon : page à puces « • » sans <ul>,250            # et le premier </ul> venu serait le menu du pied de page)251            m = re.match(r".{0,1000}?<ul>(.*?)</ul>",252                         html[mi.end():mi.end() + 6000], re.S)253        if m:254            for li in re.findall(r"<li[^>]*>(.*?)</li>", m.group(1), re.S):255                t = re.sub(r"\s+", " ",256                           BeautifulSoup(li, "html.parser")257                           .get_text(" ", strip=True)).strip(" .•")258                if t:259                    amen.append(t)260        if not amen:   # repli : puces « • Eau chaude inclus » dans le texte261            amen = [re.sub(r"\s+", " ", a).strip(" .")262                    for a in re.findall(r"•\s*([^•<\n]{3,60})", body)]263        # couper l'avertissement photos collé au dernier item264        amen = [re.split(r"\*\*|Les photos", a)[0].strip(" .")265                for a in amen]266        out["amenities"] = list(dict.fromkeys(a for a in amen if len(a) >= 3))[:20]267268        # Description : paragraphes entre « Description » et « Détails : »269        # (plus promotion « UN MOIS GRATUIT … » affichée sous le prix)270        desc_bits: list[str] = []271        mp = re.search(r"(UN MOIS GRATUIT[^.]*\.(?:\s*Prix régulier[^.]*\.)?)",272                       body)273        if mp:274            desc_bits.append("Promotion : " + re.sub(r"\s+", " ", mp.group(1)))275        m = re.search(r"<strong>\s*Description\s*</strong>\s*</p>(.*?)"276                      r"(?:<strong>\s*D[ée]tails|</div>\s*</div>\s*</div>)",277                      html, re.S)278        if m:279            txt = re.sub(r"\s+", " ", BeautifulSoup(m.group(1), "html.parser")280                         .get_text(" ", strip=True))281            if txt:282                desc_bits.append(txt)283        if not desc_bits:284            og = soup.find("meta", attrs={"property": "og:description"}) or \285                soup.find("meta", attrs={"name": "description"})286            if og and og.get("content"):287                desc_bits.append(og["content"].strip())288        out["description"] = " — ".join(desc_bits)[:600]289290        # Téléphone du bureau de location (lien tel:)291        for a in soup.select('a[href^="tel:"]'):292            num = re.sub(r"\D", "", a.get("href", "").split(",")[0])293            num = num[1:] if len(num) == 11 and num.startswith("1") else num294            if len(num) == 10:295                out["phone"] = f"{num[:3]}-{num[3:6]}-{num[6:10]}"296                break297298        out["images"] = [u for u in dict.fromkeys(IMG_RE.findall(html))299                         if not IMG_NOISE_RE.search(u)][:25]300        return out301302    def _apply_detail(self, lst: Listing, payload: dict) -> None:303        if not payload:304            return305        if payload.get("availability"):306            lst.availability = payload["availability"]307        if lst.price is None and payload.get("price_label"):308            lst.price_label = payload["price_label"]309            lst.price = parse_price(lst.price_label)310        if payload.get("amenities"):311            lst.amenities = payload["amenities"]312        if payload.get("description"):313            lst.description = payload["description"]314        if payload.get("phone"):315            lst.details.setdefault("contact", {})["phone"] = payload["phone"]316        if payload.get("images"):317            lst.images = payload["images"]318
Files main
Menu

Theme