SPB Git

Repository Public

mostra.py 14.3 KB 343 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/mostra.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/mostra.py : connecteur Mostra (condos locatifs gérés par Cogir)91#   Couvre TOUS les sites Mostra dans un seul connecteur :92#   1. mostra.ca (ColdFusion) — Mostra Longueuil et Mostra Candiac : pages93#      /fr/disponibilites-condo-<ville>.html découvertes depuis l'accueil,94#      puis rejeu de l'AJAX officiel POST /inc/ajax/unite.cfm (mêmes champs95#      que le bouton « Plus de résultats ») qui retourne UNIQUEMENT les96#      unités disponibles : emplacement, no d'unité, pi², ch./sb., modèle97#      (3 1/2…), plan PDF et loyer. Une annonce par unité disponible.98#   2. Sites satellites WordPress/Elementor (un immeuble chacun) — prix99#      « à partir de » par type d'unité, rendus serveur :100#      - mostracentropolis.ca (Laval, 550 unités, phases A/B) ;101#      - mostramascouche.ca (/appartements/) ;102#      - mostramaisonneuve.ca (/choisir-mon-unite/, Hochelaga-Maisonneuve) —103#        les types marqués « liste d'attente » sont exclus (aucune dispo).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, parse_price112from .base import BaseConnector113114BASE = "https://www.mostra.ca"115AJAX_URL = f"{BASE}/inc/ajax/unite.cfm"116117# Pages de disponibilités du site principal (découvertes depuis l'accueil)118DISPO_RE = re.compile(r'href="(?:/)?(fr/disponibilites-condo-([a-z-]+)\.html)"')119# Pages « emplacements » (fiche projet avec la galerie photo)120EMPL_RE = re.compile(121    r'href="(?:/)?(fr/emplacements-condos/\d+-mostra-([a-z-]+)\.html)"')122PROJET_RE = re.compile(r"projetID\s*=\s*'(\d+)'")123PAGE_RE = re.compile(r"var\s+p\s*=\s*'([^']+)'")124NBMAX_RE = re.compile(r'class="nombreMax"\s+value="(\d+)"')125CHSB_RE = re.compile(r"(\d+)\s*ch\.(?:\s*/\s*([\d.]+)\s*sb\.)?", re.I)126PHOTO_MAIN_RE = re.compile(r'(?:src|href)="(DATA/PHOTO/\d+_photo\.jpg)"', re.I)127BAD_IMG_RE = re.compile(r"logo|icon|favicon|plan|etage|-\d+x\d+\.|/20\d\d/0?\d/"128                        r"[A-Z][a-z]+\.png", re.I)129130# Sites satellites : un immeuble par site, prix « à partir de » par type131SATELLITES = [132    {133        "slug": "centropolis",134        "url": "https://mostracentropolis.ca/",135        "name": "Mostra Centropolis",136        "address": "2255, boulevard Daniel-Johnson, Laval",137        "sector": "Centropolis",138        "city": "Laval",139    },140    {141        "slug": "mascouche",142        "url": "https://mostramascouche.ca/appartements/",143        "name": "Mostra Mascouche",144        "address": "Mascouche",145        "sector": "",146        "city": "Mascouche",147    },148    {149        "slug": "maisonneuve",150        "url": "https://mostramaisonneuve.ca/choisir-mon-unite/",151        "name": "Mostra Maisonneuve",152        "address": "5460, rue Sherbrooke Est, Montréal",153        "sector": "Hochelaga-Maisonneuve",154        "city": "Montréal",155    },156]157158# « 3 1/2 À partir de 1550$ » (Mascouche)159SAT_TYPE_RE = re.compile(160    r"(\d\s*(?:½|1/2))\s*\|\s*À partir de\s*([\d\s]+)\s*\$", re.I)161# « Appartements 3 1/2 à louer | à partir de 1 811$ [(liste d'attente)] »162# et « Studios à louer à partir de 1 401$ (liste d'attente) » (Maisonneuve)163SAT_LOUER_RE = re.compile(164    r"(Studios?|Appartements?\s*\d\s*(?:½|1/2))\s*à\s*louer\s*(?:\|\s*)?"165    r"à\s*partir\s*de\s*([\d\s]+)\s*\$\s*(\(liste d'attente\))?", re.I)166# « 3½ - 1 chambre | à louer | Phase A : 1 800 $ | Phase B : 1 540 $ »167SAT_PHASE_BLOC_RE = re.compile(168    r"(\d½)\s*-\s*\d\s*chambres?\s*\|\s*à louer((?:\s*\|\s*Phase\s+[A-Z]\s*:"169    r"\s*[\d\s]+\s*\$)+)", re.I)170SAT_PHASE_RE = re.compile(r"Phase\s+([A-Z])\s*:\s*([\d\s]+)\s*\$", re.I)171SAT_IMG_RE = re.compile(172    r'(?:src|data-lazy-src)="(https?://[^"]*/wp-content/uploads/'173    r'[^"]+\.(?:jpg|jpeg|webp))"', re.I)174175176class MostraConnector(BaseConnector):177    source_id = "mostra"178    request_delay = 0.8179180    # -- site principal (ColdFusion) : unités disponibles via l'AJAX officiel --181    def _fetch_main(self) -> list[Listing]:182        listings: list[Listing] = []183        try:184            home = self.get(f"{BASE}/").text185        except Exception:186            return listings187        pages = {}                       # slug ville -> chemin relatif188        for path, ville in DISPO_RE.findall(home):189            pages.setdefault(ville, path)190        empl = {}                        # slug ville -> page fiche projet191        for path, ville in EMPL_RE.findall(home):192            empl.setdefault(ville, path)193194        for ville, path in pages.items():195            try:196                page = self.get(f"{BASE}/{path}").text197            except Exception:198                continue199            pm = PROJET_RE.search(page)200            pp = PAGE_RE.search(page)201            nm = NBMAX_RE.search(page)202            if not (pm and pp):203                continue204            nombre_max = nm.group(1) if nm else "500"205206            # photos : galerie de la fiche projet (page « emplacements »)207            images: list[str] = []208            if ville in empl:209                try:210                    fiche = self.get(f"{BASE}/{empl[ville]}").text211                    images = [f"{BASE}/{u}" for u in dict.fromkeys(212                        PHOTO_MAIN_RE.findall(fiche))][:12]213                except Exception:214                    images = []215216            try:217                frag = self.post(AJAX_URL, data={218                    "grandeur": 0, "chambre": 0, "exposition": 0, "prix": 0,219                    "salledebain": 0, "typeunite": 0, "typeunitePage": 0,220                    "emplacement": 0, "etage": 0,221                    "projet": pm.group(1),222                    "nombreAffichage": 500,223                    "nombreMax": nombre_max,224                    "page": pp.group(1),225                }).text226            except Exception:227                continue228            soup = BeautifulSoup(frag, "html.parser")229            for item in soup.select("div.uniteItem[data-id]"):230                try:231                    uid = item["data-id"]232                    cols = {}233                    for i in range(1, 9):234                        el = item.select_one(f".uniteItemCol.c{i}")235                        cols[i] = el.get_text(" ", strip=True) if el else ""236                    emplacement = cols[1]237                    num = re.sub(r"^\s*Unité\s*", "", cols[2]).strip()238                    sqft = cols[3]239                    modele = cols[5]                  # « 4 1/2 »240                    # loyer parfois sans « $ » (ex. « 2485 »)241                    price = parse_price(cols[7])242                    if price is None and re.fullmatch(r"[\d\s]{3,6}",243                                                      cols[7].strip()):244                        try:245                            price = float(re.sub(r"\s", "", cols[7]))246                        except ValueError:247                            price = None248                    bedrooms = bathrooms = None249                    m = CHSB_RE.search(cols[4])250                    if m:251                        bedrooms = float(m.group(1))252                        if m.group(2):253                            bathrooms = float(m.group(2))254                    amenities = []255                    if re.match(r"^\d[\d\s]*$", sqft):256                        amenities.append(f"{sqft} pi²")257                    listings.append(Listing(258                        source=self.source_id,259                        external_id=f"{ville}-{uid}",260                        url=f"{BASE}/{path}",261                        title=f"Mostra {emplacement} — "262                              f"{modele or 'unité'} · unité {num}",263                        address=emplacement,264                        sector="",265                        city=emplacement,266                        unit_type=normalize_unit_type(modele),267                        bedrooms=bedrooms,268                        bathrooms=bathrooms,269                        price=price,270                        price_label=cols[7],271                        availability="Disponible",272                        amenities=amenities,273                        images=images,274                    ))275                except Exception:276                    continue277        return listings278279    # -- satellites WordPress : prix « à partir de » par type d'unité ----------280    def _fetch_satellite(self, cfg: dict) -> list[Listing]:281        listings: list[Listing] = []282        try:283            html = self.get(cfg["url"]).text284        except Exception:285            return listings286        soup = BeautifulSoup(html, "html.parser")287        text = soup.get_text(" | ", strip=True).replace("\xa0", " ")288        text = re.sub(r"\s+", " ", text)289290        images = [u for u in dict.fromkeys(SAT_IMG_RE.findall(html))291                  if not BAD_IMG_RE.search(u)][:15]292293        seen: set[str] = set()294295        def add(unit_raw: str, price_label: str, extra: str = ""):296            ut = normalize_unit_type(unit_raw)297            key = re.sub(r"[^\w.]", "", f"{ut}{extra}".replace("½", ".5"))298            ext_id = f"{cfg['slug']}-{key or 'u'}"299            if ext_id in seen:300                return301            seen.add(ext_id)302            title = f"{cfg['name']} — {ut}" + (f" ({extra})" if extra else "")303            listings.append(Listing(304                source=self.source_id,305                external_id=ext_id,306                url=cfg["url"],307                title=title,308                address=cfg["address"],309                sector=cfg["sector"],310                city=cfg["city"],311                unit_type=ut,312                price=parse_price(price_label),313                price_label=price_label,314                availability="Disponible",315                images=images,316            ))317318        # Centropolis : blocs « 3½ - 1 chambre | à louer | Phase A : … »319        for m in SAT_PHASE_BLOC_RE.finditer(text):320            for phase, prix in SAT_PHASE_RE.findall(m.group(2)):321                add(m.group(1), f"À partir de {prix.strip()}$",322                    extra=f"Phase {phase}")323        # Maisonneuve : « Appartements 3 1/2 à louer à partir de 1 811$ »324        for m in SAT_LOUER_RE.finditer(text):325            if m.group(3):               # « (liste d'attente) » : pas de dispo326                continue327            unit_raw = "Studio" if m.group(1).lower().startswith("studio") \328                else m.group(1)329            add(unit_raw, f"À partir de {m.group(2).strip()}$")330        # Mascouche : « 3 1/2 | À partir de 1550$ »331        for m in SAT_TYPE_RE.finditer(text):332            add(m.group(1), f"À partir de {m.group(2).strip()}$")333        return listings334335    def fetch(self) -> list[Listing]:336        listings = self._fetch_main()337        for cfg in SATELLITES:338            try:339                listings.extend(self._fetch_satellite(cfg))340            except Exception:341                continue342        return listings343
Files main
Menu

Theme