Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/immeuble_contact.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1613# Last Modified : 2026-08-1914#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/immeuble_contact.py : Les Immeubles Contact (Alma / Lac-Saint-Jean-Est91# + Chibougamau-Chapais). Agence indépendante, site PHP maison (Solution Globale92# Informatique). La liste est rendue SERVEUR sur immeubles_centris.php?page=…93# (résidentiel + revenu), encodage ISO-8859-1. Chaque carte porte déjà tout :94# n° MLS (Centris), type, adresse, ville, prix (data-cost) et photo Centris.95#96# Page détail immeubles_centris_fiche.php?no_mls={mls} (ISO-8859-1 aussi) :97# galerie complète mesimages/photos_centris/_{mls}_{n}.jpg (spans .item_slide,98# dans l'ordre Centris), prix demandé, région + adresse complète (code postal),99# courtiers (.texte_rouge + « Cell.: »), description (#description),100# évaluation municipale, taxes, dimensions bâtiment/terrain (superficies en101# m² étiquetées « (Mètres) »), compte de pièces (Total/Chambre/S. de bain/102# S. d'eau), caractéristiques principales (#caracteristique_principales),103# inclus/exclus. Pas de GPS sur la fiche.104#105# source_id « contact_ag_qc » : l'infixe _ag_ active la dédup Centris (db.refresh_dedup,106# sources %_ag_%) — si le n° Centris est déjà porté par une bannière couverte107# (RE/MAX, Via Capitale…), la fiche est masquée ; les inscriptions propres de108# l'agence restent visibles. Aucun double-comptage.109# -----------------------------------------------------------------------------110from __future__ import annotations111112import html as _html113import os114import re115116from .base import BaseConnector117from . import _detailutil as du118from ..normalize import parse_price, parse_area_sqft, parse_lot_sqft119from ..schema import PropertyListing120121SITE = "https://www.lesimmeublescontact.com"122PAGES = ["residentiel", "revenu", "commercial"]123AGENCY = "Les Immeubles Contact"124DETAIL_LIMIT = int(os.environ.get("IMMOKA_CONTACT_DETAIL_LIMIT",125 os.environ.get("IMMOKA_DETAIL_LIMIT", "100")))126127# une carte = <article class="immeuble_row" data-cost="NNN"> … </article>128_ROW_RE = re.compile(r'<article class="immeuble_row"\s+data-cost="(\d+)"(.*?)</article>', re.S | re.I)129_TYPE_RE = re.compile(r'class="type"[^>]*>.*?<span>([^<]+)</span>', re.S | re.I)130_ADDR_RE = re.compile(r'class="address">(.*?)</p>', re.S | re.I)131_MLS_RE = re.compile(r'no_mls=(\d{6,9})', re.I)132_PRICE_RE = re.compile(r'class="price"><p>([^<]+)</p>', re.S | re.I)133134# --- page détail -------------------------------------------------------------135_DET_IMG_RE = re.compile(r'href="(mesimages/photos_centris/_\d+_(\d+)\.jpg)"', re.I)136_BROKER_RE = re.compile(r'class="texte_rouge">([^<]+)</span>', re.I)137_CELL_RE = re.compile(r'Cell\.?\s*:?\s*([\d][\d.\- ]{8,14}\d)', re.I)138# « Prix vendu / loué : S/O<br /><br /> RÉGION<br />ADRESSE, VILLE CODE </td> »139_REGION_ADDR_RE = re.compile(140 r'Prix vendu / loué\s*:</span>[^<]*<br\s*/?>\s*<br\s*/?>\s*'141 r'([^<>]{3,60}?)\s*<br\s*/?>\s*([^<>]{5,120}?)\s*</td>', re.S)142143144def _div(html: str, div_id: str) -> str:145 m = re.search(r'<div id="%s">(.*?)</div>' % re.escape(div_id), html, re.S | re.I)146 return m.group(1) if m else ""147148149def _text(fragment: str) -> str:150 return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()151152153def _sqm(val: str):154 """« 342 (Mètres) » -> pi² (les colonnes Superficie de la fiche sont en m²)."""155 v = val.replace("(Mètres)", "m²").replace("(Pieds)", "pi²").strip()156 return parse_area_sqft(v)157158159def parse_contact_detail(html: str) -> dict:160 """Fiche lesimmeublescontact.com : galerie complète Centris (ordre d'origine),161 description, évaluation/taxes, superficies, pièces, caractéristiques,162 inclus/exclus, courtier(s) + cellulaire. Pas de GPS sur ces pages."""163 out: dict = {}164 # galerie : href des .item_slide, une par photo, déjà dans l'ordre Centris165 imgs, seen = [], set()166 for m in _DET_IMG_RE.finditer(html):167 u = f"{SITE}/{m.group(1)}"168 if u not in seen:169 seen.add(u)170 imgs.append(u)171 if imgs:172 out["images"] = imgs173174 details: dict = {}175 unesc = _html.unescape(html)176 # prix demandé + adresse complète (région | adresse, ville + code postal)177 mp = re.search(r'Prix demandé\s*:</span>\s*([^<]+)<', unesc)178 if mp:179 label = mp.group(1).strip()180 if parse_price(label):181 out["price_label"] = label182 out["price"] = parse_price(label)183 ma = _REGION_ADDR_RE.search(unesc)184 if ma:185 details["Région"] = _text(ma.group(1)) # « Saguenay/Lac-Saint-Jean »186 full = _text(ma.group(2)) # « 216 Rue de la Pointe, Dolbeau-Mistassini G8L5M2 »187 out["address"] = full.split(",")[0].strip()188189 # description190 desc = _text(re.sub(r'<span class="moyen_titre">Description</span>', ' ',191 _div(html, "description")))192 if len(desc) > 20:193 out["description"] = desc[:4000]194195 # courtiers (souvent 2) + cellulaire du premier196 names = [_html.unescape(n).strip() for n in _BROKER_RE.findall(html)]197 if names:198 out["broker_name"] = " et ".join(dict.fromkeys(names[:2]))199 mc = _CELL_RE.search(html)200 if mc:201 out["broker_phone"] = mc.group(1).replace(".", "-").replace(" ", "-")202203 # évaluation municipale (année, bâtiment, terrain, total)204 ev = _html.unescape(_div(html, "evaluation"))205 my = re.search(r'Année</span>\s*:\s*(\d{4})', ev)206 year = f" ({my.group(1)})" if my else ""207 for lab, key in (("Bâtiment", "Évaluation municipale (bâtiment)"),208 ("Terrain", "Évaluation municipale (terrain)"),209 ("Total", "Évaluation municipale")):210 mv = re.search(lab + r'</span>\s*:\s*([\d\s ]+\$)', ev)211 if mv:212 details[key] = re.sub(r"\s+", " ", mv.group(1)).strip() + year213214 # taxes (municipales / scolaires / total, avec année)215 tx = _html.unescape(_div(html, "taxes"))216 for lab, key in (("Municipales", "Taxes municipales"),217 ("Scolaires", "Taxes scolaires")):218 mv = re.search(lab + r'\s*:</span></td>\s*<td[^>]*>([\d\s ]+\$)</td>\s*'219 r'<td[^>]*>(\d{4})?', tx)220 if mv:221 details[key] = (re.sub(r"\s+", " ", mv.group(1)).strip()222 + (f" ({mv.group(2)})" if mv.group(2) else ""))223224 # dimensions : lignes Bâtiment / Terrain — Superficie(s) en m² « (Mètres) »225 dims = _html.unescape(_div(html, "dimensions"))226 _row = (r'</span></td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*'227 r'<td>([^<]*)</td>\s*<td>([^<]*)</td>')228 mb = re.search(r'Bâtiment' + _row + r'\s*<td>([^<]*)</td>', dims)229 if mb:230 w, d = mb.group(2).strip(), mb.group(3).strip()231 if w and d:232 details["Dimensions du bâtiment"] = f"{w} x {d}"233 hab = _sqm(mb.group(5))234 if hab and hab > 200:235 out["area_sqft"] = hab236 mt = re.search(r'Terrain' + _row, dims)237 if mt:238 lot = _sqm(mt.group(4))239 if lot:240 out["lot_sqft"] = lot241242 # pièces : Total | Chambre | S. de bain | S. d'eau243 mr = re.search(r"S\.\s*d'eau.*?<tr>\s*<td[^>]*>(\d+)</td>\s*<td[^>]*>(\d+)</td>"244 r"\s*<td[^>]*>(\d+)</td>\s*<td[^>]*>(\d+)</td>", unesc, re.S)245 if mr:246 details["Nombre de pièces"] = mr.group(1)247 out["bedrooms"] = int(mr.group(2)) or None248 out["bathrooms"] = int(mr.group(3)) or None249 out["powder_rooms"] = int(mr.group(4)) or None250251 # caractéristiques principales : « Libellé : | Valeur » (2 colonnes) —252 # le div contient un div imbriqué (tableautop), on tranche jusqu'à #inclus253 i = unesc.find('id="caracteristique_principales"')254 j = unesc.find('id="inclus"', max(i, 0))255 car = unesc[i:j] if 0 <= i < j else (unesc[i:] if i >= 0 else "")256 for lab, val in re.findall(r'sous_titre">([^<:]{2,45}?)\s*:</span></td>\s*'257 r'<td[^>]*>([^<]+)</td>', car):258 val = re.sub(r"\s+", " ", val).strip()259 if val and val.lower() != "s/o":260 details[lab.strip()] = val[:200]261262 # inclus -> features ; exclus -> details263 inc = _text(re.sub(r'<span class="moyen_titre">Inclus</span>', ' ',264 _div(html, "inclus")))265 feats = [s.strip() for s in re.split(r"[,;]| et ", inc) if 2 <= len(s.strip()) <= 90]266 if feats:267 out["features"] = feats[:20]268 exc = _text(re.sub(r'<span class="moyen_titre">Exclus</span>', ' ',269 _div(html, "exclus")))270 if exc:271 details["Exclusions"] = exc[:300]272273 if details:274 out["details"] = details275 return out276277278class ImmeubleContactConnector(BaseConnector):279 source_id = "contact_ag_qc"280 request_delay = 0.4281282 def fetch(self) -> list[PropertyListing]:283 by_id: dict[str, PropertyListing] = {}284 for page in PAGES:285 url = f"{SITE}/immeubles_centris.php?page={page}"286 try:287 resp = self.get(url)288 resp.encoding = "iso-8859-1"289 html = resp.text290 except Exception:291 continue292 for cost, blk in _ROW_RE.findall(html):293 lst = self._card(cost, blk, page)294 if lst:295 by_id.setdefault(lst.external_id, lst)296 listings = list(by_id.values())297 # fiche détail : galerie complète, description, caractéristiques,298 # courtier — plafonné/cycle, cache BD (voir _detailutil)299 du.enrich(self, listings, DETAIL_LIMIT, parse_contact_detail,300 key="v1", fetch_html=self._fetch_html)301 return listings302303 def _fetch_html(self, url: str) -> str:304 """GET avec décodage ISO-8859-1 (le site n'envoie pas de charset HTTP)."""305 resp = self.get(url)306 resp.encoding = "iso-8859-1"307 return resp.text308309 def _card(self, cost: str, blk: str, page: str) -> PropertyListing | None:310 mm = _MLS_RE.search(blk)311 if not mm:312 return None313 mls = mm.group(1)314315 addr_raw = _ADDR_RE.search(blk)316 addr_txt = ""317 city = ""318 if addr_raw:319 parts = re.split(r'<br\s*/?>', addr_raw.group(1))320 addr_txt = _html.unescape(re.sub(r'<[^>]+>', ' ', parts[0])).strip().rstrip(",").strip()321 if len(parts) > 1:322 city = _html.unescape(re.sub(r'<[^>]+>', ' ', parts[1])).strip()323324 tm = _TYPE_RE.search(blk)325 prop_type = _html.unescape(tm.group(1)).strip() if tm else ""326 pm = _PRICE_RE.search(blk)327 price_label = _html.unescape(pm.group(1)).strip() if pm else ""328 price = parse_price(price_label) or (float(cost) if cost and cost != "0" else None)329330 return PropertyListing(331 source=self.source_id,332 external_id=mls,333 url=f"{SITE}/immeubles_centris_fiche.php?no_mls={mls}",334 title=addr_txt or f"{prop_type} à vendre",335 address=addr_txt,336 city=city,337 property_type=prop_type,338 price=price,339 price_label=price_label,340 mls=mls,341 images=[f"{SITE}/mesimages/photos_centris/_{mls}_1.jpg"],342 agency=AGENCY,343 broker_name=AGENCY,344 )345