SPB Git

Repository Public

niddamour.py 15.3 KB 370 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/niddamour.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/niddamour.py : connecteur Nid d'Amour / Karen Cadet inc.91#   (niddamour.ca — Plateau, Verdun, Outremont, Rosemont, Ville-Marie,92#    Brossard...). Front WordPress + Angular sur la plateforme source.immo :93#   on lit la config publique (_configs.json) puis on interroge directement94#   l'API JSON api-v1.source.immo (liste + fiches avec toutes les photos).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import hashlib99import json100import re101102from ..schema import Listing103from .base import BaseConnector104105SITE = "https://niddamour.ca"106# la config source.immo (config_path) est présente sur la page d'accueil ;107# les pages /proprietes/ sont des routes Angular servies en HTTP 404108HOME_URL = f"{SITE}/"109API_ROOT = "https://api-v1.source.immo/api"110111# Régions administratives admissibles (Grand Montréal / CMM)112ALLOWED_REGIONS = {"montreal", "laval", "monteregie", "lanaudiere", "laurentides"}113114_BEDROOMS_TO_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}115116# mots-clés des champs structurés inclusions/exclusions -> clés Lou-Ka117_INCL_KEYS = [118    (re.compile(r"electricite|hydro"), "electricity"),119    (re.compile(r"chauffage"), "heating"),120    (re.compile(r"eau chaude"), "hot_water"),121    (re.compile(r"internet|wi-?fi"), "internet"),122    (re.compile(r"cable|television"), "cable"),123]124125126def _strip_accents_lower(s: str) -> str:127    import unicodedata128    return "".join(c for c in unicodedata.normalize("NFD", (s or "").lower())129                   if unicodedata.category(c) != "Mn")130131132class _CapAtteint(Exception):133    """Plafond de requêtes détail atteint pour cette synchronisation."""134135136class NiddamourConnector(BaseConnector):137    source_id = "niddamour"138    request_delay = 0.6139    max_real_details = 150   # vraies requêtes détail par sync (cache exclu)140141    # -- helpers ---------------------------------------------------------------142    def _api(self, path: str, cfg: dict) -> dict:143        headers = {144            "x-si-account": cfg["account_id"],145            "x-si-api": cfg["api_key"],146            "x-si-appId": cfg["app_id"],147            "x-si-appVersion": cfg.get("app_version", ""),148            "Origin": SITE,149            "Referer": SITE + "/",150        }151        return self.get(f"{API_ROOT}/{path}", headers=headers).json()152153    def _load_config(self) -> dict | None:154        """Extrait l'URL du _configs.json de source.immo depuis le site."""155        try:156            page = self.get(HOME_URL).text157        except Exception:158            return None159        m = re.search(r'config_path\s*:\s*"([^"]+)"', page)160        if not m:161            return None162        cfg_url = m.group(1).replace("\\/", "/")163        if cfg_url.startswith("//"):164            cfg_url = "https:" + cfg_url165        try:166            return self.get(cfg_url).json()167        except Exception:168            return None169170    # -- fiche détaillée (via cache BD self.detail) ----------------------------171    def _unit_detail(self, ref: str, key: str, view: str, cfg: dict) -> dict:172        """Fiche source.immo : photos, adresse (+ code postal), description,173        addendum, inclusions/exclusions structurées, étage, sdb."""174        def _fetch() -> dict:175            if self._real_details >= self.max_real_details:176                raise _CapAtteint()177            self._real_details += 1178            det = self._api(179                f"listing/view/{view}/fr/items/ref_number/{ref}", cfg)180            out: dict = {}181            out["images"] = [ph.get("url") for ph in (det.get("photos") or [])182                             if isinstance(ph, dict) and ph.get("url")]183            out["description"] = re.sub(184                r"\s+", " ", det.get("description") or "").strip()185186            adr = (det.get("location") or {}).get("address") or {}187            parts = [adr.get("street_number"), adr.get("street_name")]188            address = " ".join(x for x in parts if x)189            if adr.get("door") and address:190                address += f", app. {adr['door']}"191            if adr.get("postal_code") and address:192                address += f", {adr['postal_code']}"193            out["address"] = address194195            out["inclusions_txt"] = det.get("inclusions") or ""196            out["exclusions_txt"] = det.get("exclusions") or ""197198            # étage de l'unité principale + salles de bain199            for u in det.get("units") or []:200                if (u.get("category_code") == "MAIN"201                        and isinstance(u.get("level"), int)202                        and 0 < u["level"] <= 60):203                    out["floor"] = u["level"]204            main = next((u for u in det.get("units") or []205                         if u.get("category_code") == "MAIN"), {})206            if isinstance(main.get("bathroom_count"), int) \207                    and main["bathroom_count"] > 0:208                out["bathrooms"] = main["bathroom_count"]209210            # addendum HTML (détails de l'appartement, services à proximité)211            add = det.get("addendum") or ""212            add = re.sub(r"<br\s*/?>", " — ", add)213            add = re.sub(r"<[^>]+>", " ", add)214            add = re.sub(r"&nbsp;?", " ", add)215            out["addendum"] = re.sub(r"\s+", " ", add).strip()216            return out217218        try:219            return self.detail(ref, key, _fetch)220        except Exception:221            return {}222223    # -- contrat ---------------------------------------------------------------224    def fetch(self) -> list[Listing]:225        self._real_details = 0226        listings: list[Listing] = []227        cfg = self._load_config()228        if not cfg or not cfg.get("api_key"):229            return listings230231        view = cfg.get("default_view") or ""232        if view.startswith("{"):233            try:234                view = json.loads(view).get("id", "")235            except ValueError:236                return listings237        if not view:238            return listings239240        # Dictionnaires (codes ville / sous-catégorie / région -> libellés)241        try:242            meta = self._api(f"view/{view}/fr", cfg)243        except Exception:244            return listings245        dico = meta.get("dictionary") or {}246        cities = dico.get("city") or {}247        subcats = dico.get("listing_subcategory") or {}248        regions = dico.get("region") or {}249250        try:251            items = (self._api(f"listing/view/{view}/fr/items", cfg)252                     .get("items") or [])253        except Exception:254            return listings255256        for it in items:257            try:258                ref = it.get("ref_number") or ""259                if not ref:260                    continue261                # disponibles à louer, résidentiel seulement262                if it.get("status_code") != "AVAILABLE":263                    continue264                if not it.get("for_rent_flag"):265                    continue266                if (it.get("category_code") or "") != "RESIDENTIAL":267                    continue268                subcap = ((subcats.get(it.get("subcategory_code") or "") or {})269                          .get("caption") or "")270                if re.search(r"stationnement|commercial|bureau|local|terrain|"271                             r"industriel|garage|entrep[oô]t", subcap, re.I):272                    continue273274                loc = it.get("location") or {}275                region_cap = ((regions.get(loc.get("region_code") or "") or {})276                              .get("caption") or "")277                if region_cap and \278                        _strip_accents_lower(region_cap) not in ALLOWED_REGIONS:279                    continue  # hors Grand Montréal280281                # 'Montréal (Le Plateau-Mont-Royal)' -> ville + quartier282                city_cap = ((cities.get(loc.get("city_code") or "") or {})283                            .get("caption") or "")284                mcity = re.match(r"^([^(]+?)\s*(?:\(([^)]+)\))?$", city_cap)285                city = (mcity.group(1).strip() if mcity else city_cap) or "Montréal"286                sector = (mcity.group(2) or "").strip() if mcity else ""287288                price = ((it.get("price") or {}).get("rent") or {}).get("amount")289                price = float(price) if isinstance(price, (int, float)) else None290                price_label = (f"{price:,.0f}".replace(",", " ") + " $ / mois"291                               if price else "")292293                bedrooms = (it.get("main_unit") or {}).get("bedroom_count")294                if re.search(r"maison", subcap, re.I):295                    unit_type = "Maison"296                elif re.search(r"studio|loft", subcap, re.I) and not bedrooms:297                    unit_type = "Studio"298                else:299                    unit_type = _BEDROOMS_TO_TYPE.get(300                        bedrooms, f"{bedrooms} chambres" if bedrooms else "")301302                # Fiche détaillée (cache BD, clé = hash de l'item de liste)303                key = hashlib.sha1(json.dumps(304                    it, sort_keys=True, ensure_ascii=False)305                    .encode("utf-8")).hexdigest()[:16]306                det = self._unit_detail(ref, key, view, cfg)307308                address = det.get("address") or ""309                description = det.get("description") or ""310                if det.get("addendum"):311                    description = (f"{description} — {det['addendum']}"312                                   if description else det["addendum"])313                if det.get("bathrooms"):314                    description = " — ".join(315                        x for x in [description,316                                    f"{det['bathrooms']} sdb"] if x)317                description = description[:600]318319                # inclusions positives -> amenities brutes (affichage)320                amenities = [re.sub(r"^[-–•\s]+", "", ln).strip(" ;.")321                             for ln in (det.get("inclusions_txt") or "")322                             .splitlines() if ln.strip(" -–•;.")]323324                # inclusions/exclusions structurées -> details.inclusions325                # (les exclusions priment : « Électricité, chauffage et eau326                #  chaude » non inclus ne doit pas devenir positif)327                details: dict = {}328                incl: dict = {}329                incl_key = _strip_accents_lower(det.get("inclusions_txt") or "")330                excl_key = _strip_accents_lower(det.get("exclusions_txt") or "")331                for rx, cle in _INCL_KEYS:332                    if rx.search(incl_key):333                        incl[cle] = True334                for rx, cle in _INCL_KEYS:335                    if rx.search(excl_key):336                        incl[cle] = False337                if incl:338                    details["inclusions"] = incl339                if det.get("floor"):340                    details["floor"] = det["floor"]341342                images = det.get("images") or []343                if not images and it.get("photo_url"):344                    images = [it["photo_url"]]345346                title = address or f"{unit_type or 'Logement'} — {sector or city}"347                listings.append(Listing(348                    source=self.source_id,349                    external_id=ref,350                    url=f"{SITE}/propriete/{ref.lower()}/",351                    title=title,352                    address=address,353                    sector=sector,354                    city=city,355                    unit_type=unit_type,356                    price=price,357                    price_label=price_label,358                    availability="Disponible",359                    description=description,360                    amenities=[a for a in amenities if a][:15],361                    details=details,362                    images=list(dict.fromkeys(images))[:25],363                    lat=loc.get("latitude"),364                    lng=loc.get("longitude"),365                ))366            except Exception:367                continue368369        return listings370
Files main
Menu

Theme