SPB Git

Repository Public

m_immobilier.py 11.2 KB 282 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/m_immobilier.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/m_immobilier.py : M Immobilier (mimmobilier.com) — LOCATIONS91#   Agence indépendante de prestige (Grand Montréal), inscriptions Centris.92#   La liste /properties est rendue serveur et paginée ; le formulaire expose93#   un filtre statut « à louer » (radio name="CODE_STATUT" value="AL") qu'on94#   rejoue en query string : /properties?CODE_STATUT=AL&page=N. Chaque carte95#   « cardProperty » porte l'URL (avec no Centris), le badge « à louer », la96#   ville, l'adresse, chambres, salles de bains, superficie (PC) et le loyer97#   « X $ / M ». Adapté du connecteur « à vendre » d'Immo-Ka98#   (agent-courtage/immoka), qui excluait justement ces cartes-là.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import html as _html103import os104import re105106from ..schema import Listing107from .base import BaseConnector108109from . import _detailutil as du110111BASE = "https://www.mimmobilier.com"112LISTING_URL = f"{BASE}/properties?CODE_STATUT=AL"      # AL = à louer (serveur)113CARD_SPLIT = "cardProperty col-span-12"114HREF_RE = re.compile(r'href="(/properties/[^"]+/(\d+))"')115IMG_RE = re.compile(r'(/images/centris-slideshow/\d+-\d+-\d+\.(?:jpg|jpeg|png|webp))', re.I)116# loyer « 1 500.0 $ / M » (M = mois) — le montant précède le $117_RENT_RE = re.compile(r"([\d\s ,]+(?:\.\d+)?)\s*\$\s*/\s*M", re.I)118_H1_RE = re.compile(r"<h1[^>]*>(.*?)</h1>", re.S)119# l'agence loue aussi des locaux commerciaux au mois (bureaux, entrepôts…) sans120# ligne « chambres » : on ne garde ces cartes-là que si l'extrait de description121# contient un marqueur clairement résidentiel (studio, bachelor, logement…)122_RESIDENTIAL_RE = re.compile(123    r"\b(studios?|bachelor|logements?|appartements?|condos?|chambres?|"124    r"r[ée]sidentiel(?:le)?s?|unit[ée]s?|laveuse|maison|complexe)\b", re.I)125MAX_PAGES = int(os.environ.get("LOUKA_MIMMO_MAX_PAGES", "10"))126DETAIL_LIMIT = int(os.environ.get("LOUKA_MIMMO_DETAIL_LIMIT", "100"))127128129class MImmobilierConnector(BaseConnector):130    source_id = "m_immobilier"131    request_delay = 0.6132133    def fetch(self) -> list[Listing]:134        out: dict[str, Listing] = {}135        for page in range(1, MAX_PAGES + 1):136            url = LISTING_URL if page == 1 else f"{LISTING_URL}&page={page}"137            try:138                html = self.get(url).text139            except Exception:140                break141            cards = html.split(CARD_SPLIT)[1:]142            fresh = 0143            for card in cards:144                lst = self._parse_card(CARD_SPLIT + card[:6000])145                if lst and lst.uid not in out:146                    out[lst.uid] = lst147                    fresh += 1148            # dernière page atteinte (vide ou uniquement des doublons)149            if not cards or fresh == 0:150                break151        listings = list(out.values())152        # fiche détail : galerie Centris complète + description + adresse pleine153        du.enrich(self, listings, DETAIL_LIMIT, parse_m_detail, key="v1")154        return listings155156    def _parse_card(self, card: str) -> Listing | None:157        m = HREF_RE.search(card)158        if not m:159            return None160        url = BASE + m.group(1)161        external_id = m.group(2)162163        images = []164        for im in IMG_RE.findall(card):165            full = BASE + im166            if full not in images:167                images.append(full)168169        # texte du carton, ligne par ligne : badge statut, ville, adresse,170        # extrait de description, puis paires libellé/valeur171        text = _html.unescape(re.sub(r"<[^>]+>", "\n", card))172        lines = [l.strip() for l in text.splitlines() if l.strip()]173        try:174            k = next(i for i, l in enumerate(lines)175                     if l.lower().startswith(("à louer", "a louer")))176        except StopIteration:177            return None                     # vente/vendu/loué : pas une location active178        city_raw = lines[k + 1] if k + 1 < len(lines) else ""179        address = lines[k + 2] if k + 2 < len(lines) else ""180        snippet = lines[k + 3] if k + 3 < len(lines) else ""181182        price_label = _after(lines, "prix")183        if "/ m" not in price_label.lower():184            return None                     # garde-fou : loyer mensuel attendu185        price = None186        pm = _RENT_RE.search(price_label)187        if pm:188            try:189                price = float(pm.group(1).replace(" ", "").replace(" ", "")190                              .replace(",", ""))191            except ValueError:192                price = None193194        beds = _int(_after(lines, "chambres"))          # « 3 + 1 » -> 4195        baths = _after(lines, "salles de bains")196        sqft = _int(_after(lines, "pc"))                # PC = pieds carrés197198        # sans chambres, c'est souvent un local commercial loué au mois :199        # on exige un marqueur résidentiel dans l'extrait (studio, bachelor…)200        unit_type = f"{beds} chambres" if beds else ""201        if beds is None:202            if not _RESIDENTIAL_RE.search(snippet):203                return None204            if re.search(r"\b(studios?|bachelor)\b", snippet, re.I):205                unit_type = "Studio"206207        # ville « Montréal (Le Plateau-Mont-Royal) » -> ville + secteur ;208        # les cartes tronquent à ~30 caractères (« Notr... ») -> on nettoie209        city, sector = city_raw, ""210        cm = re.match(r"^(.*?)\s*\(([^)]*)\)?\s*$", city_raw)211        if cm and cm.group(2):212            city, sector = cm.group(1).strip(), cm.group(2).strip()213        city = city.rstrip(".").rstrip()214        sector = re.sub(r"\.{2,}$", "", sector).rstrip("/ -")215216        # adresse parfois tronquée (« 9017 Rue Jean-Baptiste-Gauthie... ») :217        # on la laisse vide et le H1 de la fiche détail la complète218        truncated = address.endswith("...")219        title = f"{re.sub(r'[.]{3,}$', '', address)}, {city}".strip(", ")220221        lst = Listing(222            source=self.source_id,223            external_id=external_id,224            url=url,225            title=title,226            address="" if truncated else address,227            sector=sector,228            city=city,229            unit_type=unit_type,230            price=price,231            price_label=price_label,232            description=re.sub(r"[.]{3,}$", "", snippet),233            details={"Agence": "M Immobilier", "No Centris": external_id},234            images=images,235        )236        if baths:237            lst.details["Salles de bain"] = baths.replace(" + ", "+")238        if sqft:239            lst.area_sqft = float(sqft)240        return lst241242243def parse_m_detail(html: str) -> dict:244    """Galerie Centris complète + description (JSON-LD) + adresse pleine (H1)."""245    out: dict = {}246    imgs = []247    seen = set()248    for im in IMG_RE.findall(html):249        full = BASE + im250        if full not in seen:251            seen.add(full)252            imgs.append(full)253    if imgs:254        out["images"] = imgs255    desc = du.ld_description(html)256    if desc:257        out["description"] = desc258    m = _H1_RE.search(html)259    if m:260        h1 = _html.unescape(re.sub(r"<[^>]+>", " ", m.group(1))).strip()261        if h1 and re.match(r"\d", h1):262            out["address"] = h1             # complète les adresses tronquées263    # pas de table de caractéristiques exploitable sur la fiche (seule la table264    # des pièces existe, qui produirait du bruit) : galerie + description suffisent265    return out266267268def _after(lines: list[str], label: str) -> str:269    lab = label.lower()270    for i, l in enumerate(lines):271        if l.lower() == lab and i + 1 < len(lines):272            return lines[i + 1]273    return ""274275276def _int(s: str):277    if not s:278        return None279    # « 3 + 1 » -> 4 (chambres principales + sous-sol)280    nums = [int(x) for x in re.findall(r"\d+", s)]281    return sum(nums) if nums else None282
Files main
Menu

Theme