SPB Git

Repository Public

prona.py 12.2 KB 303 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/prona.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/prona.py : connecteur Gestion Prona (gestionprona.ca)91#   Gestionnaire multi-régions : Cowansville, Saint-Jean-sur-Richelieu,92#   Saint-Hubert, Candiac, Saint-Hyacinthe (Montérégie) + Montréal, Québec,93#   Blainville. WordPress + thème immobilier Houzez rendu serveur (même94#   plateforme qu'immeubles_bc) : la page /properties/ expose des cartes95#   .item-listing-wrap (data-listid STABLE, titre, adresse taxonomique,96#   prix, chambres/sdb). La fiche /property/<slug>/ (via cache BD) fournit97#   la VILLE structurée (champ « Ville » du bloc adresse — la taxonomie de98#   la carte liste mêle quartier/arrondissement/MRC), la description, les99#   caractéristiques, le GPS et la galerie. Les locaux commerciaux/bureaux100#   sont exclus.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://gestionprona.ca"113LIST_URL = f"{BASE}/properties/"114115_COMMERCIAL_RE = re.compile(116    r"commerc|bureau|\blocal\b|stationnement|garage|entrep[oô]t", re.I)117_MAP_LATLNG_RE = re.compile(118    r'"lat"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"lng"\s*:\s*"?(-?\d+\.\d+)"?')119# suffixe de redimensionnement WordPress (« -592x444.jpg » -> pleine taille)120_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)121_IMG_RE = re.compile(122    r"https://gestionprona\.ca/wp-content/uploads/[^\"'\s\\)]+"123    r"\.(?:jpe?g|png|webp)", re.I)124_SKIP_IMG = re.compile(r"logo|icon|favicon|-\d{2,3}x\d{2,3}\.", re.I)125126127def _clean_price_label(label: str) -> str:128    """'$1,450/mois' -> '$1450/mois' (virgule = milliers, pour parse_price)."""129    return re.sub(r"(\d),(\d{3})", r"\1\2", label)130131132class PronaConnector(BaseConnector):133    source_id = "prona"134    request_delay = 0.6135    max_details = 40     # garde-fou fiches détail (vraies requêtes par sync)136137    def fetch(self) -> list[Listing]:138        html = self.get(LIST_URL).text139        soup = BeautifulSoup(html, "html.parser")140141        listings: dict[str, Listing] = {}142        for card in soup.select("div.item-listing-wrap"):143            try:144                self._parse_card(card, listings)145            except Exception:146                continue147148        # fiches détail (cache BD) : ville structurée, description, GPS…149        self._fetched = 0150        for lst in listings.values():151            key = hashlib.sha1(152                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"153                .encode("utf-8")).hexdigest()[:16]154            try:155                payload = self.detail(lst.external_id, key,156                                      lambda u=lst.url: self._fetch_detail(u))157            except Exception:158                continue159            self._apply_detail(lst, payload)160        return list(listings.values())161162    # -- carte Houzez -----------------------------------------------------------163    def _parse_card(self, card, listings: dict[str, Listing]) -> None:164        link = card.select_one("h2.item-title a[href]")165        if not link:166            return167        url = link["href"]168        title = link.get_text(strip=True)169        m = re.search(r"/property/([^/]+)/?", url)170        slug = m.group(1) if m else ""171        listid_el = card.select_one("[data-listid]")172        ext_id = (listid_el.get("data-listid") if listid_el else "") or slug173        if not ext_id or str(ext_id) in listings:174            return175        if _COMMERCIAL_RE.search(title):176            return                              # local commercial : exclu177178        status_el = card.select_one(".label-status")179        availability = status_el.get_text(strip=True) if status_el else ""180        if re.search(r"lou[ée]", availability, re.I):181            return182183        addr_el = card.select_one("address.item-address")184        address = addr_el.get_text(" ", strip=True) if addr_el else ""185186        price_el = card.select_one("li.item-price")187        price_label = price_el.get_text(strip=True) if price_el else ""188189        amenities: list[str] = []190        beds = ""191        beds_el = card.select_one("li.h-beds .hz-figure")192        if beds_el:193            beds = beds_el.get_text(strip=True)194            if beds:195                amenities.append(f"{beds} chambre(s)")196        baths_el = card.select_one("li.h-baths .hz-figure")197        if baths_el and baths_el.get_text(strip=True):198            amenities.append(f"{baths_el.get_text(strip=True)} salle(s) de bain")199200        unit_type = ""201        if beds.isdigit():202            unit_type = "Studio" if beds == "0" else \203                normalize_unit_type(f"{beds} chambres")204        # le titre porte souvent le vrai type (« Grand 4.5 … »)205        m = re.search(r"\b(\d[½.]5?)\b", title)206        if m:207            t = normalize_unit_type(m.group(1))208            if re.match(r"^\d½$", t):209                unit_type = t210211        images: list[str] = []212        thumb = card.select_one("img.wp-post-image[src]")213        if thumb:214            images = [_SIZE_SUFFIX.sub("", thumb["src"])]215216        listings[str(ext_id)] = Listing(217            source=self.source_id,218            external_id=str(ext_id),219            url=url,220            title=title,221            address=address,222            unit_type=unit_type,223            price=parse_price(_clean_price_label(price_label)),224            price_label=price_label,225            availability=availability,226            amenities=amenities,227            images=images,228        )229230    # -- fiche détail (Houzez) ----------------------------------------------------231    def _fetch_detail(self, url: str) -> dict:232        """Ville structurée, adresse, description, caractéristiques, GPS."""233        if self._fetched >= self.max_details:234            raise RuntimeError("budget de fiches détail atteint")235        self._fetched += 1236        html = self.get(url).text237        soup = BeautifulSoup(html, "html.parser")238        out: dict = {}239240        # bloc adresse : lignes « <label> <valeur> » (Ville, Adresse…)241        for li in soup.select("#property-address-wrap li"):242            txt = li.get_text(" ", strip=True)243            m = re.match(r"^(Adresse|Ville)\s+(.+)$", txt)244            if m:245                out["ville" if m.group(1) == "Ville" else "adresse"] = \246                    m.group(2).strip()247248        desc_el = soup.select_one("#property-description-wrap")249        if desc_el:250            txt = desc_el.get_text("\n", strip=True)251            txt = re.sub(r"^(La )?[Dd]escription\n", "", txt)252            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1200]253254        feats = [a.get_text(" ", strip=True)255                 for a in soup.select("#property-features-wrap li")256                 if a.get_text(strip=True)]257        # bloc « Détails » structuré (superficie, pièces…)258        for li in soup.select("#property-detail-wrap li"):259            txt = re.sub(r"\s+", " ", li.get_text(" ", strip=True))260            m = re.match(r"^Taille de la propriété:\s*([\d,\s]+)\s*sqft", txt)261            if m:262                try:263                    out["area"] = float(m.group(1).replace(",", "")264                                        .replace(" ", ""))265                except ValueError:266                    pass267        out["amenities"] = feats[:20]268269        m = _MAP_LATLNG_RE.search(html)270        if m:271            out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))272273        imgs = [u for u in dict.fromkeys(_IMG_RE.findall(html))274                if not _SKIP_IMG.search(u)]275        out["images"] = imgs[:20]276        return out277278    def _apply_detail(self, lst: Listing, d: dict) -> None:279        if not d:280            return281        if d.get("ville"):282            lst.city = d["ville"]283        if d.get("adresse"):284            lst.address = d["adresse"]285        if not lst.city and d.get("adresse"):286            # repli : sans champ « Ville », la 3e composante de l'adresse287            # complète Houzez est la municipalité (n°, rue, ville, MRC…)288            parts = [p.strip() for p in d["adresse"].split(",") if p.strip()]289            if len(parts) >= 3 and not re.search(r"\d", parts[2]):290                lst.city = parts[2]291        desc = d.get("description") or ""292        if desc and desc.strip() != lst.address.strip():293            lst.description = desc294        if d.get("amenities"):295            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))296        if d.get("area") and lst.area_sqft is None:297            if 80 <= d["area"] <= 20000:298                lst.area_sqft = d["area"]299        if d.get("lat") is not None and d.get("lng") is not None:300            lst.lat, lst.lng = d["lat"], d["lng"]301        if d.get("images"):302            lst.images = d["images"]303
Files main
Menu

Theme