SPB Git

Repository Public

lespac.py 12.3 KB 303 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/lespac.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/lespac.py : LesPAC (lespac.com) — petites annonces du Québec91#   UNIQUEMENT l'immobilier ACHAT-VENTE (pas la location, pas les entreprises) :92#     b37 résidentiel · b38 terrains · b39 commercial-industriel ·93#     b40 chalets · b41 fermes · b42 immeubles à revenus94#   Les pages « /quebec/… _b{cat}k{page}R2.jsa » (toute la province) embarquent95#   `var searchResponse = {…}` côté serveur : 20 annonces/page + totalPages.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import html as _html100import json101import os102import re103104from ..schema import PropertyListing105from .base import BaseConnector106107from . import _detailutil as du108109BASE = "https://www.lespac.com"110DETAIL_LIMIT = int(os.environ.get("IMMOKA_LESPAC_DETAIL_LIMIT", "400"))111CATEGORIES = [112    (37, "immobilier-achat-vente-residentiel", "Maison"),113    (38, "immobilier-achat-vente-terrains", "Terrain"),114    (39, "immobilier-achat-vente-commercial-industriel", "Commercial"),115    (40, "immobilier-achat-vente-chalets", "Chalet"),116    (41, "immobilier-achat-vente-fermes", "Fermette"),117    (42, "immobilier-achat-vente-immeubles-a-revenus", "Immeuble à revenus"),118]119_RE_RESP = re.compile(r"var searchResponse = (\{.*?\});\s*[\r\n]", re.S)120121122class LesPacConnector(BaseConnector):123    source_id = "lespac"124    request_delay = 0.9125126    def _search_page(self, slug: str, cat: int, page: int) -> dict | None:127        url = f"{BASE}/quebec/{slug}_b{cat}k{page}R2.jsa"128        m = _RE_RESP.search(self.get(url).text)129        return json.loads(m.group(1)) if m else None130131    def _to_listing(self, r: dict, ptype: str) -> PropertyListing | None:132        lid = str(r.get("listingPublicId") or "")133        url = (r.get("listingDisplayUrl") or "").split("?")[0]134        if not lid or not url:135            return None136        # caractéristiques structurées (« Type de propriété », « Chambres »…)137        chars = {c.get("label", ""): str(c.get("value", ""))138                 for c in r.get("characteristics") or [] if c.get("label")}139        def as_int(label):140            m = re.search(r"\d+", chars.get(label, ""))141            return int(m.group(0)) if m else None142        # ville : cityLabel (accents corrects), sinon 1er segment du chemin143        seg = url.replace(BASE + "/", "").split("/")144        city = r.get("cityLabel") or (seg[0].replace("-", " ").title() if seg else "")145        images = [i["formattableImageUrl"].replace("%FORMAT%", "zoomedGallery")146                  for i in r.get("images") or [] if i.get("formattableImageUrl")]147        details = {}148        ts = r.get("publicReleaseTimestamp")   # date de mise en ligne (ms epoch)149        if ts:150            import datetime151            try:152                details["listed_at"] = datetime.datetime.fromtimestamp(153                    ts / 1000.0, datetime.timezone.utc).strftime("%Y-%m-%d")154            except (ValueError, OSError, OverflowError):155                pass156        return PropertyListing(157            source=self.source_id,158            external_id=lid,159            url=url,160            title=r.get("title") or "",161            city=city,162            property_type=chars.get("Type de propriété") or ptype,163            price=r.get("price"),164            price_label=r.get("priceLabel") or "",165            bedrooms=as_int("Chambres"),166            bathrooms=as_int("Salles de bain") or as_int("Salle de bain"),167            year_built=as_int("Année de construction"),168            description=(r.get("description") or "")[:2000],169            features=[f"{k} : {v}" for k, v in chars.items()],170            details=details,171            images=images,172            broker_name=r.get("advertiserName") or "LesPAC (particuliers)",173            agency="LesPAC Québec",174        )175176    def fetch(self) -> list[PropertyListing]:177        out: dict[str, PropertyListing] = {}178        for cat, slug, ptype in CATEGORIES:179            page, total_pages = 1, 1180            while page <= total_pages:181                try:182                    d = self._search_page(slug, cat, page)183                except Exception:184                    break185                if not d:186                    break187                total_pages = min(int(d.get("totalPages") or 1), 400)188                for r in d.get("searchResults") or []:189                    lst = self._to_listing(r, ptype)190                    if lst is not None:191                        out.setdefault(lst.uid, lst)192                page += 1193        listings = list(out.values())194        # v2 = TOUTES les boîtes de caractéristiques (l'ancien parseur ne lisait195        # que la 1re) + salles de bain/d'eau + superficies (dimensions du terrain)196        du.enrich(self, listings, DETAIL_LIMIT, _parse_lespac_detail, key="v2")197        return listings198199200def _clean(s: str) -> str:201    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", s))).strip()202203204def _area_pi2(value: str) -> float | None:205    """« 1 200 pi2 » / « 111 m2 » -> pi² (via la normalisation commune)."""206    from ..normalize import parse_area_sqft207    return parse_area_sqft(value)208209210_DIMS_RE = re.compile(r"([\d\s]+(?:,\d+)?)\s*x\s*([\d\s]+(?:,\d+)?)\s*(pieds|m[èe]tres)",211                      re.I)212213214def _dims_pi2(value: str) -> float | None:215    """« 15,24 x 30,48 mètres » / « 50 x 100 pieds » -> superficie en pi²."""216    m = _DIMS_RE.search(value or "")217    if not m:218        return None219    try:220        a = float(m.group(1).replace(" ", "").replace(",", "."))221        b = float(m.group(2).replace(" ", "").replace(",", "."))222    except ValueError:223        return None224    if a <= 0 or b <= 0 or a > 100000 or b > 100000:225        return None226    s = a * b227    if m.group(3).lower().startswith("m"):228        s *= 10.7639229    return round(s) if s >= 300 else None    # < 300 pi² : dimensions suspectes230231232def _parse_lespac_detail(html: str) -> dict:233    """Fiche LesPAC : description complète, adresse civique, caractéristiques234    (boîte « Caractéristiques » : <p><span>Label</span><span>Valeur</span></p>)235    et galerie pleine taille (binary/basephoto)."""236    out: dict = {}237    md = re.search(r'class="description"[^>]*>(.*?)</(?:p|div)>', html, re.S | re.I)238    if md:239        desc = _clean(md.group(1))240        if desc:241            out["description"] = desc[:6000]242    features, details = [], {}243    # section « Caractéristiques » -> fin des boîtes : PLUSIEURS <div class="box">244    # (types, équipements, description des pièces…) — on lit toutes les rangées245    # <p><span>Label</span> <span>Valeur</span> jusqu'à la bannière suivante.246    i = html.find(">Caractéristiques</p>")247    if i >= 0:248        j = html.find("pub-middle-listing-detail", i)249        seg = html[i:j if j > i else i + 30000]250        for lm, vm in re.findall(r"<p><span>(.*?)</span>\s*<span>(.*?)</span>",251                                 seg, re.S):252            label, value = _clean(lm), _clean(vm)253            if not label or not value or len(label) > 45 or len(value) > 120:254                continue255            if label not in details:256                features.append(f"{label} : {value}")257                details[label] = value258            low = label.lower()259            if label == "Adresse" and re.match(r"\s*\d", value):260                out["address"] = value261            elif label == "Année":262                my = re.search(r"(18|19|20)\d{2}", value)263                if my:264                    out["year_built"] = int(my.group(0))265            elif label == "Type de propriété":266                out["property_type"] = value267            elif "chambre" in low:268                mn = re.search(r"\d+", value)269                if mn:270                    out["bedrooms"] = int(mn.group(0))271            elif "salle" in low and "eau" in low and "bain" not in low:272                mn = re.search(r"\d+", value)273                if mn and int(mn.group(0)) > 0:274                    out["powder_rooms"] = int(mn.group(0))275            elif "salle" in low and "bain" in low:276                mn = re.search(r"\d+", value)277                if mn:278                    out["bathrooms"] = int(mn.group(0))279            elif "superficie" in low and "terrain" in low:280                v = _area_pi2(value)281                if v:282                    out["lot_sqft"] = v283            elif "superficie" in low:284                v = _area_pi2(value)285                if v:286                    out["area_sqft"] = v287            elif label == "Dimension du terrain":288                v = _dims_pi2(value)289                if v:290                    out["lot_sqft"] = v291    if features:292        out["features"] = features293    if details:294        out["details"] = details295    imgs, seen = [], set()296    for u in re.findall(r'https://cdn\.lespac\.com/binary/basephoto/\d+\.jpg', html):297        if u not in seen:298            seen.add(u)299            imgs.append(u)300    if imgs:301        out["images"] = imgs302    return out303
Files main
Menu

Theme