Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/m_immobilier.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1214#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/m_immobilier.py : M Immobilier (mimmobilier.com)91# Agence indépendante de prestige (Grand Montréal), inscriptions Centris.92# La page /properties est rendue serveur : chaque carte « cardProperty »93# porte l'URL (avec no Centris), la ville, l'adresse, chambres, salles de94# bains, prix et les photos (/images/centris-slideshow/{id}-N-*.jpg).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import html as _html99import os100import re101102from .base import BaseConnector103from . import _detailutil as du104from ..normalize import parse_price105from ..schema import PropertyListing106107BASE = "https://www.mimmobilier.com"108LISTING_URL = f"{BASE}/properties"109CARD_SPLIT = "cardProperty col-span-12"110HREF_RE = re.compile(r'href="(/properties/[^"]+/(\d+))"')111IMG_RE = re.compile(r'(/images/centris-slideshow/\d+-\d+-\d+\.(?:jpg|jpeg|png|webp))', re.I)112DETAIL_LIMIT = int(os.environ.get("IMMOKA_M_DETAIL_LIMIT", "300"))113114115class MImmobilierConnector(BaseConnector):116 source_id = "m_immobilier"117 request_delay = 0.6118 use_detail_cache = False119120 def fetch(self) -> list[PropertyListing]:121 html = self.get(LISTING_URL).text122 cards = html.split(CARD_SPLIT)[1:]123 out: dict[str, PropertyListing] = {}124 for card in cards:125 card = CARD_SPLIT + card[:6000]126 lst = self._parse_card(card)127 if lst and lst.uid not in out:128 out[lst.uid] = lst129 listings = list(out.values())130 # fiche détail : galerie complète (135 photos) + description + type131 du.enrich(self, listings, DETAIL_LIMIT, parse_m_detail, key="v2")132 return listings133134 def _parse_card(self, card: str) -> PropertyListing | None:135 m = HREF_RE.search(card)136 if not m:137 return None138 url = BASE + m.group(1)139 external_id = m.group(2)140141 images = []142 for im in IMG_RE.findall(card):143 full = BASE + im144 if full not in images:145 images.append(full)146147 # texte du carton, ligne par ligne148 text = _html.unescape(re.sub(r"<[^>]+>", "\n", card))149 lines = [l.strip() for l in text.splitlines() if l.strip()]150151 status_txt = lines[1] if len(lines) > 1 else ""152 # ville et adresse : les 2 lignes après le statut « À vendre »153 city = address = ""154 try:155 k = next(i for i, l in enumerate(lines)156 if l.lower().startswith(("à vendre", "a vendre", "vendu")))157 status_txt = lines[k]158 city = lines[k + 1] if k + 1 < len(lines) else ""159 address = lines[k + 2] if k + 2 < len(lines) else ""160 except StopIteration:161 pass162163 price_label = _after(lines, "prix")164 if price_label and "/ m" in price_label.lower():165 return None # location, pas une vente166 price = parse_price(price_label or "")167 beds = _int(_after(lines, "chambres"))168 baths = _int(_after(lines, "salles de bains"))169170 vendu = "vendu" in status_txt.lower()171 return PropertyListing(172 source=self.source_id,173 external_id=external_id,174 url=url,175 title=f"{address}, {city}".strip(", "),176 address=address,177 city=city,178 property_type="", # non exposé sur le carton179 price=price,180 price_label=price_label or "",181 bedrooms=beds,182 bathrooms=baths,183 mls=external_id,184 status="vendu" if vendu else "a-vendre",185 images=images,186 broker_name="M Immobilier",187 )188189190def parse_m_detail(html: str) -> dict:191 """Galerie Centris complète + description (JSON-LD) + caractéristiques."""192 out: dict = {}193 imgs = []194 seen = set()195 for im in IMG_RE.findall(html):196 full = BASE + im197 if full not in seen:198 seen.add(full)199 imgs.append(full)200 if imgs:201 out["images"] = imgs202 desc = du.ld_description(html)203 if desc:204 out["description"] = desc205 _det = du.centris_details(du.flatten(html))206 if _det:207 out.setdefault("details", {}).update(_det)208 return out209210211def _after(lines: list[str], label: str) -> str:212 lab = label.lower()213 for i, l in enumerate(lines):214 if l.lower() == lab and i + 1 < len(lines):215 return lines[i + 1]216 return ""217218219def _int(s: str):220 if not s:221 return None222 # « 4 + 1 » -> 5 (chambres principales + sous-sol)223 nums = [int(x) for x in re.findall(r"\d+", s)]224 return sum(nums) if nums else None225