Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/imcha.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/imcha.py : Les Immeubles Charlevoix (imcha.com) — Baie-Saint-Paul,91# La Malbaie, Les Éboulements, Petite-Rivière-Saint-François + Vieux-Québec /92# Côte-de-Beaupré. Seule agence indépendante crédible de Charlevoix. Site93# custom rendu SERVEUR, liste paginée /vente-de-proprietes/page-N. Chaque carte94# (li.estate-single) porte : code interne, type, ville, prix, chambres et95# photo. Le n° Centris est encodé dans le nom de fichier photo96# (/uploads/photos/max/{Centris}-…) → clé de déduplication.97#98# Page détail : description dans <h3 class="title--small">Description</h3>99# + <p>, galerie fancybox /uploads/photos/max/… (pleine résolution, ordre100# d'origine — préfixe = n° Centris), specs à icônes (Chambres / Salles de101# bain / Salle d'eau, ordre libellé/nombre variable), sections102# .estate__info (Type + année, Évaluation municipale, Bâtiment, Terrain103# [façade/profondeur/superficie en mètres], Inclusions, Exclusions en104# <dt>/<dd>). AUCUNE coordonnée GPS ni adresse civique exposée (pas de105# carte sur la fiche) — impossible à géocoder honnêtement. ⚠️ Les réponses106# HTTP n'annoncent pas de charset alors que le HTML est en UTF-8 → forcer107# resp.encoding partout. Enrichissement plafonné + cache (du.enrich).108#109# source_id « imcha_ag_qc » : infixe _ag_ = dédup Centris (db.refresh_dedup).110# -----------------------------------------------------------------------------111from __future__ import annotations112113import html as _html114import os115import re116117from .base import BaseConnector118from . import _detailutil as du119from ..normalize import parse_price120from ..schema import PropertyListing121122SITE = "https://www.imcha.com"123DETAIL_LIMIT = int(os.environ.get("IMMOKA_IMCHA_DETAIL_LIMIT", "150"))124AGENCY = "Les Immeubles Charlevoix"125126_ITEM_SPLIT = re.compile(r'<li class="estate-single"')127_HREF_RE = re.compile(r'href="(/(?:maisons-a-vendre|terrains-et-terres-a-vendre|[a-z-]+-a-vendre)/[a-z0-9_-]+)"', re.I)128_CODE_RE = re.compile(r'data-code="([A-Z0-9]+)"', re.I)129_CENTRIS_RE = re.compile(r'/uploads/photos/[a-z]+/(\d{6,9})-', re.I)130_IMG_RE = re.compile(r'src="(/resize\?src=[^"]+|/uploads/[^"]+\.(?:jpg|jpeg|png|webp))"', re.I)131_TYPE_RE = re.compile(r'estate-single__status">([^<]+)<', re.I)132_CITY_RE = re.compile(r'estate-single__city">([^<]+)<', re.I)133_PRICE_RE = re.compile(r'estate-single__price">([^<]+)<', re.I)134_BEDS_RE = re.compile(r'estate-spec__count">(\d+)<', re.I)135136# --- page détail ---137_DESC_RE = re.compile(r'title--small">Description</h3>\s*(.*?)\s*<div class="estate__info', re.S | re.I)138_P_RE = re.compile(r'<p[^>]*>(.*?)</p>', re.S | re.I)139_FANCY_RE = re.compile(r'class="fancybox"[^>]*href="(/uploads/photos/max/[^"]+)"', re.I)140_SPEC_RE = re.compile(r'<div class="estate__spec">\s*(.*?)</div>\s*</div>', re.S | re.I)141_SPEC_LABEL_RE = re.compile(r'estate-spec__label">\s*([^<]+)', re.I)142_SPEC_COUNT_RE = re.compile(r'estate-spec__count">\s*(\d+)', re.I)143_INFO_RE = re.compile(r'<div class="estate__info">\s*<h3 class="estate-info__title">'144 r'([^<]+)</h3>\s*<dl class="estate-info__list">(.*?)</dl>', re.S | re.I)145_DTDD_RE = re.compile(r'<dt>([^<]*)</dt>\s*(?:<dd>([^<]*)</dd>)?', re.S | re.I)146_TEL_RE = re.compile(r'Tel\.?\s*:\s*((?:1[\s-])?\d{3}[\s-]\d{3}-\d{4})')147_AREA_M2_RE = re.compile(r'([\d\s .,]+?)\s*(m|mètre|pied)', re.I)148149_SQFT_PER_SQM = 10.7639150_SPEC_FIELDS = {"chambres": "bedrooms", "chambre": "bedrooms",151 "salles de bain": "bathrooms", "salle de bain": "bathrooms",152 "salle d'eau": "powder_rooms", "salles d'eau": "powder_rooms"}153154155class ImchaConnector(BaseConnector):156 source_id = "imcha_ag_qc"157 request_delay = 0.4158 max_pages = 30159160 def fetch(self) -> list[PropertyListing]:161 by_id: dict[str, PropertyListing] = {}162 dry = 0163 for page in range(1, self.max_pages + 1):164 url = f"{SITE}/vente-de-proprietes/page-{page}"165 try:166 resp = self.get(url)167 resp.encoding = "utf-8"168 html = resp.text169 except Exception:170 break171 before = len(by_id)172 for blk in _ITEM_SPLIT.split(html)[1:]:173 blk = blk[:4000]174 lst = self._card(blk)175 if lst:176 by_id.setdefault(lst.external_id, lst)177 dry = dry + 1 if len(by_id) == before else 0178 if dry >= 2:179 break180 listings = list(by_id.values())181 du.enrich(self, listings, DETAIL_LIMIT, _parse_detail, key="v1",182 fetch_html=self._fetch_utf8)183 return listings184185 def _fetch_utf8(self, url: str) -> str:186 # le serveur n'annonce pas de charset (requests retomberait sur187 # ISO-8859-1) alors que les fiches sont en UTF-8188 resp = self.get(url)189 resp.encoding = "utf-8"190 return resp.text191192 def _card(self, blk: str) -> PropertyListing | None:193 hm = _HREF_RE.search(blk)194 if not hm:195 return None196 cm = _CENTRIS_RE.search(blk)197 code = _CODE_RE.search(blk)198 # n° Centris (photo) = clé de dédup ; sinon code interne (pas de dédup)199 mls = cm.group(1) if cm else ""200 external_id = mls or (code.group(1) if code else None)201 if not external_id:202 return None203204 tm = _TYPE_RE.search(blk)205 cy = _CITY_RE.search(blk)206 pm = _PRICE_RE.search(blk)207 bm = _BEDS_RE.search(blk)208 im = _IMG_RE.search(blk)209 img = im.group(1) if im else ""210 if img.startswith("/"):211 img = SITE + img212 price_label = _html.unescape(pm.group(1)).strip() if pm else ""213 city = _html.unescape(cy.group(1)).strip() if cy else ""214215 return PropertyListing(216 source=self.source_id,217 external_id=external_id,218 url=SITE + hm.group(1),219 title=f"{_html.unescape(tm.group(1)).strip() if tm else 'Propriété'} à vendre — {city}".strip(" —"),220 city=city,221 property_type=_html.unescape(tm.group(1)).strip() if tm else "",222 price=parse_price(price_label),223 price_label=price_label,224 bedrooms=int(bm.group(1)) if bm else None,225 mls=mls,226 images=[img] if img else [],227 agency=AGENCY,228 broker_name=AGENCY,229 )230231232def _txt(fragment: str) -> str:233 t = _html.unescape(re.sub(r"<br\s*/?>", "\n", fragment, flags=re.I))234 t = re.sub(r"<[^>]+>", " ", t).replace("\xa0", " ").replace("×", "x")235 t = re.sub(r"[ \t]+", " ", t)236 return re.sub(r"\n{3,}", "\n\n", t).strip()237238239def _parse_detail(html: str) -> dict:240 """Fiche détail imcha : description, galerie max, specs, sections dt/dd."""241 out: dict = {}242243 dm = _DESC_RE.search(html)244 if dm:245 paras = [_txt(p) for p in _P_RE.findall(dm.group(1))]246 desc = "\n\n".join(p for p in paras if p)247 if desc:248 out["description"] = desc249250 # galerie fancybox pleine résolution ; le préfixe du nom de fichier est le251 # n° Centris de LA fiche → on ne garde que le lot majoritaire (sécurité)252 anchors = _FANCY_RE.findall(html)253 if anchors:254 prefix = anchors[0].rsplit("/", 1)[-1].split("-", 1)[0]255 seen, uniq = set(), []256 for a in anchors:257 if not a.rsplit("/", 1)[-1].startswith(prefix + "-"):258 continue259 u = SITE + a260 if u not in seen:261 seen.add(u)262 uniq.append(u)263 if uniq:264 out["images"] = uniq265266 # specs à icônes (ordre libellé/nombre variable selon la spec)267 for spec in _SPEC_RE.findall(html):268 lm, cm = _SPEC_LABEL_RE.search(spec), _SPEC_COUNT_RE.search(spec)269 if not lm or not cm:270 continue271 field = _SPEC_FIELDS.get(_txt(lm.group(1)).lower())272 m = re.search(r"\d+", cm.group(1))273 if field and m and int(m.group()) > 0:274 out.setdefault(field, int(m.group()))275276 # sections .estate__info (<dt>/<dd>)277 details: dict = {}278 for title, body in _INFO_RE.findall(html):279 title = _txt(title)280 pairs = [(_txt(dt), _txt(dd or "")) for dt, dd in _DTDD_RE.findall(body)]281 if title.lower().startswith(("inclusions", "exclusions")):282 items = [dt for dt, _ in pairs if dt]283 if items:284 details[title.split(" ")[0]] = ", ".join(items)285 continue286 for dt, dd in pairs:287 dt = dt.rstrip(" :")288 if not dt or not dd or len(dd) > 120:289 continue290 if dt == "Année de construction":291 m = re.search(r"\b(1[6-9]\d{2}|20\d{2})\b", dd)292 if m: # « 0 » = inconnue chez imcha293 out["year_built"] = int(m.group(1))294 details[dt] = dd295 elif dt == "Type":296 details["Type de propriété"] = dd297 elif title.startswith("Évaluation municipale"):298 details[f"Évaluation municipale ({dt.lower()})"] = dd299 elif title in ("Terrain", "Bâtiment"):300 if dt == "Superficie":301 details[f"Superficie du {title.lower()}"] = dd302 if title == "Terrain":303 sq = _area_to_sqft(dd)304 if sq:305 out["lot_sqft"] = sq306 else:307 details[f"{title} — {dt.lower()}"] = dd308 else:309 details[dt] = dd310 if details:311 out["details"] = details312313 # téléphone de l'agence (meta description « Tel. : 1 418-435-6221 »)314 tm = _TEL_RE.search(html)315 if tm:316 out["broker_phone"] = tm.group(1).strip()317 return out318319320def _area_to_sqft(val: str) -> float | None:321 """« 7657.10 Mètres carrés » / « 2 400 pieds carrés » -> pi²."""322 m = _AREA_M2_RE.match(val.strip())323 if not m:324 return None325 try:326 n = float(re.sub(r"[^\d.]", "", m.group(1)))327 except ValueError:328 return None329 if m.group(2).lower().startswith(("m", "mètre")):330 n *= _SQFT_PER_SQM331 return round(n, 1) or None332