SPB Git

Repository Public

denux.py 14.4 KB 361 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/denux.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/denux.py : connecteur Groupe Denux (groupedenux.com)91#   Portefeuille pancanadien (plateforme Rentsync / The Lift System).92#   Seules les villes québécoises sont interrogées (Montréal, Saint-Lambert,93#   Mascouche) — la Colombie-Britannique, l'Alberta et la France sont exclues94#   d'office. Découverte des immeubles via l'API JSON du site95#   (api.theliftsystem.com/v2/search, jeton public embarqué dans le JS du96#   site), puis parsing des fiches /residential/<slug> rendues serveur :97#   suites disponibles (div.suite[data-suite-id] avec type, prix, chambres,98#   date de disponibilité), commodités et galerie photos.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import html as htmllib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing108from .base import BaseConnector109110SITE = "https://www.groupedenux.com"111API = "https://api.theliftsystem.com/v2/search"112AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"      # jeton public (scripts/main.js du site)113CLIENT_ID = "654"114115# Villes québécoises desservies (id Lift System -> nom normalisé)116QC_CITIES = {117    "1863": "Montréal",118    "2789": "Saint-Lambert",119    "1741": "Mascouche",120}121122_GALLERY_RE = re.compile(123    r'https://assets\.rentsync\.com/groupe_denux/images/gallery/'124    r'[0-9]+/[^"\'\s\\)]+\.(?:jpg|jpeg|png|webp)', re.I)125_HALF_RE = re.compile(r"(\d)\s*(?:½|1/2|[.,]5)")126127# Nombre de chambres -> type d'unité (à défaut d'un « X.5 » dans le libellé)128_BED_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}129130131def _clean(txt: str) -> str:132    txt = htmllib.unescape(htmllib.unescape(txt or ""))133    txt = re.sub(r"<[^>]+>", " ", txt)134    return re.sub(r"\s+", " ", txt).strip()135136137class DenuxConnector(BaseConnector):138    source_id = "denux"139    request_delay = 0.6140    max_buildings = 40           # garde-fou de crawl141142    # -- API de recherche (backend officiel du site) ---------------------------143    def _search_city(self, city_id: str) -> list[dict]:144        params = {145            "locale": "fr",146            "client_id": CLIENT_ID,147            "auth_token": AUTH_TOKEN,148            "city_id": city_id,149            "geocode": "",150            "min_bed": "-1", "max_bed": "100",151            "min_bath": "-1", "max_bath": "10",152            "min_rate": "0", "max_rate": "100000",153            "property_types": "apartments, houses",154            "order": "min_rate ASC",155            "limit": "66", "offset": "0",156            "count": "false",157            "show_all_properties": "true",158        }159        data = self.get(API, params=params).json()160        return data if isinstance(data, list) else []161162    def fetch(self) -> list[Listing]:163        listings: list[Listing] = []164        buildings: list[dict] = []165        for city_id in QC_CITIES:166            try:167                buildings.extend(self._search_city(city_id))168            except Exception:169                continue170171        seen: set = set()172        for i, b in enumerate(buildings):173            if i >= self.max_buildings:174                break175            try:176                bid = b.get("id")177                if bid in seen:178                    continue179                seen.add(bid)180                addr = b.get("address") or {}181                # Garde-fou : Québec seulement (exclut C.-B., Alberta, France)182                if (addr.get("province_code") or "").upper() != "QC":183                    continue184                if int(b.get("availability_count") or 0) <= 0:185                    continue             # aucune unité disponible186                listings.extend(self._parse_building(b))187            except Exception:188                continue189        return listings190191    # -- fiche immeuble : suites rendues serveur --------------------------------192    def _parse_building(self, b: dict) -> list[Listing]:193        slug = (b.get("permalink") or "").rstrip("/").split("/")[-1]194        if not slug:195            return []196        url = f"{SITE}/residential/{slug}"197198        addr = b.get("address") or {}199        name = _clean(b.get("name") or slug)200        address = _clean(addr.get("address") or "")201        city = _clean(addr.get("city") or "")202        sector = _clean(addr.get("neighbourhood") or "")203        if sector.isupper():204            sector = sector.title()205        if sector.lower() in ("", city.lower(), "montreal", "montréal"):206            sector = ""207208        bdetails = b.get("details") or {}209        description = _clean(bdetails.get("overview") or "")[:600]210211        # Champs structurés de l'API Lift System (jamais devinés du texte)212        pets = None213        if isinstance(b.get("pet_friendly"), bool):214            pets = "oui" if b["pet_friendly"] else "non"215        details: dict = {}216        contact = b.get("contact") or {}217        cinfo = {}218        if _clean(contact.get("phone") or ""):219            cinfo["phone"] = _clean(contact["phone"])220        if _clean(contact.get("email") or ""):221            cinfo["email"] = _clean(contact["email"])222        if cinfo:223            details["contact"] = cinfo224        parking = b.get("parking") or {}225        if parking.get("indoor") or parking.get("outdoor"):226            details["parking"] = {227                "available": True,228                "type": "intérieur" if parking.get("indoor") else "extérieur",229            }230231        geo = b.get("geocode") or {}232        try:233            lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))234        except (TypeError, ValueError):235            lat = lng = None236237        html = self.get(url).text238        soup = BeautifulSoup(html, "html.parser")239240        # Commodités (suite + immeuble)241        amenities = [el.get_text(" ", strip=True)242                     for el in soup.select(".amenities .amenity-holder")]243        amenities = [a for a in dict.fromkeys(amenities) if a][:25]244245        # Galerie photos (dédupliquée par nom de fichier, tailles multiples)246        images: list[str] = []247        seen_files: set[str] = set()248        for u in _GALLERY_RE.findall(html):249            fname = u.rsplit("/", 1)[-1]250            if fname not in seen_files:251                seen_files.add(fname)252                images.append(u)253        images = images[:25]254255        # Détails par suite (ul.suite-info) indexés par data-suite-id256        info_by_id: dict[str, dict[str, str]] = {}257        photos_by_id: dict[str, list[str]] = {}258        for ul in soup.select("ul.suite-info[data-suite-id]"):259            sid = ul.get("data-suite-id") or ""260            fields: dict[str, str] = {}261            for li in ul.select("li.info-block"):262                lab = li.select_one(".label")263                val = li.select_one(".info")264                if not (lab and val):265                    continue266                label = lab.get_text(strip=True).lower()267                # Photos propres à la suite (liens « View » de la galerie)268                if "photo" in label:269                    urls = [a.get("href") or "" for a in val.select("a")]270                    urls = [u for u in dict.fromkeys(urls)271                            if u.startswith("http")]272                    if urls:273                        photos_by_id[sid] = urls[:25]274                    continue275                # Le champ « Availability » contient un lien + un modal de276                # formulaire : ne garder que le libellé du lien.277                link = val.select_one("a.open-suite-modal")278                text = (link.get_text(" ", strip=True) if link279                        else val.get_text(" ", strip=True))280                fields[label] = text[:80].strip()281            info_by_id[sid] = fields282283        results: list[Listing] = []284        for div in soup.select("div.suite[data-suite-id]"):285            sid = div.get("data-suite-id") or ""286            if not sid:287                continue288            type_el = div.select_one(".suite-type")289            rate_el = div.select_one(".suite-rate")290            suite_label = _clean(type_el.get_text(" ", strip=True)291                                 if type_el else "")292            # Nettoyage du libellé (certains contiennent dispo + prix)293            suite_label = re.sub(r"\s*[-–]?\s*Starting at\s*\$[\d,]+", "",294                                 suite_label, flags=re.I)295            suite_label = re.sub(r"\s*[-–]?\s*Available\s+(now|immediately)\b",296                                 "", suite_label, flags=re.I).strip(" -–,")297            info = info_by_id.get(sid, {})298299            # Type d'unité : « Grand 5.5, balcon... » -> 5½, sinon nb chambres300            unit_type = ""301            hm = _HALF_RE.search(suite_label)302            if hm:303                unit_type = f"{hm.group(1)}½"304            else:305                beds_txt = (info.get("bedrooms") or306                            (div.get("class") and307                             next((c.replace("beds_", "")308                                   for c in div.get("class")309                                   if c.startswith("beds_")), "")) or "")310                try:311                    unit_type = _BED_TYPE.get(int(beds_txt), "")312                except (ValueError, TypeError):313                    unit_type = ""314315            # Prix : « $1,320 » (à partir de)316            price = None317            price_label = ""318            if rate_el:319                raw = rate_el.get_text(" ", strip=True)320                digits = re.sub(r"[^\d.]", "", raw)321                if digits:322                    try:323                        price = float(digits)324                    except ValueError:325                        price = None326                    price_label = f"À partir de {raw}/mois"327            if price is not None and not (100 <= price <= 20000):328                price = None329330            availability = info.get("availability", "") or \331                _clean(b.get("availability_status_label") or "")332333            # Commodités de l'immeuble + salles de bain de la suite334            suite_amenities = list(amenities)335            baths = (info.get("bathrooms") or "").strip()336            if baths and re.match(r"^[\d.]+$", baths):337                suite_amenities.append(f"{baths} salle(s) de bain")338339            results.append(Listing(340                source=self.source_id,341                external_id=str(sid),342                url=url,343                title=f"{name} — {suite_label}" if suite_label else name,344                address=address,345                sector=sector,346                city=city or QC_CITIES.get(str(addr.get("city_id")), ""),347                unit_type=unit_type,348                price=price,349                price_label=price_label,350                availability=availability,351                pets=pets,352                description=description,353                amenities=suite_amenities,354                details={k: dict(v) if isinstance(v, dict) else v355                         for k, v in details.items()},356                images=photos_by_id.get(sid) or images,357                lat=lat,358                lng=lng,359            ))360        return results361
Files main
Menu

Theme