SPB Git

Repository Public

logisbourg.py 15.4 KB 360 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/logisbourg.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/logisbourg.py : connecteur Logisbourg (logisbourg.com)91#   Site ASP classique : tableau des disponibilités par immeuble92#   (Le Bourgarde, Les Terrasses du Bourg, Le Bourg du Maizerets,93#   Le Bourg du Fleuve) + fiche appartement.asp pour adresse (avec no94#   d'unité), lat/lng (carte Google), superficie (encadré dédié), images,95#   caractéristiques de l'appartement et de l'immeuble, services optionnels96#   et téléphone du bureau de location. Fiches mises en cache via97#   self.detail() : re-visitées seulement quand la ligne du tableau change.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import html as htmllib103import re104from urllib.parse import quote105106from ..schema import Listing, infer_city, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://www.logisbourg.com"110LIST_URL = f"{BASE}/appartements-disponibles.asp"111112# En-têtes d'immeuble : "Charlesbourg / Lebourgneuf  : Le Bourgarde"113_COMPLEX_RE = re.compile(114    r'class="dispos_td_complexe".*?<div class="nomComplexe">\s*(.*?)<BR>\s*'115    r'<div class="nomComplexeAdresse">(.*?)</div>', re.S | re.I)116# Lignes de logement : <TR id="tr_23_" ...> ... </TR>117_ROW_RE = re.compile(r'<TR id="tr_(\d+)_".*?</TR>', re.S | re.I)118_LINK_RE = re.compile(119    r"appartement\.asp\?SID=(\d+)&CID=(\d+)&LID=(\d+)&Secteur=([^&']*)&Complexe=([^']*)'")120# Fiche : icônes/texte des caractéristiques (<div class='carac_icone'>…</div>)121_CARAC_RE = re.compile(r"<div class=['\"]carac_icone['\"][^>]*>(.*?)</div>",122                       re.S | re.I)123# Fiche : superficie dans son encadré dédié (<div id='superficie_encadre'>)124_SUPERFICIE_RE = re.compile(125    r"id=['\"]superficie_encadre['\"][^>]*>\s*([\d\s]{2,7})\s*pi", re.I)126# Fiche : coordonnées de la carte Google (new google.maps.LatLng(46.84,-71.26))127_LATLNG_RE = re.compile(r"google\.maps\.LatLng\((-?\d{1,3}\.\d+),\s*(-?\d{1,3}\.\d+)\)")128# Fiche : adresse complète avec no d'unité (« 4855, 6e Avenue Ouest # 403 »)129_ADDR_UNIT_RE = re.compile(r'<div class="nomComplexeAdresse">(.*?)</div>', re.S | re.I)130131132def _strip_tags(s: str) -> str:133    return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]+>", " ", s))).strip()134135136def _fix_sup(street: str) -> str:137    """« 6 e Avenue » (issu de 6<SUP>e</SUP>) -> « 6e Avenue »."""138    return re.sub(r"(\d)\s+(e|er|re)(\s+|$)", r"\1\2 ", street).strip()139140141class _DetailBudget(Exception):142    """Plafond de vraies requêtes de fiches atteint pour cette synchro."""143144145class LogisbourgConnector(BaseConnector):146    source_id = "logisbourg"147    request_delay = 0.6148    max_details = 80        # plafond de VRAIES requêtes de fiches par synchro149150    def __init__(self) -> None:151        super().__init__()152        self._detail_fetches = 0153154    # le serveur n'annonce pas de charset : forcer l'UTF-8 déclaré dans le HTML155    def _get_text(self, url: str) -> str:156        resp = self.get(url)157        resp.encoding = "utf-8"158        return resp.text159160    def fetch(self) -> list[Listing]:161        html = self._get_text(LIST_URL)162163        # 1) Position des en-têtes d'immeuble (secteur : nom + adresse de rue)164        complexes: list[tuple[int, str, str, str]] = []   # (pos, secteur, nom, rue)165        for m in _COMPLEX_RE.finditer(html):166            header = _strip_tags(m.group(1))              # "Secteur : Nom"167            street = _strip_tags(m.group(2))              # "6e Avenue Ouest"168            sector, _, name = header.partition(":")169            complexes.append((m.start(), sector.strip(), name.strip(), street))170171        # 2) Lignes de disponibilités172        listings: dict[str, Listing] = {}173        row_keys: dict[str, str] = {}                     # lid -> hash de la ligne174        for row_m in _ROW_RE.finditer(html):175            row = row_m.group(0)176            link = _LINK_RE.search(row)177            if not link:178                continue179            sid, cid, lid, sector_q, complex_q = link.groups()180            if lid in listings:181                continue182183            # immeuble courant = dernier en-tête avant cette ligne184            sector = name = street = ""185            for pos, sec, nom, rue in complexes:186                if pos < row_m.start():187                    sector, name, street = sec, nom, rue188                else:189                    break190            sector = sector or sector_q191            name = name or complex_q192193            def cell(cls: str) -> str:194                c = re.search(r'class="%s"[^>]*>(.*?)</TD>' % cls, row, re.S | re.I)195                return _strip_tags(c.group(1)) if c else ""196197            def cell_title(cls: str) -> str:198                c = re.search(r'class="%s"\s+TITLE="([^"]*)"' % cls, row, re.I)199                return htmllib.unescape(c.group(1)).replace("\xa0", " ") if c else ""200201            unit_raw = cell("Grandeur")202            avail = cell_title("DateDispo") or cell("DateDispo")203            floor = cell_title("Etage") or cell("Etage")204            price_label = cell("Prix")205            # inclusions (icônes avec ALT dans la colonne "Inclus")206            included = [htmllib.unescape(a) for a in207                        re.findall(r'ALT="([^"]+)"', row, re.I)208                        if "favoris" not in a.lower()]209210            url = (f"{BASE}/appartement.asp?SID={sid}&CID={cid}&LID={lid}"211                   f"&Secteur={quote(sector_q)}&Complexe={quote(complex_q)}")212            amenities = list(dict.fromkeys(included))213            if floor:214                amenities.append(f"Étage : {floor}")215216            # clé de cache des fiches : contenu de la ligne du tableau217            # (préfixe v2 = version de l'extraction, pour invalider le cache218            # quand le connecteur change)219            row_keys[lid] = "v3:" + hashlib.sha1(220                " | ".join([unit_raw, avail, floor, price_label] + included)221                .encode("utf-8")).hexdigest()222223            listings[lid] = Listing(224                source=self.source_id,225                external_id=lid,226                url=url,227                title=f"{name} — {unit_raw}".strip(" —"),228                sector=sector,229                city=infer_city(sector, default="Québec"),230                unit_type=normalize_unit_type(unit_raw),231                price=parse_price(price_label),232                price_label=price_label,233                availability=avail,234                amenities=amenities,235            )236237        # 3) Fiches (avec cache BD) : adresse + no d'unité, lat/lng, superficie,238        #    images, caractéristiques, services optionnels, téléphone239        for lid, lst in listings.items():240            url = lst.url241            try:242                payload = self.detail(243                    lid, row_keys.get(lid, ""),244                    lambda u=url: self._fetch_detail(u))245            except _DetailBudget:246                continue247            except Exception:248                continue249            self._apply_detail(lst, payload)250251        return list(listings.values())252253    # -- fiche appartement.asp -------------------------------------------------254    def _fetch_detail(self, url: str) -> dict:255        if self._detail_fetches >= self.max_details:256            raise _DetailBudget(url)257        self._detail_fetches += 1258        detail = self._get_text(url)259        out: dict = {}260261        # adresse complète avec no d'unité (« 4855, 6e Avenue Ouest # 403 »)262        m = _ADDR_UNIT_RE.search(detail)263        if m:264            addr = _fix_sup(_strip_tags(m.group(1)))265            out["address"] = re.sub(r"#\s*", "#", addr)266        if not out.get("address"):267            # repli : variables JS adr1/adr2 de la carte Google268            m = re.search(r'var adr1 = "([^"]*)";\s*var adr2 = "([^"]*)"', detail)269            if m and m.group(1):270                out["address"] = f"{m.group(1)}, {_fix_sup(_strip_tags(m.group(2)))}".strip(" ,")271272        # coordonnées de la carte Google (structurées)273        m = _LATLNG_RE.search(detail)274        if m:275            out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))276277        # superficie : encadré dédié de la fiche (structuré)278        m = _SUPERFICIE_RE.search(detail)279        if m:280            try:281                val = float(m.group(1).replace(" ", ""))282                if 80 <= val <= 20000:283                    out["area_sqft"] = val284            except ValueError:285                pass286287        # téléphone du bureau de location (lien tel: du formulaire de visite)288        m = re.search(r"Pour une visite.*?tel:\+?1?(\d{10})", detail, re.S | re.I)289        if m:290            d = m.group(1)291            out["phone"] = f"{d[0:3]}-{d[3:6]}-{d[6:10]}"292293        # retirer commentaires et scripts avant les extractions texte294        detail = re.sub(r"<!--.*?-->", " ", detail, flags=re.S)295        detail = re.sub(r"<script.*?</script>", " ", detail, flags=re.S | re.I)296297        # images de l'immeuble : ./<secteur>/<immeuble>/images/xxx.jpg298        imgs = re.findall(299            r'(?:\./)?([a-z0-9_\-]+/[a-z0-9_\-]+/images/[^"\'\s]+'300            r'\.(?:jpg|jpeg|png|webp))', detail, re.I)301        out["images"] = [f"{BASE}/{u}" for u in dict.fromkeys(imgs)][:25]302303        # caractéristiques de l'appartement : ALT des icônes (« Entrées304        # laveuse/sécheuse incluses ») + texte visible (« Balcon 60 pi² »,305        # « Un stationnement extérieur »…)306        amen: list[str] = []307        for c in _CARAC_RE.findall(detail):308            amen += [htmllib.unescape(a or b) for a, b in309                     re.findall(r"(?:ALT|alt)=(?:\"([^\"]{3,60})\"|'([^']{3,60})')", c)]310            amen.append(_strip_tags(c))311        # caractéristiques de l'immeuble (liste <li> : Bell Fibe, Intercom…)312        m = re.search(r"Caract[ée]ristiques immeuble(.*?)(?:Services optionnels|"313                      r"Les informations)", detail, re.S | re.I)314        immeuble_txt = ""315        if m:316            immeuble_txt = _strip_tags(m.group(1))317            amen += [_strip_tags(li) for li in318                     re.findall(r"<li>(.*?)</li>", m.group(1), re.S | re.I)]319        # revêtements de sol (« Revêtements : Bois flottant, céramique… »)320        m = re.search(r"Rev[êe]tements?\s*:\s*([^<]{3,120})", detail, re.I)321        if m:322            amen.append("Revêtements : " + _strip_tags(m.group(1)))323        out["amenities"] = [a for a in dict.fromkeys(amen)324                            if len(a) >= 3 and a.lower() != "superficie"][:25]325326        # description : présentation du complexe + immeuble + services optionnels327        desc_bits = []328        m = re.search(r'<div id="DescriptionComplexe">(.*?)</div>', detail,329                      re.S | re.I)330        if m and _strip_tags(m.group(1)):331            desc_bits.append(_strip_tags(m.group(1)))332        if immeuble_txt:333            desc_bits.append("Caractéristiques de l'immeuble : " + immeuble_txt)334        m = re.search(r"Services optionnels(.*?)Les informations", detail,335                      re.S | re.I)336        if m and _strip_tags(m.group(1)):337            desc_bits.append("Services optionnels : " + _strip_tags(m.group(1)))338        out["description"] = " — ".join(desc_bits)[:900]339        return out340341    def _apply_detail(self, lst: Listing, payload: dict) -> None:342        if not payload:343            return344        if payload.get("address"):345            lst.address = payload["address"]346            lst.title = f"{payload['address']} — {lst.unit_type}".strip(" —")347        if payload.get("lat") is not None and payload.get("lng") is not None:348            lst.lat, lst.lng = payload["lat"], payload["lng"]349        if payload.get("area_sqft"):350            lst.area_sqft = payload["area_sqft"]351        if payload.get("phone"):352            lst.details.setdefault("contact", {})["phone"] = payload["phone"]353        for a in payload.get("amenities", []):354            if a not in lst.amenities:355                lst.amenities.append(a)356        if payload.get("images"):357            lst.images = payload["images"]358        if payload.get("description"):359            lst.description = payload["description"]360
Files main
Menu

Theme