SPB Git

Repository Public

bribourg.py 13.0 KB 315 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/bribourg.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/bribourg.py : connecteur Bri Bourg (bribourg.com)91#   Site PHP simple (Charlesbourg, Vanier, Beauport). Les annonces de92#   logements à louer sont publiées via un blogue DropInBlog embarqué dans93#   Logements-a-louer.php ; on lit le flux RSS DropInBlog, puis on complète94#   avec la page d'immeuble correspondante (Immeubles.php) : photos, code95#   postal, descriptif de l'immeuble et services à proximité (via le cache96#   self.detail()). Contact (tel:/mailto:) pris sur la page principale.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import html as htmllib102import re103import unicodedata104from urllib.parse import unquote, urlparse, parse_qs105106from ..schema import Listing, infer_city, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://bribourg.com"110RENT_PAGE = f"{BASE}/Logements-a-louer.php"111# identifiant du blogue DropInBlog (repli si non détecté dans la page)112DEFAULT_BLOG_ID = "dcc6791b-355d-4d9b-bb91-a30d855f6cdf"113FEED_URL = "https://io.dropinblog.com/feed/{blog_id}/?limit=100"114115116def _strip_tags(s: str) -> str:117    return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]+>", " ", s))).strip()118119120def _norm(s: str) -> str:121    s = unicodedata.normalize("NFD", s.lower())122    return "".join(c for c in s if unicodedata.category(c) != "Mn")123124125class BribourgConnector(BaseConnector):126    source_id = "bribourg"127    request_delay = 0.6128129    def fetch(self) -> list[Listing]:130        # 1) Détecter l'identifiant du blogue DropInBlog dans la page131        #    (+ contact du gestionnaire : liens tel:/mailto: structurés)132        blog_id = DEFAULT_BLOG_ID133        self._contact: dict = {}134        try:135            page = self.get(RENT_PAGE).text136            m = re.search(r"embedjs/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-"137                          r"[0-9a-f]{4}-[0-9a-f]{12})", page)138            if m:139                blog_id = m.group(1)140            m = re.search(r'href="tel:(\d{10})"', page)141            if m:142                d = m.group(1)143                self._contact["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"144            m = re.search(r'href="mailto:([^"?]+)"', page)145            if m:146                self._contact["email"] = m.group(1)147        except Exception:148            pass149150        # 2) Flux RSS des annonces151        try:152            feed = self.get(FEED_URL.format(blog_id=blog_id)).text153        except Exception:154            return []155156        # 3) Pages d'immeubles (pour compléter les photos)157        building_pages = self._building_pages()158159        listings: list[Listing] = []160        for item in re.findall(r"<item>(.*?)</item>", feed, re.S):161            try:162                lst = self._parse_item(item, building_pages)163                if lst:164                    listings.append(lst)165            except Exception:166                continue167        return listings168169    # -- inventaire des pages d'immeubles ---------------------------------------170    def _building_pages(self) -> list[str]:171        try:172            html = self.get(f"{BASE}/Immeubles.php").text173        except Exception:174            return []175        pages = re.findall(r'href="((?:\./)?\d[\w\-]+\.php)"', html)176        return sorted({p.lstrip("./") for p in pages})177178    # -- une annonce du flux -----------------------------------------------------179    def _parse_item(self, item: str, building_pages: list[str]) -> Listing | None:180        def tag(name: str) -> str:181            m = re.search(r"<%s>(.*?)</%s>" % (name, name), item, re.S)182            return htmllib.unescape(m.group(1).strip()) if m else ""183184        title = _strip_tags(tag("title"))185        link = tag("link") or RENT_PAGE186        m = re.search(r"<content:encoded>\s*<!\[CDATA\[(.*?)\]\]>", item, re.S)187        content = m.group(1) if m else tag("description")188189        # exclusions : stationnement / commercial / rangement190        if re.search(r"stationnement|commercial|rangement|garage|entrep[oô]t",191                     title, re.I):192            return None193194        text = _strip_tags(content)195        # "Adresse : 510, avenue Claude-Martin, Québec (Vanier)"196        addr_m = re.search(r"Adresse\s*:\s*([^A-Z]*?[\w\s,.'’\-()]+?)"197                           r"(?=\s*(?:Loyer|Disponibilit|Caract|$))", text)198        address = addr_m.group(1).strip(" ,") if addr_m else ""199        price_m = re.search(r"Loyer\s*:\s*([\d\s,]+\$[^A-Z]*?)(?=\s*(?:Disponibilit|Caract|$))",200                            text)201        price_label = price_m.group(1).strip() if price_m else ""202        avail_m = re.search(r"Disponibilit[ée]\s*:\s*(.+?)(?=\s*Caract|$)", text)203        availability = avail_m.group(1).strip() if avail_m else ""204205        # secteur : "(Vanier)" dans l'adresse ou le titre206        sector = ""207        m = re.search(r"\(([^)]+)\)", address) or re.search(r"\(([^)]+)\)", title)208        if m:209            sector = m.group(1).strip()210211        # caractéristiques (liste <li>)212        amenities = []213        for li in re.findall(r"<li[^>]*>(.*?)</li>", content, re.S):214            t = _strip_tags(li)215            if t and t not in amenities:216                amenities.append(t)217        unit_type = normalize_unit_type(title) or normalize_unit_type(" ".join(amenities))218219        # images de l'annonce (hébergées chez DropInBlog)220        images = [u for u in dict.fromkeys(221            re.findall(r'src="(https?://[^"]+\.(?:jpg|jpeg|png|webp))"', content, re.I))]222223        # identifiant stable : slug du paramètre ?p= du lien224        qs = parse_qs(urlparse(link).query)225        ext_id = unquote(qs.get("p", [""])[0]) or _norm(re.sub(r"\W+", "-", address or title))226227        # compléter avec la page de l'immeuble correspondant (numéro civique228        # + rue) : photos, code postal, descriptif, services à proximité —229        # via le cache self.detail() (clé = hash du contenu RSS de l'annonce)230        description = text[:600]231        civic_m = re.match(r"(\d+)", address)232        if civic_m and building_pages:233            civic = civic_m.group(1)234            street_words = [w for w in re.findall(r"[a-z]{4,}", _norm(address))235                            if w not in ("avenue", "boulevard", "quebec")]236            for pg in building_pages:237                pg_n = _norm(pg)238                if re.match(r"%s\D" % re.escape(civic), pg) and \239                        any(w in pg_n for w in street_words):240                    key = hashlib.sha1(item.encode("utf-8")).hexdigest()241                    payload = self.detail(242                        ext_id, key, lambda p=pg: self._building_payload(p))243                    for full in payload.get("images") or []:244                        if full not in images:245                            images.append(full)246                    postal = payload.get("postal") or ""247                    if postal and postal not in address:248                        address = f"{address}, {postal}"249                    bits = [text]250                    if payload.get("building_desc"):251                        bits.append("Immeuble : " + payload["building_desc"])252                    if payload.get("services"):253                        bits.append("Services à proximité : " +254                                    ", ".join(payload["services"]))255                    description = " — ".join(bits)[:600]256                    break257258        city = infer_city(sector, default="Québec")259        return Listing(260            source=self.source_id,261            external_id=ext_id,262            url=link,263            title=title,264            address=address,265            sector=sector,266            city=city,267            unit_type=unit_type,268            price=parse_price(price_label),269            price_label=price_label,270            availability=availability,271            description=description,272            amenities=amenities,273            details={"contact": dict(self._contact)} if self._contact else {},274            images=images[:25],275        )276277    # -- page d'immeuble (photos, code postal, descriptif, services) -----------278    def _building_payload(self, page: str) -> dict:279        try:280            bhtml = self.get(f"{BASE}/{page}").text281        except Exception:282            return {}283        out: dict = {}284        images: list[str] = []285        extra = re.findall(286            r'(?:src|href)="((?:\./)?images/[\w\-]+\.(?:jpg|jpeg|png|webp))"',287            bhtml, re.I)288        for u in dict.fromkeys(extra):289            if re.search(r"logo|favicon|apropos|ico-", u, re.I):290                continue291            images.append(f"{BASE}/{u.lstrip('./')}")292        if images:293            out["images"] = images[:25]294295        btext = _strip_tags(bhtml)296        m = re.search(r"Code postal\s*:\s*([A-Z]\d[A-Z]\s?\d[A-Z]\d)", btext)297        if m:298            out["postal"] = m.group(1)299        # descriptif : premier paragraphe substantiel (« Immeuble situé … »)300        for p in re.findall(r"<p[^>]*>(.*?)</p>", bhtml, re.S):301            t = _strip_tags(p)302            if len(t) > 60 and not re.search(r"RSS|FeedBurner", t):303                out["building_desc"] = t[:300]304                break305        # « SERVICES À PROXIMITÉ » (liste à puces)306        m = re.search(r"PROXIMIT.*?<ul[^>]*>(.*?)</ul>", bhtml, re.S)307        if m:308            services = [_strip_tags(li)309                        for li in re.findall(r"<li[^>]*>(.*?)</li>",310                                             m.group(1), re.S)]311            services = [s for s in services if s]312            if services:313                out["services"] = services[:12]314        return out315
Files main
Menu

Theme