SPB Git

Repository Public

org_dupuis.py 12.2 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/org_dupuis.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/org_dupuis.py : connecteur Organisation Dupuis91#   (organisationdupuis.ca — promoteur/gestionnaire de Granby ; portail de92#    location locationorganisationdupuis.bstk.io sur la plateforme Building93#    Stack, même famille que les portails des connecteurs summum.py /94#    urban_services.py / edifia.py) :95#     - /Listing/Listings embarque `var units = [...]` (une entrée par96#       appartement annoncé : ApartmentId stable, prix, pi², chambres, sdb,97#       adresse complète avec GPS, contact de location, photo) ;98#     - les pages immeuble /b/<id> donnent la date de disponibilité par unité99#       et les commodités de l'immeuble (une requête par immeuble, via le100#       cache self.detail, plafonnée).101#   Parc étendu au-delà de Granby/Bromont/Waterloo : Sherbrooke, Terrebonne,102#   L'Assomption, Bécancour, Sorel-Tracy, Trois-Rivières, Victoriaville…103#   ⚠️ Le portail liste aussi Edmundston (Nouveau-Brunswick) : tout ce qui104#   n'est pas Province == QC est exclu.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import hashlib109import html as _html110import json111import re112113from bs4 import BeautifulSoup114115from ..schema import Listing116from .base import BaseConnector117118BASE = "https://locationorganisationdupuis.bstk.io"119LIST_URL = f"{BASE}/Listing/Listings"120121_WS_RE = re.compile(r"\s+")122123124def _extract_json(html: str, marker: str):125    """Décode la structure JSON qui suit `marker` dans un script inline."""126    i = html.find(marker)127    if i < 0:128        return None129    try:130        data, _ = json.JSONDecoder().raw_decode(html[i + len(marker):].lstrip())131    except Exception:132        return None133    return data134135136def _sqft(raw) -> float | None:137    try:138        v = float(str(raw).strip().replace(" ", "").replace(",", "."))139    except (TypeError, ValueError):140        return None141    return v if 80 <= v <= 20000 else None142143144class OrgDupuisConnector(BaseConnector):145    source_id = "org_dupuis"146    request_delay = 0.6147    max_buildings = 60           # garde-fou pages immeuble (26 au 2026-08)148    max_images = 12149150    # -- page immeuble /b/<id> : dates de disponibilité + commodités -----------151    def _building_page(self, pub: str, key: str) -> dict:152        """{ 'dates': {unité: dispo}, 'amenities': [...], 'images': [...] }."""153        def _fetch() -> dict:154            html = self.get(f"{BASE}/b/{pub}").text155            soup = BeautifulSoup(html, "html.parser")156            dates: dict[str, str] = {}157            for a in soup.select("ul.wpb-tabs-menu a.apartment-view-potential"):158                spans = [s.get_text(" ", strip=True) for s in a.find_all("span")]159                if len(spans) >= 6 and spans[0]:160                    dates[spans[0]] = spans[5]        # Unité -> Disponible161            amenities: list[str] = []162            for li in soup.select(".facilities ul li label"):163                t = _WS_RE.sub(" ", li.get_text(" ", strip=True))164                if 3 <= len(t) <= 90 and t not in amenities:165                    amenities.append(t)166            imgs = list(dict.fromkeys(re.findall(167                r"https://wfiles\.buildingstack\.com/resources/image/\w+",168                html)))169            return {"dates": dates, "amenities": amenities[:20],170                    "images": imgs[:10]}171172        try:173            return self.detail(pub, key, _fetch)174        except Exception:175            return {}176177    # -- fetch ------------------------------------------------------------------178    def fetch(self) -> list[Listing]:179        html = self.get(LIST_URL).text180        units = _extract_json(html, "var units =") or []181182        # regrouper par immeuble (parc québécois, résidentiel seulement)183        by_pub: dict[str, list[dict]] = {}184        for u in units:185            addr = u.get("Address") or {}186            prov = ((addr.get("Province") or {}).get("ProvinceCode") or "")187            if prov.upper() != "QC":188                continue                  # Edmundston (N.-B.) : exclu189            if not (u.get("Apartment") or {}).get("IsResidential", True):190                continue                  # commercial / stationnement191            pub = str((u.get("Building") or {})192                      .get("PublicListBuildingName") or "")193            if pub:194                by_pub.setdefault(pub, []).append(u)195196        # une page immeuble par immeuble (clé de cache = contenu des unités)197        bldg_info: dict[str, dict] = {}198        for pub, us in sorted(by_pub.items())[: self.max_buildings]:199            key = hashlib.sha1(json.dumps(200                sorted((str(x.get("ApartmentId")),201                        str((x.get("Apartment") or {}).get("Price")))202                       for x in us)).encode("utf-8")).hexdigest()[:16]203            bldg_info[pub] = self._building_page(pub, key)204205        listings: list[Listing] = []206        for pub, us in by_pub.items():207            info = bldg_info.get(pub) or {}208            for u in us:209                try:210                    lst = self._listing(u, pub, info)211                    if lst:212                        listings.append(lst)213                except Exception:214                    continue              # une unité ne bloque pas le reste215216        # dédup par external_id (sécurité)217        uniq: dict[str, Listing] = {}218        for lst in listings:219            uniq.setdefault(lst.external_id, lst)220        return list(uniq.values())221222    # -- une annonce par unité ----------------------------------------------------223    def _listing(self, u: dict, pub: str, info: dict) -> Listing | None:224        apt = u.get("Apartment") or {}225        adr = u.get("Address") or {}226        bld = u.get("Building") or {}227        ext_id = str(u.get("ApartmentId") or "")228        if not ext_id:229            return None230        num = str(apt.get("UnitName") or "").strip()231        bname = _WS_RE.sub(" ", _html.unescape(232            str(u.get("BuildingName") or ""))).strip()233234        # convention Building Stack (comme edifia) : 0 chambre = studio235        beds = apt.get("NumberOfBedrooms") or 0236        baths = apt.get("NumberOfBathrooms") or 0237        unit_type = "Studio" if not beds else f"{int(beds) + 2}½"238239        dispo = (info.get("dates") or {}).get(num, "")240        if not dispo:241            availability = "Disponible"242        elif re.search(r"\d", dispo):     # « sept. 01, 2026 »243            availability = f"Libre {dispo}"244        else:                             # « Disponible dès maintenant! »245            availability = dispo246247        area = _sqft(apt.get("Area"))248        desc = " — ".join(x for x in [249            f"{area:g} pi²" if area else "",250            f"{beds} chambre(s)" if beds else "",251            f"{baths} salle(s) de bain" if baths else ""] if x)252253        details: dict = {"bedrooms": int(beds), "bathrooms": int(baths)}254        if isinstance(u.get("ParkingsIsAvailable"), bool):255            details["parking"] = {"available": u["ParkingsIsAvailable"]}256        if isinstance(u.get("StoragesIsAvailable"), bool):257            details["storage"] = u["StoragesIsAvailable"]258        contacts = bld.get("ListingEmployeesContacts") or []259        if contacts:260            c = contacts[0]261            contact = {k: v for k, v in [262                ("name", c.get("FullName")),263                ("phone", c.get("FormattedPhoneNumber")),264                ("email", c.get("Email"))] if v}265            if contact:266                details["contact"] = contact267268        # photo de l'unité (aperçu liste), puis photos de l'immeuble269        imgs: list[str] = []270        prev = str(u.get("PreviewUrl") or "")271        if prev.startswith("http"):272            imgs.append(prev)273        imgs += [x for x in (info.get("images") or []) if x not in imgs]274275        try:276            lat, lng = float(adr.get("Latitude")), float(adr.get("Longitude"))277        except (TypeError, ValueError):278            lat = lng = None279280        burl = str(u.get("BuildingUrl") or "")281        url = BASE + burl if burl.startswith("/") else f"{BASE}/b/{pub}"282        return Listing(283            source=self.source_id,284            external_id=ext_id,285            url=url,286            title=(f"{bname} — Unité {num}" if num else bname),287            address=_html.unescape(str(adr.get("Full") or "")),288            sector="",289            city=_html.unescape(str(adr.get("City") or "")),290            unit_type=unit_type,291            price=float(apt.get("Price") or 0) or None,292            price_label=str(apt.get("PriceFormatted") or ""),293            availability=availability,294            area_sqft=area,295            description=desc[:600],296            amenities=list(info.get("amenities") or []),297            details=details,298            images=imgs[: self.max_images],299            lat=lat,300            lng=lng,301        )302
Files main
Menu

Theme