SPB Git

Repository Public

moderno.py 12.5 KB 302 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/moderno.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/moderno.py : connecteur Moderno Construction (moderno.immo)91#   Promoteur-gestionnaire de Lanaudière (Joliette — Aqua Roca, Domaine du92#   Sentier Riverain). Site custom SSR très propre : /logements-a-louer liste93#   des cartes BEM (titre, disponibilité, prix, adresse, badge « Loué »),94#   chaque carte pointe vers /logements-a-louer/<projet>/<CODE> ; le CODE95#   (= champ « Référence » de la fiche) sert d'external_id stable. La fiche96#   détail (via cache BD) ajoute chambres/sdb, unité/niveau/vue/superficie,97#   inclusions, commodités, description et galerie.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://moderno.immo"110LIST_URL = f"{BASE}/logements-a-louer"111112_CARD = "appartements-a-louer__liste__item"113_DET = "details-appartement__details"114115# vignettes DigitalOcean Spaces : ".../<id>/conversions/<nom>-thumb.jpg"116# -> pleine taille ".../<id>/<nom>.jpg" (même schéma que les images de cartes)117_THUMB_RE = re.compile(r"/conversions/(.+?)-(?:first_)?thumb(\.\w+)$")118119120def _full_img(url: str) -> str:121    return _THUMB_RE.sub(r"/\1\2", url.strip())122123124class ModernoConnector(BaseConnector):125    source_id = "moderno"126    request_delay = 0.7127    max_details = 40    # garde-fou fiches détail (vraies requêtes par sync)128129    def fetch(self) -> list[Listing]:130        html = self.get(LIST_URL).text131        soup = BeautifulSoup(html, "html.parser")132        listings: dict[str, Listing] = {}133        for card in soup.select(f"a.{_CARD}[href]"):134            try:135                self._parse_card(card, listings)136            except Exception:137                continue138139        self._fetched = 0140        for lst in listings.values():141            key = hashlib.sha1(142                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.address}"143                .encode("utf-8")).hexdigest()144            try:145                payload = self.detail(lst.external_id, key,146                                      lambda u=lst.url: self._fetch_detail(u))147            except Exception:148                continue149            self._apply_detail(lst, payload)150        return list(listings.values())151152    # -- carte liste ------------------------------------------------------------153    def _parse_card(self, card, listings: dict[str, Listing]) -> None:154        url = card["href"]155        if url.startswith("/"):156            url = BASE + url157        m = re.search(r"/logements-a-louer/([^/]+)/([A-Z0-9]+)/?$", url)158        if not m:159            return160        project_slug, code = m.group(1), m.group(2)161        if code in listings:162            return163164        def _txt(suffix: str) -> str:165            el = card.select_one(f".{_CARD}__{suffix}")166            return re.sub(r"\s+", " ", el.get_text(" ", strip=True)) if el else ""167168        # badge « Loué » : annonce déjà partie, on l'ignore169        if re.search(r"lou[ée]", _txt("rented"), re.I):170            return171172        title = _txt("titre")                      # « 4 1/2 - Domaine du Sentier Riverain »173        address_full = _txt("adresse")             # « 105-1002 rue Gustave-Guertin, Joliette »174        parts = [p.strip() for p in address_full.split(",") if p.strip()]175        address = re.sub(r"\s+", " ", parts[0]) if parts else ""176        city = parts[-1] if len(parts) > 1 else ""177        price_label = _txt("prix")                 # « 1 915 $ par mois »178        message = _txt("message")                  # accroche rédigée par Moderno179180        images: list[str] = []181        img = card.select_one("img[src]")182        if img and img["src"].startswith("http"):183            images.append(_full_img(img["src"]))184185        listings[code] = Listing(186            source=self.source_id,187            external_id=code,                      # champ « Référence » de la fiche188            url=url,189            title=title,190            address=address,191            city=city,192            unit_type=normalize_unit_type(title),193            price=parse_price(price_label),194            price_label=price_label,195            availability=_txt("disponibilite"),    # « Disponible 1er octobre 2026 »196            description=message,197            details={"project": project_slug},198            images=images,199        )200201    # -- fiche détail -------------------------------------------------------------202    def _fetch_detail(self, url: str) -> dict:203        """Chambres/sdb, chiffres (unité, niveau, vue, superficie, dispo),204        inclusions + commodités, description et galerie pleine taille."""205        if self._fetched >= self.max_details:206            raise RuntimeError("budget de fiches détail atteint")207        self._fetched += 1208        html = self.get(url).text209        soup = BeautifulSoup(html, "html.parser")210        out: dict = {}211212        det = soup.select_one(f"section.{_DET}")213        if det is None:214            return out215216        # adresse complète de la fiche (parfois plus propre que la carte)217        addr = det.select_one(f".{_DET}__adresse")218        if addr:219            out["address_full"] = re.sub(r"\s+", " ", addr.get_text(" ", strip=True))220221        # « 1 chambre », « 1 salle de bain »222        out["pieces"] = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))223                         for p in det.select(f".{_DET}__pieces__piece")]224225        # paires libellé/valeur : Unité, Niveau, Vue, Superficie, Disponibilité, Référence226        chiffres: dict[str, str] = {}227        for div in det.select(f".{_DET}__chiffres > div"):228            ps = div.find_all("p")229            if len(ps) >= 2:230                lab = ps[0].get_text(" ", strip=True)231                val = re.sub(r"\s+", " ", ps[1].get_text(" ", strip=True))232                if lab and val:233                    chiffres[lab] = val234        out["chiffres"] = chiffres235236        # Inclusions (eau chaude, internet…) et Commodités (logement + immeuble)237        feats: list[str] = []238        for box in det.select(f".{_DET}__inclusions, .{_DET}__commodites"):239            items = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))240                     for li in box.find_all("li")]241            if not items:   # listes parfois en <p>242                items = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))243                         for p in box.find_all("p")][1:]244            head = box.find(["h4", "h5", "div"])245            head_txt = head.get_text(" ", strip=True) if head else ""246            if re.match(r"(?i)localisation", head_txt):247                continue                             # adresse déjà captée248            for it in items:249                if it and it not in feats and not re.match(r"(?i)inclusions|commodit|caractéristiques|localisation", it):250                    feats.append(it)251        out["features"] = feats[:40]252253        # description : accroche + paragraphes rédigés de la fiche254        msg = det.select_one(f".{_DET}__message")255        paras = [msg.get_text(" ", strip=True)] if msg else []256        for p in det.find_all("p"):257            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))258            if len(t) > 60 and t not in paras:259                paras.append(t)260        out["description"] = "\n".join(paras)[:1200]261262        # galerie (vignettes /conversions/ -> pleine taille)263        images: list[str] = []264        for img in soup.select(".details-appartement__introduction__galerie img[src]"):265            u = _full_img(img["src"])266            if u.startswith("http") and u not in images:267                images.append(u)268        out["images"] = images[:30]269        return out270271    def _apply_detail(self, lst: Listing, d: dict) -> None:272        if not d:273            return274        ch = d.get("chiffres") or {}275        details = dict(lst.details)276        for lab, key in (("Unité", "unit_number"), ("Niveau", "floor"),277                         ("Vue", "view"), ("Référence", "reference")):278            if ch.get(lab):279                details[key] = ch[lab]280        lst.details = details281        m = re.match(r"([\d\s,.]+)\s*pi", ch.get("Superficie", ""))282        if m:283            try:284                lst.area_sqft = float(m.group(1).replace(" ", "").replace(",", ""))285            except ValueError:286                pass287        if ch.get("Disponibilité") and not lst.availability:288            lst.availability = ch["Disponibilité"]289        if d.get("address_full") and not lst.address:290            parts = [p.strip() for p in d["address_full"].split(",")]291            lst.address = parts[0]292            if len(parts) > 1 and not lst.city:293                lst.city = parts[-1]294        extra = (d.get("pieces") or []) + (d.get("features") or [])295        if extra:296            lst.amenities = list(dict.fromkeys(lst.amenities + extra))297        if d.get("description"):298            lst.description = d["description"]299        if d.get("images"):300            merged = d["images"] + [u for u in lst.images if u not in d["images"]]301            lst.images = merged[:30]302
Files main
Menu

Theme