SPB Git

Repository Public

gestion_bloc.py 10.1 KB 255 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_bloc.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/gestion_bloc.py : connecteur Gestion Bloc (gestionbloc.ca)91#   Gestionnaire immobilier de Québec / Lévis / Chaudière-Appalaches. Site Wix92#   MAIS la page /logements est rendue serveur (SSR Thunderbolt) : galeries93#   Pro Gallery avec une carte par logement — titre (rue), localité, puis94#   « Pièces / Chambre(s) / Salle(s) de bain ». Annonces sans prix ni date95#   (Tier B). Granularité : logement (une carte = une annonce).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Listing, strip_accents104from .base import BaseConnector105106BASE = "https://www.gestionbloc.ca"107LIST_URL = f"{BASE}/logements"108109ROOMS_RE = re.compile(r"pi[eè]ces?\s*:?\s*([\d]+(?:\s*1/2|\s*½|\.5)?)", re.I)110BED_RE = re.compile(r"chambres?\s*:?\s*(\d+(?:\.\d+)?)", re.I)111BATH_RE = re.compile(r"salles?\s*de\s*bain\s*:?\s*(\d+(?:\.\d+)?)", re.I)112LIT_RE = re.compile(r"lits?\s*:?\s*(\d+)", re.I)113114CONTACT = {"email": "reception@gestionbloc.com", "phone": "418-903-5585"}115116# quartiers/secteurs de la ville de Québec (pour distinguer « Val-Bélair,117# Québec » [= ville de Québec] de « Donnacona, Québec » [= province])118QUEBEC_SECTORS = {119    "val-belair", "cap-rouge", "limoilou", "charlesbourg", "sainte-foy",120    "ste-foy", "beauport", "sillery", "vanier", "duberger", "les-saules",121    "lebourgneuf", "loretteville", "neufchatel", "saint-sauveur",122    "saint-roch", "montcalm", "saint-jean-baptiste", "lairet", "maizerets",123}124LEVIS_SECTORS = {125    "levis", "saint-jean-chrysostome", "st-jean-chrysostome", "charny",126    "saint-romuald", "st-romuald", "saint-nicolas", "st-nicolas",127    "pintendre", "breakeyville", "saint-redempteur", "st-redempteur",128}129130131def _slug(text: str) -> str:132    return re.sub(r"-+", "-",133                  re.sub(r"[^a-z0-9]+", "-", strip_accents(text.lower()))134                  ).strip("-")135136137class GestionBlocConnector(BaseConnector):138    source_id = "gestion_bloc"139    request_delay = 0.6140141    def fetch(self) -> list[Listing]:142        listings: list[Listing] = []143        try:144            html = self.get(LIST_URL).text145        except Exception:146            return listings147        soup = BeautifulSoup(html, "html.parser")148149        seen: set[str] = set()150        # 2 galeries : « Ville de Québec & Rive Nord » puis « Ville de Lévis151        # & Rive Sud » — sert de ville par défaut quand la carte n'en a pas.152        galleries = soup.select("div.pro-gallery-margin-container") or [soup]153        for gi, gallery in enumerate(galleries):154            default_city = "Québec" if gi == 0 else "Lévis"155            for title_el in gallery.select('[data-hook="item-title"]'):156                try:157                    lst = self._parse_card(title_el, default_city, seen)158                except Exception:159                    continue160                if lst is not None:161                    listings.append(lst)162        return listings163164    def _parse_card(self, title_el, default_city: str,165                    seen: set[str]) -> Listing | None:166        info = title_el.find_parent(class_="info-element-text")167        if info is None:168            return None169        lines = [ln.strip() for ln in170                 info.get_text("\n", strip=True).split("\n")171                 if ln.strip() and ln.strip() != "​"]172        if not lines:173            return None174        street = lines[0]175        locality = lines[1] if len(lines) > 1 else ""176        blob = " | ".join(lines[2:])177178        # localité « Secteur, Ville » — mais « X, Québec » peut vouloir dire179        # « quartier de la ville de Québec » OU « ville X, province de180        # Québec » : on tranche avec les listes de quartiers connus.181        parts = [p.strip(" .") for p in locality.split(",") if p.strip(" .")]182        sector, city = "", default_city183        if len(parts) >= 2:184            first = strip_accents(parts[0].lower()).replace(" ", "-")185            if first in QUEBEC_SECTORS:186                sector, city = parts[0], "Québec"187            elif first in LEVIS_SECTORS:188                sector = parts[0] if first != "levis" else ""189                city = "Lévis"190            else:191                city = parts[0]          # ville autonome (Donnacona…)192        elif parts:193            solo = strip_accents(parts[0].lower()).replace(" ", "-")194            m = re.match(r"^(.*)\((qu[ée]bec)\)$", parts[0], re.I)195            if m:                        # « Sainte-Foy (Québec) »196                sector, city = m.group(1).strip(), "Québec"197            elif solo in QUEBEC_SECTORS:198                sector, city = parts[0], "Québec"199            elif solo in LEVIS_SECTORS:200                city = "Lévis"201            else:202                city = parts[0]203        if sector and "(" in sector:204            sector = sector.split("(")[0].strip()205        if sector.lower() == city.lower():206            sector = ""207208        bedrooms = None209        m = BED_RE.search(blob) or LIT_RE.search(blob)210        if m:211            bedrooms = float(m.group(1))212        bathrooms = None213        m = BATH_RE.search(blob)214        if m:215            bathrooms = float(m.group(1))216        unit_type = ""217        m = ROOMS_RE.search(blob)218        if m:219            unit_type = m.group(1).replace("1/2", "½") \220                .replace(".5", "½").replace(" ", "")221            if "½" not in unit_type:222                unit_type += "½"223224        ext_id = _slug(f"{street}-{sector or city}")225        if not ext_id or ext_id in seen:226            return None227        seen.add(ext_id)228229        # photo de la carte (galerie Wix, URL nettoyée des transformations)230        images: list[str] = []231        container = title_el.find_parent(attrs={"data-hook": "item-container"})232        if container is not None:233            img = container.select_one(234                'img[data-hook="gallery-item-image-img"]')235            if img and img.get("src", "").startswith("http"):236                images = [img["src"].split("/v1/")[0]]237238        return Listing(239            source=self.source_id,240            external_id=ext_id,241            url=LIST_URL,242            title=street,243            address=f"{street}, {city}" if city else street,244            sector=sector,245            city=city,246            unit_type=unit_type,247            bedrooms=bedrooms,248            bathrooms=bathrooms,249            price_label="Prix sur demande",250            description=f"Logement à louer sur {street} "251                        f"({locality}) — Gestion Bloc. {blob}",252            details={"contact": dict(CONTACT)},253            images=images,254        )255
Files main
Menu

Theme