Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/charisma.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/charisma.py : Les Immeubles Charisma (charisma.ca) — Laval,91# Montréal, Montérégie. 3e bannière indépendante du Québec (200+ courtiers).92# Site WordPress (plugin « MW Properties » / realestate.marketingwebsites.ca),93# liste rendue SERVEUR sur /fr/proprietes/, paginée par ?pages=N (~10/page,94# ~84 pages). Chaque carte (box-house) porte : n° Centris (URL + image), prix,95# ville, chambres/sdb et photo (property-images/{Centris}/).96#97# ENRICHISSEMENT DÉTAIL (v2) : la page /fr/properties/{adresse}/{centris}/ est98# rendue serveur elle aussi et porte TOUT : galerie fancybox complète (toutes99# les photos property-images pleine taille, ordre d'origine), blocs100# Description / Inclusions / Exclusions / Plus d'information, box-icons101# (sdb, salles d'eau, année, chambres, superficie « 58.9 MC »), tableaux102# th.prop-table/td (Bâtiment + Caractéristiques), Détails de pièce, courtier103# inscripteur (seller-info : nom + tel), coordonnées GPS (google.maps.LatLng).104# Cache BD via _detailutil.enrich (seules les fiches nouvelles sont relues).105#106# ⚠ DÉDUP : Charisma a fusionné avec L'Expert Immobilier P.M. (déjà couvert)107# en 2021 → beaucoup de co-inscriptions. source_id « charisma_ag_qc » : l'infixe108# _ag_ (db.refresh_dedup) masque les fiches dont le n° Centris est déjà porté109# par une source couverte ; les inscriptions uniques restent visibles.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import html as _html114import os115import re116import urllib.parse117118from .base import BaseConnector119from . import _detailutil as du120from ..normalize import parse_price121from ..schema import PropertyListing122123SITE = "https://charisma.ca"124LISTING = SITE + "/fr/proprietes/"125AGENCY = "Les Immeubles Charisma"126IMG_ROOT = "https://realestate.marketingwebsites.ca/property-images"127# fiches détail (re)lues au plus par cycle — le cache BD (key v2) rend les128# cycles suivants quasi gratuits (~368 fiches publiées → 2 cycles de rattrapage)129DETAIL_LIMIT = int(os.environ.get("IMMOKA_CHARISMA_DETAIL_LIMIT",130 os.environ.get("IMMOKA_DETAIL_LIMIT", "200")))131132_CARD_SPLIT = re.compile(r'<div class="box-house[^"]*">')133_HREF_RE = re.compile(r'href="(https://charisma\.ca/fr/properties/[^"]*?/(\d{6,9}))"', re.I)134_IMG_RE = re.compile(r'(https://realestate\.marketingwebsites\.ca/property-images/\d+/[^"\']+\.(?:jpg|jpeg|png|webp))', re.I)135# prix format nord-américain « $545,000 » (parfois « 545 000 $ »)136_PRICE_RE = re.compile(r'class="price">\s*(\$[\d,]+|[\d\s ]+\$)', re.I)137_BEDS_RE = re.compile(r'<span>(\d+)</span>\s*Chambres', re.I)138_BATHS_RE = re.compile(r'<span>(\d+)</span>\s*Bains', re.I)139# « #1605 - 200 Rue André-Prévost<br/> Montréal (Verdun/Île-des-Soeurs) »140_LOC_RE = re.compile(r'class="location[^"]*"[^>]*>(.*?)</p>', re.S | re.I)141_TYPE_RE = re.compile(r'class="title">\s*<a[^>]*>([^<]+)</a>', re.S | re.I)142143144class CharismaConnector(BaseConnector):145 source_id = "charisma_ag_qc"146 request_delay = 0.4147 max_pages = 120 # garde-fou (~10/page)148149 def fetch(self) -> list[PropertyListing]:150 by_id: dict[str, PropertyListing] = {}151 dry = 0152 for page in range(1, self.max_pages + 1):153 url = LISTING if page == 1 else f"{LISTING}?pages={page}"154 try:155 html = self.get(url).text156 except Exception:157 break158 before = len(by_id)159 for blk in _CARD_SPLIT.split(html)[1:]:160 blk = blk[:2500]161 lst = self._card(blk)162 if lst:163 by_id.setdefault(lst.external_id, lst)164 dry = dry + 1 if len(by_id) == before else 0165 if dry >= 2:166 break167 listings = list(by_id.values())168 # fiche détail (server-rendered) : galerie complète, description +169 # addendum, caractéristiques, pièces, courtier, GPS — cache BD.170 du.enrich(self, listings, DETAIL_LIMIT, _parse_charisma_detail, key="v2")171 return listings172173 def _card(self, blk: str) -> PropertyListing | None:174 hm = _HREF_RE.search(blk)175 im = _IMG_RE.search(blk)176 mls = hm.group(2) if hm else (re.search(r'property-images/(\d{6,9})/', blk) or [None, None])[1]177 if not mls:178 return None179 url = hm.group(1) if hm else f"{SITE}/fr/properties/{mls}"180181 # localisation : « {adresse}<br/> {ville} » ; adresse aussi dans l'URL182 addr, city = "", ""183 lm = _LOC_RE.search(blk)184 if lm:185 loc = re.split(r'<br\s*/?>', lm.group(1))186 addr = _html.unescape(re.sub(r'<[^>]+>', ' ', loc[0])).strip()187 if len(loc) > 1:188 city = _html.unescape(re.sub(r'<[^>]+>', ' ', loc[1])).strip()189 if not addr:190 am = re.search(r'/fr/properties/([^/]+)/\d{6,9}', url)191 if am:192 addr = _html.unescape(urllib.parse.unquote_plus(am.group(1))).strip()193194 pm = _PRICE_RE.search(blk)195 price_label = pm.group(1).strip() if pm else ""196 price = None197 if price_label:198 price = parse_price(price_label.replace("$", "").replace(",", "")) \199 if price_label.startswith("$") else parse_price(price_label)200 bm = _BEDS_RE.search(blk)201 sm = _BATHS_RE.search(blk)202 tm = _TYPE_RE.search(blk)203204 return PropertyListing(205 source=self.source_id,206 external_id=mls,207 url=url,208 title=addr or "Propriété à vendre",209 address=addr,210 city=city,211 property_type=_html.unescape(tm.group(1)).strip() if tm else "",212 price=price,213 price_label=price_label,214 bedrooms=int(bm.group(1)) if bm else None,215 bathrooms=int(sm.group(1)) if sm else None,216 mls=mls,217 images=[im.group(1)] if im else [f"{IMG_ROOT}/{mls}/{mls}-01.jpg"],218 agency=AGENCY,219 broker_name=AGENCY,220 )221222223# --- fiche détail (MW Properties, server-rendered) ---------------------------224_GAL_RE = re.compile(r'data-fancybox="gallery"\s+href="(https://realestate\.'225 r'marketingwebsites\.ca/property-images/[^"]+)"', re.I)226# box-icons du sommaire : « <div class=text-4…>Libellé:</div><div class=text-1…>Valeur</div> »227_FACT_RE = re.compile(r'text-4 text-color-default">\s*([^<]+?)\s*</div>\s*'228 r'<div class="text-1 text-color-heading">\s*([^<]+?)\s*</div>', re.S)229# sections texte : « <div class="wg-title …">Description</div> <p>…</p> »230_SEC_RE = re.compile(r'wg-title[^"]*">\s*(Description|Inclusions|Exclusions|'231 r'Plus d.information)\s*</div>\s*<p>(.*?)</p>', re.S | re.I)232# tableaux Bâtiment / Caractéristiques : « <tr><th class=prop-table>L</th><td>V</td></tr> »233# (le tableau des pièces a 4 <th> consécutifs → jamais capté par cette forme)234_ROW_RE = re.compile(r'<tr>\s*<th class="prop-table"[^>]*>\s*([^<]+?)\s*</th>\s*'235 r'<td[^>]*>\s*(.*?)\s*</td>\s*</tr>', re.S)236_ROOM_RE = re.compile(r'<td data-title="Room">([^<]*)</td>\s*'237 r'<td data-title="Dimensions">([^<]*)</td>\s*'238 r'<td data-title="Level">([^<]*)</td>\s*'239 r'<td data-title="Flooring">([^<]*)</td>', re.S)240_BROKER_RE = re.compile(r'class="seller-info"(.*?)</ul>', re.S)241_NAME_RE = re.compile(r'<h6 class="name">([^<]+)</h6>')242_DESIG_RE = re.compile(r'class="designation[^"]*">([^<]+)<')243_TEL_RE = re.compile(r'href="tel:[^"]*"[^>]*>([^<]+)<')244_COORD_RE = re.compile(r'LatLng\((-?\d{1,2}\.\d+),\s*(-?\d{2,3}\.\d+)\)')245_TOUR_RE = re.compile(r'https?://(?:my\.matterport\.com/show/[^"\'\s<>]+'246 r'|(?:www\.)?youtube\.com/(?:embed/|watch\?v=)[^"\'\s<>]+'247 r'|youtu\.be/[^"\'\s<>]+'248 r'|(?:player\.)?vimeo\.com/(?:video/)?\d+[^"\'\s<>]*)', re.I)249_ZEROS = {"", "0", "0x0", "0 x 0", "n/a", "-"}250251252def _text(fragment: str) -> str:253 """Fragment HTML -> texte propre (les <br> deviennent des sauts de ligne)."""254 t = re.sub(r'<br\s*/?>', '\n', fragment)255 t = re.sub(r'<[^>]+>', ' ', t)256 t = _html.unescape(t)257 t = re.sub(r'[ \t]+', ' ', t)258 return "\n".join(line.strip() for line in t.splitlines()).strip()259260261def _num(raw: str) -> float | None:262 v = raw.replace(" ", "").replace(" ", "").replace(" ", "")263 if v.count(",") == 1 and "." not in v:264 v = v.replace(",", ".") # décimale française « 58,9 »265 else:266 v = v.replace(",", "") # milliers « 1,200 »267 try:268 return float(v) or None269 except ValueError:270 return None271272273def _sqft(val: str) -> float | None:274 """« 58.9 MC » / « 1200 PC » -> pi² (unité obligatoire, 0 rejeté)."""275 m = re.search(r'([\d][\d\s ,.]*)\s*(MC|M2|M²|PC|PI2|PI²)\b', val or "", re.I)276 if not m:277 return None278 v = _num(m.group(1))279 if not v:280 return None281 return round(v * 10.7639) if m.group(2).upper() in ("MC", "M2", "M²") else round(v)282283284def _parse_charisma_detail(html: str) -> dict:285 """Fiche MW Properties : galerie, description+addendum, box-icons,286 tableaux th/td, pièces, courtier, GPS, visite virtuelle."""287 out: dict = {}288 details: dict = {}289290 # galerie fancybox pleine taille, ordre du document291 imgs = list(dict.fromkeys(_GAL_RE.findall(html)))292 if len(imgs) > 1:293 out["images"] = imgs[:80]294295 # sommaire (box-icons)296 for label, val in _FACT_RE.findall(html):297 label = _html.unescape(label).strip().rstrip(":").strip()298 val = _html.unescape(val).strip()299 if val.lower() in _ZEROS:300 continue301 if label == "Salles de bain" and val.isdigit():302 out["bathrooms"] = int(val)303 elif label == "Salles d'eau" and val.isdigit():304 out["powder_rooms"] = int(val)305 elif label == "Chambres à coucher" and val.isdigit():306 out["bedrooms"] = int(val)307 elif label == "Année de construction" and re.fullmatch(r"(1[6-9]|20)\d{2}", val):308 out["year_built"] = int(val)309 elif label == "Superficie habitable":310 a = _sqft(val)311 if a:312 out["area_sqft"] = a313 details["Superficie habitable"] = val314 elif label == "Taille du lot":315 t = _sqft(val)316 if t:317 out["lot_sqft"] = t318 details["Superficie du terrain"] = val319320 # Description / Inclusions / Exclusions / Plus d'information (addendum)321 desc, addendum = "", ""322 for name, body in _SEC_RE.findall(html):323 txt = _text(body)324 if not txt:325 continue326 low = name.lower()327 if low.startswith("description"):328 desc = txt329 elif low.startswith("inclusion"):330 details["Inclusions"] = txt[:600]331 elif low.startswith("exclusion"):332 details["Exclusions"] = txt[:600]333 else: # « Plus d'information »334 addendum = txt335 if desc or addendum:336 out["description"] = "\n\n".join(filter(None, (desc, addendum)))[:6000]337338 # tableaux Bâtiment + Caractéristiques (paires th.prop-table / td)339 for label, val in _ROW_RE.findall(html):340 label = _html.unescape(label).strip().rstrip(":").strip()341 val = _text(val)342 if not label or val.lower() in _ZEROS:343 continue344 if label == "La Taille Du Lot":345 label = "Superficie du terrain"346 if label == "Type":347 label = "Type de bâtiment"348 details.setdefault(label, val[:300])349350 # détails de pièce -> features + nombre de pièces351 rooms = _ROOM_RE.findall(html)352 if rooms:353 feats = []354 for name, dim, lvl, floor in rooms:355 name, dim = _html.unescape(name).strip(), _html.unescape(dim).strip()356 lvl, floor = _html.unescape(lvl).strip(), _html.unescape(floor).strip()357 line = name + (f" — {dim}" if dim else "") + (f", {lvl}" if lvl else "")358 if floor:359 line += f" ({floor})"360 feats.append(line)361 out["features"] = feats[:40]362 details.setdefault("Nombre de pièces", str(len(rooms)))363364 # courtier inscripteur (encadré « Informations »)365 mb = _BROKER_RE.search(html)366 if mb:367 seg = mb.group(1)368 mn = _NAME_RE.search(seg)369 if mn:370 out["broker_name"] = _html.unescape(mn.group(1)).strip()371 md = _DESIG_RE.search(seg)372 if md:373 details.setdefault("Titre du courtier", _html.unescape(md.group(1)).strip())374 mt = _TEL_RE.search(seg)375 if mt:376 out["broker_phone"] = _html.unescape(mt.group(1)).strip()377378 # coordonnées GPS (carte Google inline)379 mc = _COORD_RE.search(html)380 if mc:381 lat, lng = float(mc.group(1)), float(mc.group(2))382 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:383 out["lat"], out["lng"] = lat, lng384385 # visite virtuelle / vidéo (modal #video, matterport, youtube, vimeo)386 mt = _TOUR_RE.search(html)387 if mt:388 details.setdefault("Visite virtuelle / vidéo", mt.group(0))389390 if details:391 out["details"] = details392 return out393