SPB Git

Repository Public

may_bourg.py 10.4 KB 258 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/may_bourg.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/may_bourg.py : connecteur Gestion May Bourg (maybourg.com)91#   Parc de 162 unités à Bécancour (Centre-du-Québec). WordPress + Elementor +92#   Dynamic Content for Elementor : la page /repertoire-de-logements/ liste les93#   modèles disponibles en <article class="logement"> avec data-dce-post-id94#   stable (ID de post WP), titre, projet, adresse, prix (« 1350$ / mois »),95#   superficie (« 1048 P.C. ») et badge « Unités disponibles ». Les fiches96#   /logement/<slug>/ (via cache BD) ajoutent la description et la galerie.97#   robots.txt : /wp-json/ interdit → HTML seulement (respecté).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://maybourg.com"110LIST_URL = f"{BASE}/repertoire-de-logements/"111112_PRICE_RE = re.compile(r"\d[\d\s,.]*\$")113_AREA_RE = re.compile(r"(\d[\d\s]*)\s*P\.?\s*C\.?", re.I)114_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp))", re.I)115116117class MayBourgConnector(BaseConnector):118    source_id = "may_bourg"119    request_delay = 0.7120    max_details = 20    # garde-fou fiches détail (parc ~7 modèles affichés)121122    def fetch(self) -> list[Listing]:123        html = self.get(LIST_URL).text124        soup = BeautifulSoup(html, "html.parser")125126        listings: dict[str, Listing] = {}127        # la grille DCE est dupliquée (variantes responsive) : dédup par post-id128        for art in soup.select("article.logement[data-dce-post-id]"):129            try:130                self._parse_card(art, listings)131            except Exception:132                continue133134        # fiches détail (cache BD) : description + galerie complète135        self._fetched = 0136        for lst in listings.values():137            card_key = hashlib.sha1(138                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"139                .encode("utf-8")).hexdigest()140            try:141                payload = self.detail(lst.external_id, card_key,142                                      lambda u=lst.url: self._fetch_detail(u))143            except Exception:144                continue145            if payload.get("description"):146                lst.description = payload["description"]147            if payload.get("images"):148                lst.images = payload["images"]149150        return list(listings.values())151152    # -- carte de la grille DCE ------------------------------------------------153    def _parse_card(self, art, listings: dict[str, Listing]) -> None:154        ext_id = str(art.get("data-dce-post-id", "")).strip()155        link = art.select_one('a[href*="/logement/"]')156        if not ext_id or not link or ext_id in listings:157            return158        url = link["href"]159160        # widgets texte de la carte : titre, projet, adresse, prix, superficie,161        # badge « Unités disponibles » — identifiés par leur contenu (l'ordre162        # des conteneurs Elementor n'est pas garanti)163        texts: list[str] = []164        for el in art.select(".elementor-widget-text-editor "165                             ".elementor-widget-container"):166            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))167            if t and t not in texts:168                texts.append(t)169170        title = texts[0] if texts else ""171        if not title:172            return173        # exclusions : commercial / stationnement / rangement174        if re.search(r"commercial|stationnement|rangement|entrep[oô]t",175                     title, re.I):176            return177178        price_label = address = availability = area_txt = sector = ""179        for t in texts[1:]:180            if _PRICE_RE.search(t) and not price_label:181                price_label = t182            elif _AREA_RE.search(t) and not area_txt:183                area_txt = t184            elif re.search(r"disponible", t, re.I) and not availability:185                availability = t186            elif re.search(r"b[ée]cancour", t, re.I) and not address:187                address = t188            elif not sector:189                sector = t     # nom du projet (« Logements Port Royal »…)190191        # type d'unité : titre (« 4 1/2 – 2e étage »), repli sur la classe192        # taxonomique WP « type-de-logement-4-1-2 »193        unit_type = normalize_unit_type(title)194        if not unit_type:195            for c in art.get("class", []):196                m = re.match(r"type-de-logement-(\d)-1-2", c)197                if m:198                    unit_type = normalize_unit_type(f"{m.group(1)} 1/2")199                    break200201        area_sqft = None202        m = _AREA_RE.search(area_txt)203        if m:204            area_sqft = float(m.group(1).replace(" ", ""))205206        images: list[str] = []207        img = art.select_one("img[src]")208        if img:209            src = _SIZE_SUFFIX.sub("", img["src"].split("?")[0])210            if src.startswith("http"):211                images.append(src)212213        listings[ext_id] = Listing(214            source=self.source_id,215            external_id=ext_id,           # ID du post WordPress (stable)216            url=url,217            title=title,218            address=address,219            sector=sector,220            # tout le parc May Bourg (162 unités) est à Bécancour :221            # projets rue Roy, boul. de Port-Royal et Godefroy (cf. site)222            city="Bécancour",223            unit_type=unit_type,224            price=parse_price(price_label),225            price_label=price_label,226            availability=availability,227            area_sqft=area_sqft,228            images=images,229        )230231    # -- fiche détail /logement/<slug>/ -----------------------------------------232    def _fetch_detail(self, url: str) -> dict:233        """Description (paragraphe principal de la fiche) + galerie complète."""234        if self._fetched >= self.max_details:235            raise RuntimeError("budget de fiches détail atteint")236        self._fetched += 1237        html = self.get(url).text238        soup = BeautifulSoup(html, "html.parser")239        out: dict = {}240241        # description = plus long paragraphe des widgets texte (la fiche n'a242        # qu'un seul vrai bloc descriptif)243        paras = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))244                 for p in soup.select(".elementor-widget-text-editor p")]245        paras = [p for p in paras if len(p) > 120]246        if paras:247            out["description"] = max(paras, key=len)[:1200]248249        images: list[str] = []250        for img in soup.select("img[src*='/wp-content/uploads/']"):251            src = _SIZE_SUFFIX.sub("", (img.get("src") or "").split("?")[0])252            if src.startswith("http") and src not in images \253                    and not re.search(r"logo|icon", src, re.I):254                images.append(src)255        if images:256            out["images"] = images[:30]257        return out258
Files main
Menu

Theme