SPB Git

Repository Public

gestion_legrand.py 8.9 KB 226 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_legrand.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-2714#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/gestion_legrand.py : connecteur Gestion Le Grand (gestionlegrand.ca)91#   WordPress + Elementor. Les logements sont des articles de la catégorie92#   « Location » (id 28) : l'API wp-json livre id, lien, titre et contenu93#   complet en 1 requête ; la page /a-louer/ (2e requête) fournit les94#   vignettes (certains médias sont bloqués côté REST). Prix (« Prix :95#   1 200 $ / mois »), dispo et adresse lus dans le contenu de l'article.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100import time101102import requests103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "https://gestionlegrand.ca"109API_URL = (f"{BASE}/wp-json/wp/v2/posts?categories=28&per_page=100"110           "&_fields=id,link,title,content")111LIST_URL = f"{BASE}/a-louer/"112113_PRIX_RE = re.compile(r"Prix\s*:\s*([\d\s.,]*\d\s*\$(?:\s*/?\s*mois)?)", re.I)114_ADDR_RE = re.compile(r"situ[ée]e?\s+au\s+(\d+[^,.]*,\s*(?:rue|boul(?:evard|\.)?|"115                      r"avenue|av\.|place|chemin)[^,.]+)", re.I)116_SECTEUR_RE = re.compile(r"secteur\s+(?:[\w\s]{0,40}?de\s+)?"117                         r"([A-ZÉ][\wé]+(?:-[A-ZÉa-z][\wéè]+)+)")118119120class GestionLegrandConnector(BaseConnector):121    source_id = "gestion_legrand"122    request_delay = 0.6123    timeout = 45  # le site a des lenteurs sporadiques (read timeout à 30 s)124125    def _api_posts(self) -> list:126        # Un timeout direct fait basculer l'escalade proxy, qui peut renvoyer127        # un 200 HTML non-JSON (JSONDecodeError du 2026-08-27) : on retente.128        last_exc: Exception | None = None129        for attempt in range(3):130            if attempt:131                time.sleep(5 * attempt)132            try:133                data = self.get(API_URL).json()134            except (ValueError, requests.RequestException) as exc:135                last_exc = exc136                continue137            if isinstance(data, list):138                return data139        raise RuntimeError(f"wp-json illisible après 3 tentatives ({last_exc})")140141    def fetch(self) -> list[Listing]:142        posts = self._api_posts()143144        # vignettes : la grille Elementor de /a-louer/ (post-<id> -> data-src)145        thumbs: dict[str, str] = {}146        try:147            soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")148            for art in soup.select("article.elementor-post"):149                pid = next((c.split("-", 1)[1] for c in art.get("class", [])150                            if re.fullmatch(r"post-\d+", c)), "")151                img = art.select_one("img[data-src], img[src]")152                if pid and img:153                    src = img.get("data-src") or img.get("src") or ""154                    if src.startswith("http"):155                        thumbs[pid] = src156        except Exception:157            pass158159        listings: list[Listing] = []160        for post in posts:161            try:162                lst = self._parse_post(post, thumbs)163            except Exception:164                continue165            if lst:166                listings.append(lst)167        return listings168169    def _parse_post(self, post: dict, thumbs: dict[str, str]) -> Listing | None:170        ext_id = str(post.get("id", ""))171        url = post.get("link", "")172        title = BeautifulSoup(post.get("title", {}).get("rendered", ""),173                              "html.parser").get_text(" ", strip=True)174        if not ext_id or not url or not title:175            return None176        # exclusions : locaux commerciaux, stationnements, rangements177        if re.search(r"commercial|bureau|stationnement|rangement|entrep[ôo]t",178                     title, re.I):179            return None180181        body = BeautifulSoup(post.get("content", {}).get("rendered", ""),182                             "html.parser")183        paras = [re.sub(r"\s+", " ", el.get_text(" ", strip=True))184                 for el in body.find_all(["p", "h2", "h3", "li"])]185        paras = [p for p in paras if p]186        text = "\n".join(dict.fromkeys(paras))187188        # « Disponible maintenant », « Disponible dès juin 2026 !! », …189        availability = next((p for p in paras190                             if re.match(r"disponible\b", p, re.I)), "")191192        m = _PRIX_RE.search(text)193        price_label = m.group(1).strip() if m else ""194195        m = _ADDR_RE.search(text)196        address = m.group(1).strip() if m else ""197198        m = _SECTEUR_RE.search(text)199        sector = m.group(1) if m else ""200201        # ville réelle : le titre se termine par « …, Drummondville » ;202        # tout le parc Le Grand y est (repli documenté dans le rapport)203        city = title.rsplit(",", 1)[1].strip() if "," in title else "Drummondville"204205        unit_type = normalize_unit_type(title)206        if not re.fullmatch(r"\d½\+?|Studio|Loft|Maison", unit_type or ""):207            unit_type = ""208209        images = [thumbs[ext_id]] if ext_id in thumbs else []210211        return Listing(212            source=self.source_id,213            external_id=ext_id,214            url=url,215            title=title,216            address=address,217            sector=sector,218            city=city,219            unit_type=unit_type,220            price=parse_price(price_label),221            price_label=price_label,222            availability=availability,223            description=text[:2000],224            images=images,225        )226
Files main
Menu

Theme