SPB Git

Repository Public

gestion_montreal.py 14.9 KB 353 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_montreal.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/gestion_montreal.py : connecteur Gestion Montréal91#   (gestion-montreal.com — Montréal, Longueuil, Repentigny, La Prairie).92#   Site immosquare rendu serveur : la page /fr/inscriptions embarque un93#   GeoJSON complet (window.properties_geojson) avec prix, adresse, photos,94#   description, chambres/salles de bain et coordonnées. Les pages détail95#   /fr/inscriptions/<slug> ajoutent les sections structurées « Équipements /96#   Caractéristiques / Services / Animaux » (via self.detail, mises en cache).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import html as html_lib102import json103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_area_sqft, strip_accents108from .base import BaseConnector109110BASE = "https://gestion-montreal.com"111LIST_URL = f"{BASE}/fr/inscriptions"112113# Garde-fou géographique : bounding box du Grand Montréal (CMM approx.)114BBOX = (-74.30, 45.15, -73.10, 45.85)   # lng_min, lat_min, lng_max, lat_max115116# Nombre de chambres -> type d'unité normalisé117_BEDROOMS_TO_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}118119120def _fix_mojibake(s: str) -> str:121    """Répare 'Montrã©Al' -> 'Montréal' (UTF-8 lu en latin-1 chez la source,122    parfois re-capitalisé ensuite, d'où le 'ã©' minuscule)."""123    if not s:124        return ""125    for bad, good in (("é", "é"), ("ã©", "é"), ("è", "è"), ("ã¨", "è"),126                      ("ô", "ô"), ("ã´", "ô"), ("î", "î"), ("ã®", "î"),127                      ("É", "É"), ("à ", "à ")):128        s = s.replace(bad, good)129    # la source re-capitalise après le 'ã©' : « MontréAl » -> « Montréal »130    s = re.sub(r"([éèêôîà])([A-Z])(?=[a-z])",131               lambda m: m.group(1) + m.group(2).lower(), s)132    return s.strip()133134135def _norm_city(raw: str) -> str:136    city = _fix_mojibake(raw)137    if strip_accents(city).lower().startswith("montreal"):138        return "Montréal"139    return city140141142# Quartiers/arrondissements connus (repérés dans le titre de l'annonce)143_SECTORS = [144    "Centre-ville", "Vieux-Montréal", "Plateau-Mont-Royal", "Plateau",145    "Mile-End", "Mile End", "Griffintown", "Saint-Henri", "Petite-Italie",146    "Petite-Patrie", "Rosemont", "Hochelaga-Maisonneuve", "Hochelaga",147    "Mercier", "Tétreaultville", "Verdun", "Île-des-Sœurs", "LaSalle",148    "Lachine", "Villeray", "Parc-Extension", "Ahuntsic", "Cartierville",149    "Saint-Laurent", "Saint-Léonard", "Saint-Michel", "Anjou",150    "Montréal-Nord", "Rivière-des-Prairies", "Pointe-aux-Trembles",151    "Côte-des-Neiges", "Notre-Dame-de-Grâce", "NDG", "Outremont",152    "Westmount", "Ville-Marie", "Sud-Ouest", "Pointe-Saint-Charles",153    "Quartier latin", "Quartier des spectacles", "Vieux-Longueuil",154]155_SECTOR_RE = re.compile(156    "|".join(re.escape(s) for s in _SECTORS), re.IGNORECASE)157158159def _strip_html(s: str) -> str:160    s = html_lib.unescape(html_lib.unescape(s or ""))   # &amp;eacute; -> é161    s = re.sub(r"<[^>]+>", " ", s)162    return re.sub(r"\s+", " ", s).strip()163164165def _sector_from_text(*texts: str) -> str:166    """Repère un quartier connu dans le titre (puis la description)."""167    for text in texts:168        m = _SECTOR_RE.search(_fix_mojibake(text or ""))169        if m:170            sector = m.group(0)171            # recapitalisation propre à partir de la liste de référence172            for ref in _SECTORS:173                if ref.lower() == sector.lower():174                    return ref175            return sector176    return ""177178179class GestionMontrealConnector(BaseConnector):180    source_id = "gestion_montreal"181    request_delay = 0.6182    max_detail_requests = 150     # vraies requêtes détail par sync (hors cache)183184    def __init__(self) -> None:185        super().__init__()186        # gestion-montreal.com coupe la connexion dès que le User-Agent187        # contient un suffixe de type bot ("LouKaBot/1.0 (+courriel)") ;188        # on se présente donc avec un UA navigateur standard.189        self.session.headers["User-Agent"] = (190            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "191            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36")192193    def fetch(self) -> list[Listing]:194        listings: list[Listing] = []195        self._detail_budget = 0196        try:197            html = self.get(LIST_URL).text198        except Exception:199            return listings200201        m = re.search(r"window\.properties_geojson\s*=\s*", html)202        if not m:203            return listings204        try:205            features, _ = json.JSONDecoder().raw_decode(html[m.end():])206        except ValueError:207            return listings208209        for feat in features:210            try:211                p = feat.get("properties") or {}212                ext_id = str(p.get("id") or "")213                slug = p.get("slug_link") or ""214                if not ext_id or not slug:215                    continue216217                # exclusions : déjà loué, non résidentiel218                flag = (p.get("property_flag") or {})219                if isinstance(flag, dict) and flag.get("fr") == "Loué":220                    continue221                if p.get("sold_rented"):222                    continue223                classification = ((p.get("property_classification") or {})224                                  .get("fr") or "")225                if re.search(r"stationnement|commercial|bureau|local|terrain|"226                             r"industriel|garage|entrep[oô]t", classification, re.I):227                    continue228229                # garde-fou géographique (Grand Montréal seulement)230                coords = (feat.get("geometry") or {}).get("coordinates") or []231                lng, lat = (coords + [None, None])[:2]232                if lng is not None and lat is not None and not (233                        BBOX[0] <= lng <= BBOX[2] and BBOX[1] <= lat <= BBOX[3]):234                    continue235236                city = _norm_city(p.get("locality") or "")237                title_i18n = p.get("title") or {}238                title = _fix_mojibake(title_i18n.get("fr")239                                      or title_i18n.get("en")240                                      or p.get("address_short") or "")241                desc_fr = ((p.get("description") or {}).get("fr") or "")242                sector = (p.get("sublocality") or "").strip() or \243                    _sector_from_text(title, desc_fr[:800])244245                # type d'unité : Studio/Chambre/Maison direct, sinon chambres246                if re.search(r"studio", classification, re.I):247                    unit_type = "Studio"248                elif re.search(r"chambre", classification, re.I):249                    unit_type = "Chambre"250                elif re.search(r"maison", classification, re.I):251                    unit_type = "Maison"252                else:253                    unit_type = _BEDROOMS_TO_TYPE.get(254                        p.get("bedrooms"),255                        normalize_unit_type(classification))256257                price = p.get("price")258                price = float(price) if isinstance(price, (int, float)) else None259                price_label = ((p.get("prices_formatted") or {}).get("fr")260                               or p.get("price_formatted") or "")261262                desc_i18n = p.get("description") or {}263                description = _strip_html(desc_i18n.get("fr")264                                          or desc_i18n.get("en") or "")[:600]265266                amenities: list[str] = []267                if re.search(r"meubl", classification, re.I):268                    amenities.append("Meublé")269                bathrooms = p.get("bathrooms")270                if isinstance(bathrooms, (int, float)) and bathrooms > 0:271                    amenities.append(f"{int(bathrooms)} salle(s) de bain")272273                # superficie structurée (rare : « 800 pc »)274                area_sqft = None275                if p.get("area"):276                    area_sqft = parse_area_sqft(str(p.get("area_formatted")277                                                    or ""))278279                # page détail : sections « Équipements / Caractéristiques /280                # Services / Animaux » (cache BD, plafonné par sync)281                detail_url = f"{BASE}/fr/inscriptions/{slug}"282                key = hashlib.sha1(json.dumps(283                    [p.get("updated_at"), p.get("major_updated_at"),284                     p.get("price"), p.get("availability_date"),285                     title], ensure_ascii=False).encode()).hexdigest()[:16]286                payload = self.detail(ext_id, key,287                                      lambda u=detail_url: self._fetch_detail(u))288                amenities += [a for a in (payload.get("amenities") or [])289                              if a not in amenities]290                details: dict = {}291                if payload.get("phone"):292                    details["contact"] = {"phone": payload["phone"]}293294                images = [u for u in (p.get("assets") or [])295                          if isinstance(u, str)296                          and not re.search(r"placehold|logo|icon", u, re.I)]297298                listings.append(Listing(299                    source=self.source_id,300                    external_id=ext_id,301                    url=detail_url,302                    title=title or _fix_mojibake(p.get("address_short") or ""),303                    address=_fix_mojibake(p.get("address_short")304                                          or p.get("address") or ""),305                    sector=sector,306                    city=city,307                    unit_type=unit_type,308                    price=price,309                    price_label=price_label,310                    availability=(p.get("availability_date") or "")[:10],311                    area_sqft=area_sqft,312                    description=description,313                    amenities=amenities,314                    details=details,315                    images=list(dict.fromkeys(images)),316                    lat=lat,317                    lng=lng,318                ))319            except Exception:320                continue321322        return listings323324    # -- page détail : commodités structurées -----------------------------------325    def _fetch_detail(self, url: str) -> dict:326        """Sections « Autres » de la fiche : Équipements, Caractéristiques327        Intérieures/Extérieures, Services, Animaux, Transport (items <small>).328        Retourne {} au-delà du budget de requêtes (les hits de cache ne329        passent pas par ici)."""330        if self._detail_budget >= self.max_detail_requests:331            return {}332        self._detail_budget += 1333        try:334            html = self.get(url).text335        except Exception:336            return {}337        soup = BeautifulSoup(html, "html.parser")338        amenities: list[str] = []339        for small in soup.select("div.card-body ul li ul li small"):340            t = re.sub(r"\s+", " ", small.get_text(" ", strip=True))341            if t and t not in amenities:342                amenities.append(t)343        payload: dict = {}344        if amenities:345            payload["amenities"] = amenities346        tel = soup.select_one('a[href^="tel:"]')347        if tel:348            m = re.search(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})",349                          tel.get("href", ""))350            if m:351                payload["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"352        return payload353
Files main
Menu

Theme