SPB Git

Repository Public

minto.py 15.8 KB 374 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/minto.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-2714#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/minto.py : connecteur Minto Apartments (mintoapartments.com)91#   Page « projects » Montréal rendue serveur : Rockhill, Haddon Hall, Le 4300,92#   Le Hill-Park. Chaque fiche propriété (main.html) liste ses types de suites93#   dans des cartes .projects-apartamets-unit-card : nom (h4), disponibilité94#   (« Available now » / « Available September 17 » / « Not available »),95#   prix ($X - $Y), pi² (span icon-svg-column), sdb, galerie photo par type96#   (tableaux JS `lightboxImages…`). La section Contact donne l'adresse97#   complète, le quartier (« Neighbourhood: ») et le téléphone/courriel ;98#   les sections Features listent les commodités (items à coche).99#   Une annonce par type de suite disponible.100#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO=1 : Minto est d'abord101#   ottavien ; on ajoute les pages « projects » d'Ottawa102#   (/ottawa/apartment-rentals/…) et de la GTA103#   (/gta/<Secteur>-apartment-rentals/… : Toronto, Etobicoke, North York,104#   Mississauga, Oakville). Même structure de fiches (cartes105#   .projects-apartamets-unit-card). Sans la variable d'environnement,106#   comportement strictement identique (prod QC).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import os111import re112113from bs4 import BeautifulSoup114115from ..schema import Listing, normalize_unit_type, parse_price, strip_accents116from .base import BaseConnector117118BASE = "https://www.mintoapartments.com"119LIST_URL = f"{BASE}/montreal/apartment-rentals/projects.html"120121PROJECT_RE = re.compile(122    r'https?://www\.mintoapartments\.com/montreal/apartment-rentals/'123    r'([A-Za-z0-9\-]+)/main\.html')124LIGHTBOX_RE = re.compile(r'var\s+lightboxImages(\d+)\s*=\s*\[(.*?)\];', re.S)125IMG_SRC_RE = re.compile(r"src:\s*'([^']+)'")126_PHONE_RE = re.compile(r"tel:([\d\-() .]{7,20})")127_EMAIL_RE = re.compile(r"mailto:([\w.+-]+@[\w-]+\.[\w.]+)")128129# Secteurs connus recherchés dans le <title> (repli si pas de130# « Neighbourhood: ») ; certains sont des villes distinctes de l'île.131_KNOWN_SECTORS = [132    "Côte-des-Neiges", "Westmount", "Côte-Saint-Luc", "Mont-Royal",133    "Notre-Dame-de-Grâce", "NDG", "Griffintown", "Plateau", "Ville-Marie",134    "Downtown",135]136_CITY_SECTORS = {"westmount": "Westmount", "mont-royal": "Mont-Royal",137                 "cote-saint-luc": "Côte-Saint-Luc"}138139# --- Expansion Ontario (gaté LOUKA_ONTARIO=1 ; prod QC intacte sans) ---------140_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"141142LIST_URLS_ON = [143    f"{BASE}/ottawa/apartment-rentals/projects.html",144    f"{BASE}/gta/apartment-rentals/projects.html",145]146# /<région>/<sous-chemin>/<slug>/main.html — le sous-chemin GTA porte le147# secteur (ex. North-York-apartment-rentals), celui d'Ottawa est simplement148# apartment-rentals149PROJECT_ON_RE = re.compile(150    r'https?://www\.mintoapartments\.com/(ottawa|gta)/'151    r'([A-Za-z0-9\-]+)/([A-Za-z0-9\-]+)/main\.html')152153# secteur d'URL GTA (minuscule, sans -apartment-rentals) -> (ville, secteur)154_ON_AREAS = {155    "ottawa": ("Ottawa", ""),156    "toronto": ("Toronto", ""),157    "downtown-toronto": ("Toronto", "Downtown"),158    "etobicoke": ("Toronto", "Etobicoke"),159    "north-york": ("Toronto", "North York"),160    "mississauga": ("Mississauga", ""),161    "oakville": ("Oakville", ""),162}163164165class MintoConnector(BaseConnector):166    source_id = "minto"167    request_delay = 0.6168    max_projects = 12        # garde-fou (QC)169    max_projects_on = 40     # garde-fou distinct pour l'Ontario (gaté)170    max_images = 25171172    def fetch(self) -> list[Listing]:173        html = self.get(LIST_URL).text174        slugs = list(dict.fromkeys(PROJECT_RE.findall(html)))175176        listings: list[Listing] = []177        for slug in slugs[: self.max_projects]:178            try:179                listings.extend(self._project_listings(slug))180            except Exception:181                continue182183        # Expansion Ontario (gaté LOUKA_ONTARIO=1) : Ottawa + GTA, budget de184        # projets distinct pour ne rien enlever à la couverture QC185        if _ONTARIO:186            n_on = 0187            for list_url in LIST_URLS_ON:188                try:189                    on_html = self.get(list_url).text190                except Exception:191                    continue192                for region, mid, slug in dict.fromkeys(193                        PROJECT_ON_RE.findall(on_html)):194                    # exclure les meublés courte durée (furnished-apartments)195                    if not mid.endswith("apartment-rentals"):196                        continue197                    if n_on >= self.max_projects_on:198                        break199                    n_on += 1200                    area = (re.sub(r"-?apartment-rentals$", "", mid)201                            .strip("-").lower() or region)202                    city, sector = _ON_AREAS.get(203                        area, (area.replace("-", " ").title(), ""))204                    try:205                        listings.extend(self._project_listings(206                            slug, region=region, subpath=mid,207                            on_city=city, on_sector=sector, province="ON"))208                    except Exception:209                        continue210        return listings211212    def _project_listings(self, slug: str, region: str = "montreal",213                          subpath: str = "apartment-rentals",214                          on_city: str = "", on_sector: str = "",215                          province: str = "QC") -> list[Listing]:216        url = f"{BASE}/{region}/{subpath}/{slug}/main.html"217        html = self.get(url).text218        soup = BeautifulSoup(html, "html.parser")219220        name = slug.replace("-", " ").strip()221        h1 = soup.find("h1")222        if h1 and h1.get_text(strip=True):223            name = h1.get_text(" ", strip=True)224        t = soup.find("title")225        title_text = t.get_text(strip=True) if t else ""226227        # Quartier : « Neighbourhood: Shaughnessy Village » (section Contact),228        # sinon premier quartier connu mentionné dans le <title>229        sector = ""230        nm = re.search(r"Neighbourhood:\s*([^<\n]{2,50})", html)231        if nm:232            sector = nm.group(1).strip()233        if province == "ON":234            # ville/secteur dérivés de l'URL de la page « projects » (GTA) ;235            # le « Neighbourhood: » de la fiche a priorité s'il est publié236            city = on_city237            sector = sector or on_sector238        else:239            if not sector:240                for s in _KNOWN_SECTORS:241                    if s.lower() in title_text.lower():242                        sector = "Centre-ville" if s == "Downtown" else s243                        break244            city = _CITY_SECTORS.get(strip_accents(sector.lower()), "Montréal")245        if sector == city:246            sector = ""247248        # Adresse complète (section Contact : rue + ville + code postal)249        address = ""250        am = re.search(251            r'font-weight:\s*normal">\s*([^<]{8,140})</p>', html)252        if am:253            address = re.sub(r"\s*\n\s*", ", ", am.group(1).strip())254            address = re.sub(r"\s+", " ", address)255        if not address:256            am = re.search(257                r'\d{2,5},?\s+(?:chemin|chem\.|avenue|rue|boulevard|c[ôo]te)'258                r'[^<>"{}]{3,60}', html, re.I)259            if am:260                address = re.sub(r"\s+", " ", am.group(0)).strip().rstrip(",")261        if province == "ON" and address:262            address = re.sub(r",\s*,", ",", address)   # « Drive,, Etobicoke »263            if not re.search(r"\bON\b", address):264                address = f"{address}, ON"265266        # Contact location (téléphone / courriel) -> details.contact267        details: dict = {}268        contact: dict = {}269        pm = _PHONE_RE.search(html)270        if pm:271            contact["phone"] = pm.group(1).strip()272        em = _EMAIL_RE.search(html)273        if em:274            contact["email"] = em.group(1)275        if contact:276            details["contact"] = contact277278        # Photos de la propriété (carrousel d'entête, repli des galeries)279        hero = [u for u in re.findall(280            r'https://media\.minto\.com/(?:dev/)?slideshows/[^"\'\s]+'281            r'\.(?:jpg|jpeg|png|webp)', html)]282        hero = list(dict.fromkeys(hero))[:8]283284        # Commodités : items à coche des sections « Building features » /285        # « Suite features » (l'astérisque « * » = dans certaines suites)286        amenities: list[str] = []287        for span in soup.select('li span[class*="icon-svg-check-mark"]'):288            li = span.find_parent("li")289            txt = li.get_text(" ", strip=True) if li else ""290            if txt and txt not in amenities and len(txt) < 60:291                amenities.append(txt)292        amenities = amenities[:30]293294        og = soup.find("meta", attrs={"name": "description"})295        desc = (og.get("content", "").strip()[:600] if og else "")296297        listings: list[Listing] = []298        for card in soup.select(".projects-apartamets-unit-card"):299            try:300                h4 = card.select_one("h4.h-h3-minto")301                if not h4:302                    continue303                suite_name = h4.get_text(" ", strip=True)304                if not suite_name or len(suite_name) > 70:305                    continue306307                # Disponibilité par type de suite (« Available now »,308                # « Available September 17 », « Not available »)309                av_el = card.select_one('[class*="btn-availa"]')310                availability = (av_el.get_text(" ", strip=True)311                                if av_el else "")312                if re.match(r"^not\s+available$", availability, re.I):313                    continue    # type de suite non offert actuellement314315                # Prix « $1,215 - $1,305 »316                ph5 = card.select_one("h5.h-h3-minto")317                price_txt = ph5.get_text(" ", strip=True) if ph5 else ""318                pmatch = re.search(r'\$[\d,]+(?:\s*-\s*\$[\d,]+)?', price_txt)319                if not pmatch:320                    continue    # carte non tarifée321                price_label = re.sub(r"\s+", " ", pmatch.group(0))322                price = parse_price(323                    price_label.split("-")[0].replace("$", "")324                    .replace(",", "") + " $")325326                # Superficie structurée « 425 - 560 » SQ FT (min de la plage)327                area_sqft = None328                sq_icon = card.select_one("span.icon-svg-column")329                if sq_icon:330                    sib = sq_icon.find_next_sibling("span")331                    if sib:332                        nums = [float(n.replace(",", "")) for n in333                                re.findall(r"[\d,]+", sib.get_text())]334                        nums = [n for n in nums if 80 <= n <= 20000]335                        if nums:336                            area_sqft = min(nums)337338                bm = re.search(r'([\d.]+)\s*Bathroom',339                               card.get_text(" ", strip=True))340341                # Galerie du type de suite (tableau lightbox de la carte)342                imgs: list[str] = []343                gm = LIGHTBOX_RE.search(str(card))344                if gm:345                    imgs = IMG_SRC_RE.findall(gm.group(2))346                imgs = list(dict.fromkeys(imgs))[: self.max_images] or hero347348                suite_slug = re.sub(r"[^a-z0-9]+", "-",349                                    strip_accents(suite_name.lower())).strip("-")350                bits = [f"{bm.group(1)} sdb" if bm else ""]351                listings.append(Listing(352                    source=self.source_id,353                    external_id=f"{slug}-{suite_slug}",354                    url=url,355                    title=f"{name} — {suite_name}",356                    address=address,357                    sector=sector,358                    city=city,359                    province=province,360                    unit_type=normalize_unit_type(suite_name),361                    price=price,362                    price_label=f"{price_label} /mois",363                    availability=availability,364                    area_sqft=area_sqft,365                    description=" — ".join(366                        x for x in [desc] + bits if x)[:600],367                    amenities=amenities,368                    details=dict(details),369                    images=imgs,370                ))371            except Exception:372                continue373        return listings374
Files main
Menu

Theme