Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/glmc.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1613# Last Modified : 2026-09-1314#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/glmc.py : Les Immeubles GLMC (glmc.ca) — Rivière-du-Loup + KRTB /91# Témiscouata / Les Basques (Bas-Saint-Laurent). Plus grosse agence92# indépendante de l'Est du Québec. Site WordPress (plugin mw-centris, thème X),93# liste rendue SERVEUR sur /proprietes/, paginée par ?pg=N (60/page, ~17694# fiches). Chaque carte : lien /proprietes/{adresse-slug}-{n°Centris}/ (le n°95# Centris termine le slug), adresse+ville, photo. Prix/chambres via la page96# détail (enrichissement plafonné + cache). La section « Vendus » (fiches97# vendues, après la pagination) est exclue du parsing.98#99# Page détail (thème X / Cornerstone) : PAS de JSON-LD propriété — tout est100# dans le HTML : stats à icônes « N pièces / N chambre(s) / N salle(s) de101# bain / N salle d'eau », description dans <ul class="remarques-list">,102# caractéristiques dans des grilles x-cell alternant libellé/valeur103# (Genre, Année de construction, Terrain [dimensions puis superficie],104# évaluations, taxes…), Inclusions/Exclusions en x-text, courtier(s) dans105# .mw-courtier-card (nom + tel:), galerie = photos Centris re-hébergées106# /wp-content/uploads/…/{md5}.jpg (nom 32 hex, pleine résolution, ordre107# d'origine — les logos/portraits ont un nom lisible et sont donc exclus).108# Coordonnées GPS : chargées en AJAX par mw-centris-map → non exposées.109#110# source_id « glmc_ag_qc » : infixe _ag_ = dédup Centris (db.refresh_dedup) —111# si le n° Centris est déjà porté par une bannière couverte, la fiche est112# masquée ; les inscriptions propres de GLMC restent visibles.113# -----------------------------------------------------------------------------114from __future__ import annotations115116import html as _html117import os118import re119120from .base import BaseConnector121from . import _detailutil as du122from ..normalize import parse_price123from ..schema import PropertyListing124125SITE = "https://www.glmc.ca"126LISTING = SITE + "/proprietes/"127DETAIL_LIMIT = int(os.environ.get("IMMOKA_GLMC_DETAIL_LIMIT", "250"))128AGENCY = "Les Immeubles GLMC"129130_CARD_SPLIT = re.compile(r'<a class="x-col[^"]*"\s+href="')131_HREF_RE = re.compile(r'\s*(https://www\.glmc\.ca/proprietes/([a-z0-9-]+?)-(\d{6,9})/)"', re.I)132_IMG_RE = re.compile(r'<img[^>]+src="(https://www\.glmc\.ca/wp-content/uploads/[^"]+\.(?:jpg|jpeg|png|webp))"', re.I)133_TITLE_RE = re.compile(r'x-text-content-text-primary">([^<]+)</p>', re.I)134_PRICE_RE = re.compile(r'([\d][\d\s ]{2,}\$)', re.I)135136# --- page détail ---137_GALLERY_RE = re.compile(138 r'https://www\.glmc\.ca/wp-content/uploads/sites/\d+/\d{4}/\d{2}/'139 r'[0-9a-f]{32}\.(?:jpg|jpeg|png|webp)', re.I)140_DESC_RE = re.compile(r'<ul class="remarques-list">(.*?)</ul>', re.S | re.I)141_LI_RE = re.compile(r'<li[^>]*>(.*?)</li>', re.S | re.I)142_CELL_RE = re.compile(r'class="x-cell[^>]*>(.*?)</div>\s*</div>', re.S)143_STAT_ROOMS_RE = re.compile(r'x-text-content-text-primary">\s*(\d+)\s*pi[èe]ces?', re.I)144_STAT_BEDS_RE = re.compile(r'x-text-content-text-primary">\s*(\d+)\s*chambre', re.I)145_STAT_BATHS_RE = re.compile(r'x-text-content-text-primary">\s*(\d+)\s*salle\(s\) de bain', re.I)146_STAT_POWDER_RE = re.compile(r"x-text-content-text-primary\">\s*(\d+)\s*salle d['’]eau", re.I)147_BROKER_RE = re.compile(r'mw-courtier-name">\s*<h3>([^<]+)</h3>', re.I)148_BROKER_TEL_RE = re.compile(r'mw-courtier-phone">\s*<a href="tel:(\d{7,11})"', re.I)149_INCL_RE = re.compile(r'>Inclusions</p></div>\s*<div class="x-text x-content[^>]*>([^<]{2,400})<', re.I)150_EXCL_RE = re.compile(r'>Exclusions</p></div>\s*<div class="x-text x-content[^>]*>([^<]{2,400})<', re.I)151_AREA_VAL_RE = re.compile(r'([\d\s .,]+?)\s*(MC|M2|M²|PC|PI2|PI²)\s*$', re.I)152153_SQFT_PER_SQM = 10.7639154155156class GlmcConnector(BaseConnector):157 source_id = "glmc_ag_qc"158 request_delay = 0.4159 max_pages = 40 # garde-fou (60/page)160161 def fetch(self) -> list[PropertyListing]:162 by_id: dict[str, PropertyListing] = {}163 dry = 0164 for page in range(1, self.max_pages + 1):165 url = f"{LISTING}?pg={page}"166 try:167 # SiteGround sert un challenge sgcaptcha en HTTP 202 (sans168 # exception) : get_resilient escalade (Oxylabs → Scrapfly ASP169 # → Bright Data)170 html = self.get_resilient(url).text171 except Exception:172 break173 # exclure la section « Vendus » (fiches vendues, après la pagination)174 html = html.split(">Vendus<")[0]175 before = len(by_id)176 for blk in _CARD_SPLIT.split(html)[1:]:177 blk = blk[:2500]178 lst = self._card(blk)179 if lst:180 by_id.setdefault(lst.external_id, lst)181 dry = dry + 1 if len(by_id) == before else 0182 if dry >= 2:183 break184 listings = list(by_id.values())185 du.enrich(self, listings, DETAIL_LIMIT, _parse_detail, key="v2",186 fetch_html=lambda u: self.get_resilient(u).text)187 return listings188189 def _card(self, blk: str) -> PropertyListing | None:190 hm = _HREF_RE.match(blk) or _HREF_RE.search(blk[:400])191 if not hm:192 return None193 url, _slug, mls = hm.group(1), hm.group(2), hm.group(3)194195 title = ""196 tm = _TITLE_RE.search(blk)197 if tm:198 title = _html.unescape(tm.group(1)).strip()199 # dernière virgule = ville (« 37, Rue Lionel-Chalifour, Rivière-du-Loup »)200 city = ""201 if title.count(",") >= 1:202 city = title.rsplit(",", 1)[1].strip()203204 im = _IMG_RE.search(blk)205 pm = _PRICE_RE.search(blk)206 price_label = _html.unescape(pm.group(1)).replace(" ", " ").strip() if pm else ""207208 return PropertyListing(209 source=self.source_id,210 external_id=mls,211 url=url,212 title=title or "Propriété à vendre",213 address=title,214 city=city,215 price=parse_price(price_label),216 price_label=price_label,217 mls=mls,218 images=[im.group(1)] if im else [],219 agency=AGENCY,220 broker_name=AGENCY,221 )222223224def _txt(fragment: str) -> str:225 """HTML -> texte plat propre (une ligne)."""226 t = _html.unescape(re.sub(r"<[^>]+>", " ", fragment))227 return re.sub(r"\s+", " ", t.replace("\xa0", " ")).strip()228229230def _to_sqft(val: str) -> float | None:231 """« 1729.60 MC » / « 2 400 PC » -> pieds carrés."""232 m = _AREA_VAL_RE.search(val.strip())233 if not m:234 return None235 try:236 n = float(re.sub(r"[^\d.]", "", m.group(1)))237 except ValueError:238 return None239 if m.group(2).upper() in ("MC", "M2", "M²"):240 n *= _SQFT_PER_SQM241 return round(n, 1) or None242243244def _parse_detail(html: str) -> dict:245 """Fiche détail GLMC (thème X) : stats à icônes, remarques, grilles x-cell,246 inclusions/exclusions, courtier(s), galerie pleine résolution."""247 out: dict = {}248249 # description = remarques Centris (<ul class="remarques-list">)250 dm = _DESC_RE.search(html)251 if dm:252 paras = [_txt(li) for li in _LI_RE.findall(dm.group(1))]253 desc = "\n\n".join(p for p in paras if p)254 if desc:255 out["description"] = desc256257 # stats à icônes (pièces / chambres / sdb / salles d'eau)258 details: dict = {}259 sm = _STAT_ROOMS_RE.search(html)260 if sm:261 details["Nombre de pièces"] = sm.group(1)262 for rx, field in ((_STAT_BEDS_RE, "bedrooms"),263 (_STAT_BATHS_RE, "bathrooms"),264 (_STAT_POWDER_RE, "powder_rooms")):265 m = rx.search(html)266 if m and int(m.group(1)) > 0:267 out[field] = int(m.group(1))268269 # grilles x-cell : cellules alternées libellé / valeur (avant les courtiers)270 seg = html.split("Courtier(s)")[0]271 cells = [_txt(c) for c in _CELL_RE.findall(seg)]272 for i in range(0, len(cells) - 1, 2):273 lab, val = cells[i], cells[i + 1]274 if not lab or not val or len(lab) > 45 or len(val) > 120 or lab == val:275 continue276 if lab in ("Terrain", "Bâtiment"): # sections Dimensions vs Superficie277 if re.search(r"\d\s*[xX]\s*\d", val):278 lab = f"Dimensions du {lab.lower()}"279 else:280 lab = f"Superficie du {lab.lower()}"281 elif lab == "Habitable":282 lab = "Superficie habitable"283 details[lab] = val284 if details.get("Superficie du terrain"):285 sq = _to_sqft(details["Superficie du terrain"])286 if sq:287 out["lot_sqft"] = sq288 if details.get("Superficie habitable"):289 sq = _to_sqft(details["Superficie habitable"])290 if sq:291 out["area_sqft"] = sq292 my = re.search(r"\b(1[6-9]\d{2}|20\d{2})\b", details.get("Année de construction", ""))293 if my:294 out["year_built"] = int(my.group(1))295296 # inclusions / exclusions (x-text hors grille)297 for rx, lab in ((_INCL_RE, "Inclusions"), (_EXCL_RE, "Exclusions")):298 m = rx.search(seg)299 if m:300 v = _txt(m.group(1))301 if v:302 details[lab] = v303 if details:304 out["details"] = details305306 # courtier inscripteur (première carte .mw-courtier-card)307 bm = _BROKER_RE.search(html)308 if bm:309 out["broker_name"] = _txt(bm.group(1))310 tm = _BROKER_TEL_RE.search(html)311 if tm:312 t = tm.group(1)313 if len(t) == 10:314 t = f"{t[:3]} {t[3:6]}-{t[6:]}"315 out["broker_phone"] = t316317 # prix « 349 900 $ »318 mp = re.search(r'([\d][\d\s ]{2,}\$)', html)319 if mp:320 p = parse_price(mp.group(1))321 if p:322 out["price"] = p323 out["price_label"] = mp.group(1).replace(" ", " ").strip()324325 co = du.gmaps_coords(html)326 if co:327 out["lat"], out["lng"] = co328329 # galerie : photos Centris re-hébergées (nom de fichier = 32 hex) —330 # pleine résolution, ordre d'origine ; exclut logos/portraits (noms lisibles)331 seen, uniq = set(), []332 for u in _GALLERY_RE.findall(html):333 if u not in seen:334 seen.add(u)335 uniq.append(u)336 if uniq:337 out["images"] = uniq338 return out339