SPB Git

Repository Public

immeubles_dcl.py 13.2 KB 328 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immeubles_dcl.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/immeubles_dcl.py : connecteur Les Immeubles DCL91#   (lesimmeublesdcl.com — Rouyn-Noranda, Val-d'Or, Malartic ; volet logements92#   abordables). Site Laravel + **FleetCart** (catalogue e-commerce détourné93#   en vitrine locative, Vue.js côté client) : la page /logements-a-louer est94#   vide côté serveur, mais son API interne répond en JSON structuré —95#   POST /logements-a-louer (X-CSRF-TOKEN lu dans `window.FleetCart`, session96#   Laravel du GET initial) -> products.data : adresse, ville, code postal,97#   **GPS (lat_lng)**, prix, catégorie (typologie « 1 ½ »… -> unit_type) et98#   attributs (Ameublement -> meublé, Animaux -> pets, Pièces, Chambres,99#   Salle de bain, Commodités, Inclusions, Secteurs, Disponibilité). Fiche100#   /logements-a-louer/<slug> (via cache BD) : description et galerie complète101#   (images S3 `img.popup-img`). Les logements loués vivent dans un catalogue102#   séparé (/logements-loues) : jamais mélangés. robots.txt ouvert.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import hashlib107import re108import time109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type113from .base import BaseConnector114115BASE = "https://www.lesimmeublesdcl.com"116LIST_URL = f"{BASE}/logements-a-louer"117118_CSRF_RE = re.compile(r"csrfToken:\s*'([^']+)'")119120121def _attr_values(product: dict) -> dict[str, list[str]]:122    """Attributs FleetCart du produit -> {nom: [valeurs]}."""123    out: dict[str, list[str]] = {}124    for attr in product.get("attributes") or []:125        name = (attr.get("name") or "").strip()126        vals = [v.get("value", "").strip()127                for v in attr.get("values") or [] if v.get("value")]128        if name and vals:129            out[name] = vals130    return out131132133class ImmeublesDCLConnector(BaseConnector):134    source_id = "immeubles_dcl"135    request_delay = 0.6136    max_details = 25     # garde-fou fiches détail (vraies requêtes par sync)137    max_pages = 10       # garde-fou pagination API138139    def _post_json(self, url: str, payload: dict, token: str):140        """POST JSON avec le même throttling poli que get()."""141        wait = self.request_delay - (time.time() - self._last_request)142        if wait > 0:143            time.sleep(wait)144        resp = self.session.post(145            url, json=payload, timeout=self.timeout,146            headers={"X-CSRF-TOKEN": token,147                     "X-Requested-With": "XMLHttpRequest",148                     "Accept": "application/json"})149        self._last_request = time.time()150        resp.raise_for_status()151        return resp152153    def fetch(self) -> list[Listing]:154        # 1) GET la page : cookie de session Laravel + jeton CSRF (window.FleetCart)155        html = self.get(LIST_URL).text156        m = _CSRF_RE.search(html)157        if not m:158            raise RuntimeError("csrfToken introuvable sur /logements-a-louer")159        token = m.group(1)160161        # 2) API products.index (JSON), paginée via last_page162        self._fetched = 0163        listings: dict[str, Listing] = {}164        page = 1165        while page <= self.max_pages:166            payload = {"query": "", "fromPrice": 0, "toPrice": 100000,167                       "perPage": 50, "page": page, "attribute": {},168                       "sort": "latest"}169            data = self._post_json(LIST_URL, payload, token).json()170            products = (data.get("products") or {})171            for prod in products.get("data") or []:172                try:173                    self._parse_product(prod, listings)174                except Exception:175                    continue176            if page >= int(products.get("last_page") or 1):177                break178            page += 1179        return list(listings.values())180181    # -- produit FleetCart (JSON) --------------------------------------------------------182    def _parse_product(self, prod: dict, listings: dict[str, Listing]) -> None:183        ext_id = str(prod.get("id") or "")184        slug = prod.get("slug") or ""185        if not ext_id or not slug or ext_id in listings:186            return187        url = f"{LIST_URL}/{slug}"188189        name = (prod.get("name") or "").strip()190        address = (prod.get("address") or "").strip()191        city = (prod.get("city") or "").strip()192        zip_code = (prod.get("zip") or "").strip()193        full_address = ", ".join(p for p in (address, city, zip_code) if p)194195        # prix structuré (selling_price) + libellé du site (« 900 $CA »)196        price = None197        selling = prod.get("selling_price") or {}198        cur = selling.get("inCurrentCurrency") or {}199        if isinstance(cur.get("amount"), (int, float)):200            price = float(cur["amount"])201        # « 1 425 $CA » : espaces (fines) insécables -> espace simple202        price_label = re.sub(r"\s+", " ",203                             prod.get("formatted_price") or "").strip()204205        # typologie = catégorie du catalogue (« 1 ½ », « 4 ½ »…)206        unit_type = ""207        for cat in prod.get("categories") or []:208            cname = (cat.get("name") or "").strip()209            if re.match(r"^\d\s*½", cname):210                unit_type = normalize_unit_type(cname.replace("½", "1/2"))211                break212213        attrs = _attr_values(prod)214        availability = ", ".join(attrs.get("Disponibilité", []))215        sector = ", ".join(attrs.get("Secteurs", []))216217        # animaux : champ structuré du site (prudence : conditions si permis)218        pets = None219        pets_raw = " / ".join(attrs.get("Animaux", []))220        if pets_raw:221            if re.search(r"aucun|pas accept|non", pets_raw, re.I):222                pets = "non"223            elif re.search(r"accept|autoris", pets_raw, re.I):224                pets = "conditions"225226        furnished = None227        furn_raw = " ".join(attrs.get("Ameublement", []))228        if re.search(r"^non\s*meubl", furn_raw.strip(), re.I):229            furnished = False230        elif re.search(r"meubl", furn_raw, re.I):231            furnished = True232233        amenities: list[str] = []234        if attrs.get("Pièces"):235            amenities.append(f"{attrs['Pièces'][0]} pièce(s)")236        if attrs.get("Chambres à coucher"):237            amenities.append(f"{attrs['Chambres à coucher'][0]} chambre(s)")238        if attrs.get("Salle de bain"):239            amenities.append(f"{attrs['Salle de bain'][0]} salle(s) de bain")240        for grp in ("Commodités", "Commodités de l'immeuble"):241            amenities.extend(attrs.get(grp, []))242        if attrs.get("Inclusions"):243            amenities.append("Inclus : " + ", ".join(attrs["Inclusions"]))244245        # GPS structuré (lat_lng) — validé ensuite par finalize()246        lat = lng = None247        latlng = prod.get("lat_lng") or []248        if isinstance(latlng, list) and len(latlng) == 2:249            try:250                lat, lng = float(latlng[0]), float(latlng[1])251            except (TypeError, ValueError):252                lat = lng = None253254        images = [m_.get("path", "") for m_ in prod.get("media") or []255                  if isinstance(m_, dict) and m_.get("path", "").startswith("http")]256257        lst = Listing(258            source=self.source_id,259            external_id=ext_id,260            url=url,261            title=name,262            address=full_address,263            sector=sector,264            city=city,265            unit_type=unit_type,266            price=price,267            price_label=price_label,268            availability=availability,269            pets=pets,270            furnished=furnished,271            amenities=list(dict.fromkeys(amenities))[:25],272            images=images,273            lat=lat,274            lng=lng,275        )276277        key = hashlib.sha1(278            f"{name}|{price_label}|{availability}|{sector}"279            .encode("utf-8")).hexdigest()280        try:281            payload = self.detail(ext_id, key,282                                  lambda u=url: self._fetch_detail(u))283            self._apply_detail(lst, payload)284        except Exception:285            pass286        listings[ext_id] = lst287288    # -- fiche détail (/logements-a-louer/<slug>) ----------------------------------------289    def _fetch_detail(self, url: str) -> dict:290        """Description libre et galerie complète (images S3 du carrousel)."""291        if self._fetched >= self.max_details:292            raise RuntimeError("budget de fiches détail atteint")293        self._fetched += 1294        html = self.get(url).text295        soup = BeautifulSoup(html, "html.parser")296        out: dict = {}297298        # bloc « Description » : titre (h5) suivi du texte libre299        for h in soup.find_all(["h2", "h3", "h4", "h5"]):300            if h.get_text(strip=True).lower() == "description":301                parts = []302                for sib in h.find_next_siblings():303                    if sib.name in ("h2", "h3", "h4"):304                        break305                    parts.append(sib.get_text("\n", strip=True))306                txt = "\n".join(p for p in parts if p)307                if txt:308                    out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]309                break310311        # galerie : liens pleine taille du carrousel (a.popup-img -> S3)312        images: list[str] = []313        for a in soup.select("a.popup-img[href]"):314            u = a["href"].strip()315            if u.startswith("http") and u not in images:316                images.append(u)317        out["images"] = images[:25]318        return out319320    def _apply_detail(self, lst: Listing, d: dict) -> None:321        """Reporte le payload (frais ou en cache) sur l'annonce."""322        if not d:323            return324        if d.get("description"):325            lst.description = d["description"]326        if d.get("images") and len(d["images"]) > len(lst.images):327            lst.images = d["images"]328
Files main
Menu

Theme