Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/barnes_quebec.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1213# Last Modified : 2026-08-2914#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/barnes_quebec.py : BARNES Québec (barnes-quebec.com) — LOCATIONS91# Agence de prestige (Montréal, Québec, Laval, Mont-Tremblant…). Site92# WordPress indexé dans Algolia ; la config expose l'App ID et une clé API93# dans le HTML. L'index « quebec_all » mélange ventes (type "property") et94# locations (type "rental") : on filtre côté serveur avec95# facetFilters=[["type:rental"]]. Chaque location porte le loyer mensuel96# numérique (property_rent), l'adresse, chambres/salles de bains, superficie97# et géolocalisation. Les enregistrements sont dupliqués par langue (FR/EN) →98# on dédoublonne par titre normalisé en gardant la fiche FR. Adapté du99# connecteur « à vendre » d'Immo-Ka (agent-courtage/immoka).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import os104import re105106from ..schema import Listing107from .base import BaseConnector108109from . import _detailutil as du110111APP_ID = "HCW55VIQNM"112# clé « search-only » publiée dans le HTML (var AlgoliaPHPVars) — elle TOURNE113# (rotation constatée 2026-08-29 : 403 sur l'ancienne clé). On la relit à114# chaque sync depuis /louer/ ; cette constante n'est qu'un secours.115API_KEY_FALLBACK = "6319a160319545bfd5dafbb01ffa4ca6"116_API_KEY_RE = re.compile(r'"algolia_search_api_key"\s*:\s*"([0-9a-f]{16,64})"')117INDEX = "quebec_all"118QUERY_URL = f"https://{APP_ID}-dsn.algolia.net/1/indexes/{INDEX}/query"119SITE = "https://barnes-quebec.com"120STAGING = "stg-quebec-staging.kinsta.cloud" # permaliens parfois en staging121HITS_PER_PAGE = 100122MAX_PAGES = 40123# facetFilters=[["type:rental"]] URL-encodé (le corps Algolia est un query string)124FACET_RENTAL = "facetFilters=%5B%5B%22type%3Arental%22%5D%5D"125DETAIL_LIMIT = int(os.environ.get("LOUKA_BARNES_DETAIL_LIMIT", "200"))126127# Galerie WordPress : .../wp-content/uploads/AAAA/MM/{ref}-{hash}-{L}x{H}.jpg128_IMG_RE = re.compile(129 r'https://barnes-quebec\.com/wp-content/uploads/\d{4}/\d{2}/[^"\'\\ ]+?\.(?:jpg|jpeg|png|webp)',130 re.I)131_SIZE_RE = re.compile(r'-(\d{2,4})x(\d{2,4})(?=\.[a-z]+$)', re.I)132# ville Algolia au format « Montréal (Rosemont/La Petite-Patrie) »133_CITY_SECTOR_RE = re.compile(r"^(.*?)\s*\(([^)]+)\)\s*$")134135# caractéristiques de la fiche Barnes (table Centris rendue « libellé | valeur »136# uniquement — l'ordre inverse capte la table des pièces et produit du bruit)137_DETAIL_LABELS = [138 "Année de construction", "Superficie habitable", "Superficie du terrain",139 "Stationnement", "Garage", "Mode de chauffage", "Énergie pour le chauffage",140 "Piscine", "Vue", "Zonage", "Date d'emménagement", "Bail", "Meublé",141 "Animaux", "Inclus dans le loyer",142]143144145class BarnesQuebecConnector(BaseConnector):146 source_id = "barnes_quebec"147 request_delay = 0.25148149 def fetch(self) -> list[Listing]:150 self._api_key = self._resolve_api_key()151 # une location apparaît en plusieurs langues (FR/EN) avec des objectID152 # distincts mais le même titre. Clé stable = titre normalisé ; on garde153 # la meilleure fiche (loyer connu + FR).154 best: dict[str, tuple[int, Listing]] = {}155 page = 0156 while page < MAX_PAGES:157 data = self._query(page)158 hits = data.get("hits", [])159 if not hits:160 break161 for h in hits:162 if h.get("type") != "rental": # ceinture + bretelles163 continue164 lst = self._to_listing(h)165 if lst is None:166 continue167 key = " ".join(lst.title.split()).lower()168 score = (2 if lst.price else 0) + (1 if h.get("lang_fr") == 1 else 0)169 if key not in best or score > best[key][0]:170 best[key] = (score, lst)171 if page + 1 >= data.get("nbPages", 0):172 break173 page += 1174 listings = [lst for _, lst in best.values()]175 # Algolia n'expose qu'une photo : la galerie vient de la fiche.176 du.enrich(self, listings, DETAIL_LIMIT, parse_barnes_detail, key="v1")177 return listings178179 def _resolve_api_key(self) -> str:180 """Relit la clé search dans le HTML de /louer/ (elle tourne)."""181 try:182 m = _API_KEY_RE.search(self.get(SITE + "/louer/").text)183 if m:184 return m.group(1)185 except Exception: # noqa: BLE001 — page indisponible : on tente le secours186 pass187 return API_KEY_FALLBACK188189 def _query(self, page: int) -> dict:190 resp = self.post(191 QUERY_URL,192 headers={"X-Algolia-API-Key": self._api_key,193 "X-Algolia-Application-Id": APP_ID,194 "Content-Type": "application/json"},195 json={"params": f"hitsPerPage={HITS_PER_PAGE}&page={page}&{FACET_RENTAL}"},196 )197 return resp.json()198199 def _to_listing(self, h: dict) -> Listing | None:200 object_id = str(h.get("objectID") or "")201 mls = str(h.get("property_mls_reference") or "").strip()202 if not object_id and not mls:203 return None204205 permalink = (h.get("permalink") or "").replace(STAGING, "barnes-quebec.com")206 if permalink.startswith("http://"):207 permalink = "https://" + permalink[len("http://"):]208209 # loyer mensuel : champ numérique dédié (property_price est null pour210 # les locations). property_pretty_rent = libellé propre sans HTML.211 rent = h.get("property_rent") or 0212 try:213 rent = float(rent)214 except (TypeError, ValueError):215 rent = 0.0216 price_label = (h.get("property_pretty_rent") or "").strip()217218 # « Montréal (Rosemont/La Petite-Patrie) » -> ville + secteur219 city_raw = (h.get("property_address_city") or "").strip()220 m = _CITY_SECTOR_RE.match(city_raw)221 city, sector = (m.group(1), m.group(2)) if m else (city_raw, "")222 regions = h.get("regions") or []223 if not city and regions: # rare : fiche sans ville renseignée224 city = str(regions[0]).strip()225226 # le titre concatène adresse + ville (+ région) : on isole la rue227 title = (h.get("title") or "").strip()228 address = title229 if city_raw and city_raw in title:230 address = title[:title.find(city_raw)].strip(" ,-")231232 beds = _pos(h.get("property_bedrooms_integer"))233 unit_type = ""234 if beds is not None:235 unit_type = "Studio" if beds == 0 else f"{beds} chambres"236237 lat = h.get("property_address_latitude") or None238 lng = h.get("property_address_longitude") or None239 try:240 lat = float(lat) if lat else None241 lng = float(lng) if lng else None242 except (TypeError, ValueError):243 lat = lng = None244 if lat == 0 or lng == 0:245 lat = lng = None246247 details: dict = {"Agence": "BARNES Québec"}248 if mls:249 details["No Centris"] = mls250 baths = _pos(h.get("property_bathrooms"))251 if baths is not None:252 details["Salles de bain"] = str(baths)253 rooms = _pos(h.get("property_rooms"))254 if rooms is not None:255 details["Nombre de pièces"] = str(rooms)256 ptype = (h.get("property_type") or "").strip()257 if ptype:258 details["Type de propriété"] = ptype259 if regions:260 details["Région"] = str(regions[0])261262 # image « liste » (la galerie complète vient de la fiche détail)263 images = []264 for k in ("image_full", "image_large", "image_medium"):265 if h.get(k):266 images = [h[k]]267 break268269 return Listing(270 source=self.source_id,271 external_id=mls or object_id,272 url=permalink or SITE + "/rental/",273 title=title,274 address=address,275 sector=sector,276 city=city,277 unit_type=unit_type,278 price=rent if rent > 0 else None, # explicite : pas de plafond parse_price279 price_label=price_label,280 area_sqft=_posf(h.get("property_area")),281 description=(h.get("content") or "")[:4000],282 details=details,283 images=images,284 lat=lat,285 lng=lng,286 )287288289def _pos(v):290 try:291 n = float(v)292 return int(n) if n and n > 0 else None293 except (TypeError, ValueError):294 return None295296297def _posf(v):298 try:299 n = float(v)300 return n if n > 0 else None301 except (TypeError, ValueError):302 return None303304305def parse_barnes_detail(html: str) -> dict:306 """Galerie photo pleine résolution (absente d'Algolia) + description/pièces."""307 out: dict = {}308 # regroupe par image de base (sans le suffixe -LxH), garde la plus grande309 best: dict[str, tuple[int, str]] = {}310 for u in _IMG_RE.findall(html):311 m = _SIZE_RE.search(u)312 area = int(m.group(1)) * int(m.group(2)) if m else 10 ** 8 # sans suffixe = original313 base = _SIZE_RE.sub("", u)314 if base not in best or area > best[base][0]:315 best[base] = (area, u)316 imgs = [u for _, u in best.values()]317 # ignore les vignettes de courtiers/logos (les photos gardent la réf Centris chiffrée)318 imgs = [u for u in imgs if re.search(r"/\d{6,}", u)] or imgs319 if imgs:320 out["images"] = imgs[:60]321 desc = du.ld_description(html)322 if desc:323 out["description"] = desc324 text = du.flatten(html)325 det: dict = {}326 for label in _DETAIL_LABELS:327 m = re.search(re.escape(label) + r"\b\s*\|\s*([^|]{1,55})", text)328 if m:329 val = m.group(1).strip(" |,")330 if val and 1 <= len(val) <= 55 and val.lower() != label.lower():331 det[label] = val332 if det:333 out.setdefault("details", {}).update(det)334 return out335