SPB Git

Repository Public

msi.py 17.9 KB 416 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/msi.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-1814#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/msi.py : connecteur MSI Gestion immobilière (msimmobiliers.com)91#   Crawl des pages de secteurs (rendu serveur) : Québec + Lévis + Montréal92#   + Thetford Mines (flux intermittent — souvent 0 unité).93#   Front Next.js : chaque fiche embarque un objet JSON `rental` complet dans94#   le payload « flight » (self.__next_f.push) — adresse + code postal,95#   lat/lng, date de disponibilité ISO, étage, superficie, caractéristiques96#   structurées (features), galerie photo, politique chiens (dogPolicy).97#   Fiches visitées via self.detail(...) (cache BD, plafond de requêtes).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import json103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, infer_city, normalize_unit_type, parse_price108from .base import BaseConnector109110BASE = "https://www.msimmobiliers.com"111ROOTS = [112    f"{BASE}/appartements-a-louer/quebec",113    f"{BASE}/appartements-a-louer/levis",114    f"{BASE}/appartements-a-louer/montreal",115    f"{BASE}/appartements-a-louer/thetford-mine",116]117UNIT_RE = re.compile(r"/appartements-a-louer/[^\"]*appartement-(\d+)[^\"]*")118LIST_RE = re.compile(r"^/appartements-a-louer/[a-z0-9\-/]+$")119# ville par défaut selon la racine de l'URL (/appartements-a-louer/<ville>/...)120_ROOT_CITY = {"quebec": "Québec", "levis": "Lévis", "montreal": "Montréal",121              "thetford-mine": "Thetford Mines"}122123# morceaux de chaîne JS des payloads flight : self.__next_f.push([1,"..."])124_FLIGHT_RE = re.compile(125    r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')126127128def _default_city(path_or_url: str) -> str:129    m = re.search(r"/appartements-a-louer/([a-z0-9\-]+)", path_or_url)130    return _ROOT_CITY.get(m.group(1) if m else "", "Québec")131132133def _extract_rental(html: str) -> dict:134    """Extrait l'objet JSON `rental` du payload flight Next.js de la fiche."""135    for m in _FLIGHT_RE.finditer(html):136        try:137            chunk = json.loads('"' + m.group(1) + '"')  # dés-échappe la chaîne138        except ValueError:139            continue140        i = chunk.find('"rental":{')141        if i < 0:142            continue143        start = i + len('"rental":')144        depth = 0145        in_str = esc = False146        for j in range(start, len(chunk)):147            c = chunk[j]148            if esc:149                esc = False150            elif c == "\\":151                esc = True152            elif in_str:153                in_str = c != '"'154            elif c == '"':155                in_str = True156            elif c == "{":157                depth += 1158            elif c == "}":159                depth -= 1160                if depth == 0:161                    try:162                        return json.loads(chunk[start:j + 1])163                    except ValueError:164                        return {}165        break166    return {}167168169class _CapAtteint(Exception):170    """Plafond de requêtes détail atteint pour cette synchronisation."""171172173class MSIConnector(BaseConnector):174    source_id = "msi"175    request_delay = 0.5176    max_list_pages = 90      # garde-fou de crawl (Qc + Lévis + Mtl)177    max_real_details = 150   # vraies requêtes détail par sync (cache exclu)178179    def fetch(self) -> list[Listing]:180        self._real_details = 0181        # 1) BFS sur les pages de listes (arrondissements / quartiers)182        to_visit = list(ROOTS)183        visited: set[str] = set()184        listings: dict[str, Listing] = {}185        card_keys: dict[str, str] = {}186187        while to_visit and len(visited) < self.max_list_pages:188            url = to_visit.pop(0)189            if url in visited:190                continue191            visited.add(url)192            try:193                html = self.get(url).text194            except Exception:195                continue196            soup = BeautifulSoup(html, "html.parser")197198            # cartes d'unités199            for card in soup.select('a[href*="appartement-"]'):200                href = card.get("href", "")201                m = UNIT_RE.search(href)202                if not m:203                    continue204                ext_id = m.group(1)205                if ext_id in listings:206                    continue207                full_url = href if href.startswith("http") else BASE + href208                text = card.get_text("|", strip=True)209                parts = [p for p in text.split("|") if p and p != "Voir cette fiche"]210                # Format observé : "4 1/2 | 1195$ / mois | Appartement / Condo |211                #                   177 Avenue Ruel | Chutes-Montmorency | Libre ..."212                unit_type = price_label = category = address = sector = avail = ""213                for p in parts:214                    if not unit_type and re.match(r"^\d\s*1/2$|^Studio|^Loft", p, re.I):215                        unit_type = p216                    elif not price_label and "$" in p:217                        price_label = p218                    elif not category and re.search(r"Appartement|Condo|Maison|Commercial|Stationnement", p, re.I):219                        category = p220                    elif not address and re.match(r"^\d+[\s,]", p):221                        address = p222                    elif not avail and re.search(r"Libre|Disponib", p, re.I):223                        avail = p224                    elif not sector and address:225                        sector = p226                # ignorer stationnements/espaces commerciaux227                if re.search(r"Stationnement|Commercial|Rangement|Parking", category or "", re.I):228                    continue229                city = _default_city(href if "/appartements-a-louer/" in href230                                     else url)231                listings[ext_id] = Listing(232                    source=self.source_id,233                    external_id=ext_id,234                    url=full_url,235                    title=address or parts[0] if parts else f"Unité {ext_id}",236                    address=address,237                    sector=sector,238                    city=infer_city(sector, default=city),239                    unit_type=normalize_unit_type(unit_type),240                    price=parse_price(price_label),241                    price_label=price_label,242                    availability=avail,243                )244                card_keys[ext_id] = hashlib.sha1(245                    "|".join(parts).encode("utf-8")).hexdigest()[:16]246247            # sous-pages de secteurs248            for a in soup.select('a[href^="/appartements-a-louer/"]'):249                href = a.get("href", "").split("?")[0]250                if LIST_RE.match(href) and "appartement-" not in href:251                    nxt = BASE + href252                    if nxt not in visited:253                        to_visit.append(nxt)254255        # 2) Fiches détaillées (cache BD) : JSON rental + caractéristiques256        for ext_id, lst in listings.items():257            det = self._unit_detail(ext_id, lst.url,258                                    card_keys.get(ext_id, ""))259            if not det:260                continue261            if det.get("images"):262                lst.images = det["images"][:25]263            if det.get("address_full"):264                lst.address = det["address_full"]   # avec ville (plus complet)265            lst.lat, lst.lng = det.get("lat"), det.get("lng")266            if det.get("area"):267                lst.area_sqft = det["area"]268            if det.get("availability") and not lst.availability:269                lst.availability = f"Disponibilité : {det['availability']}"270            lst.amenities = det.get("amenities") or []271            if det.get("floor"):272                lst.details = {**lst.details, "floor": det["floor"]}273            for k in ("walkScore", "bikeScore", "transitScore"):274                if det.get(k):275                    lst.details = {**lst.details, k: det[k]}276            dog = det.get("dog_policy") or ""277            if dog:278                lst.pets = ("non" if "not" in dog or "interdit" in dog279                            else "oui" if dog in ("allowed", "accepted")280                            else "conditions")281            lst.description = self._compose_description(lst, det)282283        return list(listings.values())284285    @staticmethod286    def _compose_description(lst: Listing, det: dict) -> str:287        """Description texte propre dérivée des champs structurés de la fiche288        (MSI n'a pas de description libre par unité, seulement un slogan)."""289        phrases: list[str] = []290        if det.get("catchphrase"):291            phrases.append(det["catchphrase"].rstrip(". ") + ".")292        unit = lst.unit_type or "Logement"293        rooms = det.get("rooms")294        seg = f"{unit} de {int(rooms)} chambre(s)" if rooms else unit295        floor = det.get("floor")296        if floor:297            if floor == 1 and det.get("floor_level") == "ground":298                seg += " au rez-de-chaussée"299            else:300                seg += (" au 1er étage" if floor == 1301                        else f" au {floor}e étage")302        if det.get("floor_level") == "last" and floor and floor > 1:303            seg += " (dernier étage)"304        if det.get("area"):305            seg += f", {det['area']:.0f} pi²"306        phrases.append(seg + ".")307        # écarter les items déjà couverts par la phrase de tête / la politique308        # chiens / les scores de mobilité (repris dans details)309        amen = [a for a in (det.get("amenities") or [])310                if not a.startswith("**")311                and not re.match(r"(?i)\d+\s*chambre|chien", a)312                and not re.search(r"(?i)score", a)313                and not (floor and re.fullmatch(314                    rf"(?i){floor}\s*e?r?\s*étage", a.strip()))315                and not (det.get("floor_level") == "last"316                         and re.fullmatch(r"(?i)dernier étage", a.strip()))]317        if amen:318            phrases.append(", ".join(amen) + ".")319        dog = det.get("dog_policy") or ""320        if "not" in dog:321            phrases.append("Chiens interdits.")322        elif dog in ("allowed", "accepted"):323            phrases.append("Chiens acceptés.")324        elif dog:325            phrases.append("Chiens acceptés sous conditions.")326        if det.get("availability") and not lst.availability:327            phrases.append(f"Disponible : {det['availability']}.")328        return " ".join(phrases)[:900]329330    def _unit_detail(self, ext_id: str, url: str, card_key: str) -> dict:331        """Fiche unité : objet JSON `rental` (flight Next.js) + liste des332        caractéristiques affichées (textes bruts, incl. chiens/fumeur)."""333        def _fetch() -> dict:334            if self._real_details >= self.max_real_details:335                raise _CapAtteint()336            self._real_details += 1337            html = self.get(url).text338            out: dict = {}339340            rental = _extract_rental(html)341            adr = rental.get("address") or {}342            if isinstance(adr, dict):343                out["address_full"] = adr.get("full") or ""344                if isinstance(adr.get("lat"), (int, float)):345                    out["lat"] = adr["lat"]346                if isinstance(adr.get("lng"), (int, float)):347                    out["lng"] = adr["lng"]348            area = rental.get("area")349            if isinstance(area, (int, float)) and 80 <= area <= 20000:350                out["area"] = float(area)351            floor = rental.get("floor")352            if isinstance(floor, int) and 0 < floor <= 60:353                out["floor"] = floor354            avail = rental.get("availability")355            if isinstance(avail, str) and avail:356                out["availability"] = avail357            catch = rental.get("catchphrase")358            if isinstance(catch, str) and catch and "$undefined" not in catch:359                out["catchphrase"] = re.sub(r"\s+", " ", catch).strip()360            # champs structurés pour la description dérivée (le site n'a pas361            # de texte libre par unité en dehors du catchphrase — vérifié362            # 2026-08-18) + politique chiens363            rooms = rental.get("rooms")364            if isinstance(rooms, (int, float)) and 0 <= rooms <= 10:365                out["rooms"] = rooms366            if rental.get("floorLevel") in ("last", "ground"):367                out["floor_level"] = rental["floorLevel"]368            dog = rental.get("dogPolicy")369            if isinstance(dog, str) and dog:370                out["dog_policy"] = dog371            for k in ("walkScore", "bikeScore", "transitScore"):372                v = rental.get(k)373                if isinstance(v, (int, float)) and v > 0:374                    out[k] = int(v)375            imgs = []376            for ph in rental.get("gallery") or []:377                u = ((ph.get("sizes") or {}).get("large") if378                     isinstance(ph, dict) else None)379                if u and u not in imgs:380                    imgs.append(u)381382            # Caractéristiques affichées (textes bruts : « Balcon »,383            # « Chien interdit », « Non fumeur », « Dernier étage »…)384            soup = BeautifulSoup(html, "html.parser")385            amenities: list[str] = []386            cat_name = ((rental.get("category") or {}).get("name") or "")387            for li in soup.select(".rental-content__hero--facilities li"):388                if li.find("a"):389                    continue        # lien Google Maps (adresse)390                txt = li.get_text(" ", strip=True)391                if (not txt or txt in ("N/C",) or txt.startswith("**")392                        or txt == cat_name or len(txt) > 60):393                    continue394                if txt not in amenities:395                    amenities.append(txt)396            if not amenities:       # repli : features structurées du JSON397                amenities = [f.get("name") for f in398                             (rental.get("features") or []) +399                             (rental.get("secondaryFeatures") or [])400                             if isinstance(f, dict) and f.get("name")]401            out["amenities"] = amenities[:20]402403            if not imgs:            # repli : images wp-content de la page404                imgs = [u for u in dict.fromkeys(re.findall(405                    r'https://api\.msimmobiliers\.com/wp-content/uploads/'406                    r'[^"\\\s\)]+\.(?:jpg|jpeg|png|webp)', html))407                    if not re.search(r"logo|icon|favicon", u, re.I)]408            out["images"] = imgs[:25]409            return out410411        try:412            # « v3 » invalide le cache d'avant l'enrichissement description413            return self.detail(ext_id, f"v3|{card_key}", _fetch)414        except Exception:415            return {}416
Files main
Menu

Theme