SPB Git

Repository Public

barnes_quebec.py 16.6 KB 388 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/barnes_quebec.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-3014#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/barnes_quebec.py : BARNES Québec (barnes-quebec.com)91#   Site WordPress indexé dans Algolia. La config expose l'App ID et une clé92#   API dans le HTML (PHPVars) ; l'index « quebec_all » contient les propriétés93#   (type "property") avec adresse, prix, MLS, chambres, salles de bains,94#   superficie et géolocalisation. Les enregistrements sont dupliqués par95#   langue → on dédoublonne par référence MLS. Les permaliens pointent vers le96#   domaine de staging Kinsta ; on les réécrit vers le domaine de production.97#   RÉSILIENCE : la clé Algolia a déjà été rotée (403 le 2026-08-15) — on98#   l'extrait donc À CHAQUE FOIS du HTML public du site (avec cache process),99#   avec repli sur la dernière clé connue si l'extraction échoue.100#   FIABILITÉ (2026-08-18) : l'index Algolia conserve des fiches PÉRIMÉES101#   (vendues/retirées de WordPress) dont la page ET les photos renvoient 404102#   (~100 fiches sur ~340, soit les « annonces sans images »). Le sitemap103#   Yoast (property/rental/new-construction) est la source de vérité de ce104#   qui est publié : on filtre les fiches mortes, et on répare les slugs105#   renommés via la réf MLS présente dans les noms de fichiers image du106#   sitemap. La galerie de la fiche est aussi isolée par sa réf MLS (les107#   pages affichent des « propriétés similaires » qui polluaient la galerie).108# -----------------------------------------------------------------------------109from __future__ import annotations110111import os112import re113import time114115import requests116117from .base import BaseConnector118from . import _detailutil as du119from ..schema import PropertyListing120121DETAIL_LIMIT = int(os.environ.get("IMMOKA_BARNES_DETAIL_LIMIT", "400"))122# Galerie WordPress : .../wp-content/uploads/AAAA/MM/{ref}-{hash}-{L}x{H}.jpg123_IMG_RE = re.compile(124    r'https://barnes-quebec\.com/wp-content/uploads/\d{4}/\d{2}/[^"\'\\ ]+?\.(?:jpg|jpeg|png|webp)',125    re.I)126_SIZE_RE = re.compile(r'-(\d{2,4})x(\d{2,4})(?=\.[a-z]+$)', re.I)127128# Repli : derniers identifiants Algolia connus (si l'extraction échoue).129APP_ID = "HCW55VIQNM"130API_KEY = "6319a160319545bfd5dafbb01ffa4ca6"131INDEX = "quebec_all"132SITE = "https://barnes-quebec.com"133STAGING = "stg-quebec-staging.kinsta.cloud"134HITS_PER_PAGE = 100135MAX_PAGES = 40136137# Identifiants publiés dans PHPVars (wp_localize_script du plugin barnes-algolia)138_APP_ID_RE = re.compile(r'"algolia_application_id"\s*:\s*"([A-Za-z0-9]{8,16})"')139# 2026-08-29 : le site ne publie plus l'admin key, seulement la search key140_API_KEY_RE = re.compile(141    r'"algolia_(?:search|admin)_api_key"\s*:\s*"([0-9a-fA-F]{16,64})"')142_PREFIX_RE = re.compile(r'"algolia_index_prefix"\s*:\s*"([A-Za-z0-9_-]{1,32})"')143_CREDS_TTL = 6 * 3600          # ré-extraire au plus toutes les 6 h par process144_creds_cache: tuple[str, str, str] | None = None145_creds_ts = 0.0146147# Sitemaps Yoast = pages réellement publiées (l'index Algolia, lui, traîne148# des fiches supprimées). Les <image:loc> commencent par la réf MLS.149_SITEMAPS = ("/property-sitemap.xml", "/rental-sitemap.xml",150             "/new-construction-sitemap.xml")151_SM_BLOCK_RE = re.compile(r"<url>(.*?)</url>", re.S)152_SM_LOC_RE = re.compile(r"<loc>\s*(https://[^<\s]+)")153_SM_IMG_MLS_RE = re.compile(r"<image:loc>\s*https://[^<\s]*/(\d{6,9})-")154# réf MLS en tête du nom de fichier image (suivie du hash hexadécimal)155_MLS_PFX_RE = re.compile(r"/(\d{6,9})-[0-9a-f]")156157158class BarnesQuebecConnector(BaseConnector):159    source_id = "barnes_quebec"160    request_delay = 0.25161    use_detail_cache = False162163    def fetch(self) -> list[PropertyListing]:164        best: dict[str, tuple[int, PropertyListing]] = {}165        page = 0166        while page < MAX_PAGES:167            data = self._query(page)168            hits = data.get("hits", [])169            if not hits:170                break171            for h in hits:172                if h.get("type") != "property":173                    continue174                lst = self._to_listing(h)175                if lst is None:176                    continue177                # une propriété apparaît en plusieurs langues et parfois en178                # doublon « Contact us » (sans prix). Clé stable = adresse179                # normalisée ; on garde la meilleure fiche (prix connu + FR).180                key = " ".join(lst.title.split()).lower()181                score = (2 if lst.price else 0) + (1 if h.get("lang_fr") == 1 else 0)182                if key not in best or score > best[key][0]:183                    best[key] = (score, lst)184            if page + 1 >= data.get("nbPages", 0):185                break186            page += 1187        listings = [lst for _, lst in best.values()]188        # Filtre anti-fiches périmées : Algolia garde des enregistrements de189        # propriétés retirées du site (page + photos 404). On ne garde que ce190        # que le sitemap publie ; slug renommé → réparé via la réf MLS.191        live, by_mls = self._live_pages()192        if len(live) >= 100:      # garde-fou : sitemap indisponible → pas de filtre193            kept = []194            for lst in listings:195                url = lst.url.rstrip("/") + "/"196                if url in live:197                    kept.append(lst)198                elif lst.mls and lst.mls in by_mls:199                    lst.url = by_mls[lst.mls]   # republiée sous un nouveau slug200                    kept.append(lst)201                # sinon : fiche morte (vendue/retirée) → non publiée202            listings = kept203        # Algolia ne contient pas les photos : on les récupère sur la fiche.204        # Une page peut être 404 même listée au sitemap (retrait très récent,205        # cache Yoast) : on l'écarte du résultat de ce cycle.206        dead: set[str] = set()207208        def _fetch(url: str) -> str:209            try:210                return self.get(url).text211            except requests.HTTPError as e:212                if e.response is not None and e.response.status_code in (404, 410):213                    dead.add(url)214                raise215216        du.enrich(self, listings, DETAIL_LIMIT, parse_barnes_detail, key="v3",217                  fetch_html=_fetch)218        return [lst for lst in listings if lst.url not in dead]219220    # -- pages réellement publiées (sitemaps Yoast) -----------------------------221    def _live_pages(self) -> tuple[set[str], dict[str, str]]:222        """(URLs vivantes, réf MLS -> URL FR) depuis les sitemaps du site."""223        live: set[str] = set()224        by_mls: dict[str, str] = {}225        for path in _SITEMAPS:226            try:227                xml = self.get(SITE + path).text228            except Exception:229                continue230            for block in _SM_BLOCK_RE.findall(xml):231                m = _SM_LOC_RE.search(block)232                if not m:233                    continue234                loc = m.group(1).rstrip("/") + "/"235                live.add(loc)236                for mls in _SM_IMG_MLS_RE.findall(block):237                    if "/en/" not in loc:238                        by_mls[mls] = loc           # la version FR gagne239                    else:240                        by_mls.setdefault(mls, loc)241        return live, by_mls242243    # -- identifiants Algolia (auto-extraits du site, avec cache) --------------244    def _algolia_creds(self, force: bool = False) -> tuple[str, str, str]:245        """(app_id, api_key, index) lus dans le HTML public — résilient à une246        rotation de clé. Cache process (TTL 6 h) ; repli : dernière clé connue."""247        global _creds_cache, _creds_ts248        if not force and _creds_cache and time.time() - _creds_ts < _CREDS_TTL:249            return _creds_cache250        creds = None251        for path in ("/acheter/", "/louer/", "/"):252            try:253                html = self.get(SITE + path).text254            except Exception:255                continue256            m_app, m_key = _APP_ID_RE.search(html), _API_KEY_RE.search(html)257            if m_app and m_key:258                m_pfx = _PREFIX_RE.search(html)259                index = (m_pfx.group(1) + "_all") if m_pfx else INDEX260                creds = (m_app.group(1), m_key.group(1), index)261                break262        _creds_cache = creds or (APP_ID, API_KEY, INDEX)263        _creds_ts = time.time()264        return _creds_cache265266    def _query(self, page: int) -> dict:267        app_id, api_key, index = self._algolia_creds()268        try:269            return self._post_query(app_id, api_key, index, page)270        except Exception:271            # clé rotée depuis la mise en cache : ré-extraire, sinon repli connu272            app2, key2, idx2 = self._algolia_creds(force=True)273            if (app2, key2, idx2) == (app_id, api_key, index):274                app2, key2, idx2 = APP_ID, API_KEY, INDEX275            return self._post_query(app2, key2, idx2, page)276277    def _post_query(self, app_id: str, api_key: str, index: str,278                    page: int) -> dict:279        resp = self.post(280            f"https://{app_id.lower()}-dsn.algolia.net/1/indexes/{index}/query",281            headers={"X-Algolia-API-Key": api_key,282                     "X-Algolia-Application-Id": app_id,283                     "Content-Type": "application/json"},284            json={"params": f"hitsPerPage={HITS_PER_PAGE}&page={page}"},285        )286        return resp.json()287288    def _to_listing(self, h: dict) -> PropertyListing | None:289        object_id = str(h.get("objectID") or "")290        mls = str(h.get("property_mls_reference") or "").strip()291        if not object_id and not mls:292            return None293294        permalink = (h.get("permalink") or "").replace(STAGING, "barnes-quebec.com")295        if permalink.startswith("http://"):296            permalink = "https://" + permalink[len("http://"):]297298        price = h.get("property_price") or 0299        try:300            price = float(price)301        except (TypeError, ValueError):302            price = 0.0303        price_label = h.get("property_pretty_price") or ""304305        area = _pos(h.get("property_area"))306        land = _pos(h.get("property_land_area"))307        lat = h.get("property_address_latitude") or None308        lng = h.get("property_address_longitude") or None309        try:310            lat = float(lat) if lat else None311            lng = float(lng) if lng else None312        except (TypeError, ValueError):313            lat = lng = None314        if lat == 0 or lng == 0:315            lat = lng = None316317        return PropertyListing(318            source=self.source_id,319            external_id=mls or object_id,320            url=permalink or SITE + "/property/",321            title=(h.get("title") or "").strip(),322            address=(h.get("title") or "").strip(),323            city=(h.get("property_address_city") or "").strip(),324            region=(h.get("region") or "").strip(),325            property_type=(h.get("property_type") or "").strip(),326            price=price if price > 0 else None,327            price_label=price_label,328            bedrooms=_pos(h.get("property_bedrooms_integer")),329            bathrooms=_pos(h.get("property_bathrooms")),330            area_sqft=area,331            lot_sqft=land,332            mls=mls,333            description=(h.get("content") or "")[:4000],334            lat=lat,335            lng=lng,336            broker_name="BARNES Québec",337        )338339340def _pos(v):341    try:342        n = float(v)343        return int(n) if n and n > 0 else None344    except (TypeError, ValueError):345        return None346347348def parse_barnes_detail(html: str) -> dict:349    """Galerie photo pleine résolution (absente d'Algolia) + description/pièces."""350    out: dict = {}351    if re.search(r'class="[^"]*\berror404\b', html):352        return out          # page « introuvable » : fiche retirée, ne rien capter353    # regroupe par image de base (sans le suffixe -LxH), garde la plus grande ;354    # l'ordre d'insertion du dict = ordre d'apparition dans la page (= galerie)355    best: dict[str, tuple[int, str]] = {}356    for u in _IMG_RE.findall(html):357        m = _SIZE_RE.search(u)358        area = int(m.group(1)) * int(m.group(2)) if m else 10 ** 8   # sans suffixe = original359        base = _SIZE_RE.sub("", u)360        if base not in best or area > best[base][0]:361            best[base] = (area, u)362    # la galerie de la fiche = les fichiers préfixés par SA réf MLS ; la page363    # affiche aussi des « propriétés similaires » (autres réfs MLS) et des364    # visuels éditoriaux → on garde le préfixe numérique dominant (nb de bases365    # distinctes), départagé par ordre d'apparition (le héros vient en premier)366    counts: dict[str, int] = {}367    first: dict[str, int] = {}368    for i, base in enumerate(best):369        m = _MLS_PFX_RE.search(base)370        if m:371            counts[m.group(1)] = counts.get(m.group(1), 0) + 1372            first.setdefault(m.group(1), i)373    if counts:374        own = max(counts, key=lambda p: (counts[p], -first[p]))375        imgs = [u for base, (_, u) in best.items()376                if (m := _MLS_PFX_RE.search(base)) and m.group(1) == own]377    else:   # aucune image nommée par réf MLS : comportement d'origine378        imgs = [u for _, u in best.values()]379    if imgs:380        out["images"] = imgs[:60]381    desc = du.ld_description(html)382    if desc:383        out["description"] = desc384    _det = du.centris_details(du.flatten(html))385    if _det:386        out.setdefault("details", {}).update(_det)387    return out388
Files main
Menu

Theme