SPB Git

Repository Public

montagnais.py 9.2 KB 217 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/montagnais.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/montagnais.py : connecteur Le Montagnais, résidences étudiantes91#   (lemontagnais.com) — 6 campus/immeubles à Sherbrooke (Campus principal,92#   Campus de la santé, Campus Centro, Campus Mont-Bellevue, Résidences E et G),93#   location longue durée (bail) : chambres, studios, 2½ à 5½.94#   WordPress (thème Oktane « campus ») : la page /logement/ charge la liste95#   via admin-ajax `get_posts_location` (post_type=logement) qui retourne le96#   JSON complet des types de logements — titre, prix « à partir de »97#   (startingFrom), campus (habitation_terms), statut (projet_status/acf),98#   adresse structurée Google (ville, code postal, GPS), description,99#   caractéristiques ACF et photo. Granularité = type de logement par campus100#   (aucune unité individuelle publiée), comme sig.py. 1 requête par sync.101#   Seuls les types au statut « Disponible » deviennent des annonces.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://www.lemontagnais.com"113LOGEMENT_PAGE = f"{BASE}/logement/"114AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"115116117class MontagnaisConnector(BaseConnector):118    source_id = "montagnais"119    request_delay = 0.6120121    def fetch(self) -> list[Listing]:122        # POST admin-ajax : le même appel que la page /logement/ (post_type123        # logement, toutes les fiches d'un coup)124        resp = self.session.post(125            AJAX_URL,126            data={"action": "get_posts_location", "post_type": "logement",127                  "posts_per_page": "-1", "page": "1"},128            timeout=self.timeout)129        resp.raise_for_status()130        data = resp.json()131132        listings: list[Listing] = []133        seen: set[str] = set()134        for row in data.get("results") or []:135            post = (row or {}).get("post") or {}136            ext_id = str(post.get("ID") or "")137            if not ext_id or ext_id in seen:138                continue139            seen.add(ext_id)140141            # statut : « Disponible » sinon on saute (rien d'inventé)142            status = (post.get("projet_status") or "").strip()143            if status.lower() != "disponible":144                continue145146            title = (post.get("post_title") or "").strip()147            campus = (post.get("habitation_terms") or "").strip()148149            # type d'unité depuis le titre (« Logement 2 ½ », « Studio Galt150            # Ouest », « Grande chambre… ») — motif net seulement151            unit_type = normalize_unit_type(title)152            if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",153                                unit_type or ""):154                unit_type = ""155156            # prix « à partir de » (champ startingFrom / ACF logement_a_partir_de)157            raw_price = str(post.get("startingFrom") or "").strip()158            price_label = f"À partir de {raw_price} $/mois" if raw_price else ""159            price = parse_price(price_label)160            if price is None and re.fullmatch(r"\d{3,5}(?:[.,]\d{2})?", raw_price):161                price = float(raw_price.replace(",", "."))162163            # adresse structurée Google (ACF) : rue, ville, code postal, GPS164            addr = post.get("address") or {}165            street = " ".join(x for x in (166                str(addr.get("street_number") or ""),167                str(addr.get("street_name") or "")) if x).strip()168            postal = (addr.get("post_code") or "").strip()169            address = ", ".join(x for x in (street, postal) if x)170            city = (addr.get("city") or "").strip() or "Sherbrooke"171            lat, lng = addr.get("lat"), addr.get("lng")172173            # description (contenu du billet) + caractéristiques ACF (liste)174            description = re.sub(175                r"\s+", " ", (post.get("post_content") or "")).strip()[:1500]176            amenities: list[str] = []177            specs = (post.get("habitation_specs") or "").strip()178            for t in specs.split(","):179                t = t.strip()180                if t and t not in amenities:181                    amenities.append(t)182            acf = post.get("acf") or {}183            carac = acf.get("logement_caracteristiques") or ""184            if carac:185                for li in BeautifulSoup(carac, "html.parser").select("li"):186                    t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))187                    if t and t not in amenities and len(amenities) < 25:188                        amenities.append(t)189190            images = []191            thumb = (post.get("post_thumbnail_url") or "").strip()192            if thumb.startswith("http"):193                images.append(thumb)194195            details = {"residence": campus} if campus else {}196            listings.append(Listing(197                source=self.source_id,198                external_id=ext_id,199                url=(post.get("permalink") or LOGEMENT_PAGE),200                title=f"{title} — {campus}" if campus and201                      campus.lower() not in title.lower() else title,202                address=address,203                sector=campus,          # campus = « secteur » du Montagnais204                city=city,205                unit_type=unit_type,206                price=price,207                price_label=price_label,208                availability=status,    # « Disponible »209                description=description,210                amenities=amenities,211                details=details,212                images=images,213                lat=float(lat) if lat else None,214                lng=float(lng) if lng else None,215            ))216        return listings217
Files main
Menu

Theme