SPB Git

Repository Public

groupe_dallaire.py 18.9 KB 450 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_dallaire.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-1814#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/groupe_dallaire.py : connecteur Groupe Dallaire — Faubourg du91#   Moulin (faubourgdumoulin.ca). Complexes Alizé, Noroît (I-II), Sirocco,92#   Sonora, Zéphyr (I-II) — rue Lionel-Audet, Québec (Beauport).93#   La page /disponibilite charge les unités via JetEngine (admin-ajax.php) :94#   on rejoue l'appel `get_listing` (lazy-load) puis la pagination95#   `jet_smart_filters` pour récupérer toutes les unités disponibles96#   (numéro, étage, prix, date de disponibilité, plan). Les fiches d'unité97#   (via cache BD) ajoutent type d'unité, superficie nette (« Pieds carrés »)98#   et inclusions réelles (« Incluant »).99#   2026-08-18 : le pare-feu du site bloque l'IP du serveur Lou-Ka (timeout TCP100#   sur TOUT le domaine, même la page d'accueil — vérifié : OK depuis une autre101#   IP). On tente d'abord la voie directe avec un timeout court (8 s), puis on102#   bascule automatiquement sur Scrapfly en proxy simple (asp=False,103#   render_js=False — 1 crédit/appel) pour rejouer les mêmes requêtes.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import html as htmllib109import json110import re111import time112from urllib.parse import urlencode113114import requests115from bs4 import BeautifulSoup116117from ..schema import Listing, normalize_unit_type, parse_price118from .base import BaseConnector119120BASE = "https://faubourgdumoulin.ca"121AJAX = f"{BASE}/wp-admin/admin-ajax.php"122DISPO_URL = f"{BASE}/disponibilite/"123SECTOR = "Beauport"124CITY = "Québec"125ADDRESS = "rue Lionel-Audet, Québec (Faubourg du Moulin)"126127COMPLEXES = {128    "alize": "Alizé", "alize-2": "Alizé (Phase II)",129    "noroit": "Noroît", "noroit-2": "Noroît II",130    "sirocco": "Sirocco", "sonora": "Sonora",131    "zephyr": "Zéphyr", "zephyr-2": "Zéphyr II",132}133134# paramètres du widget « dispo » de la page /disponibilite135PAGE_SETTINGS = {136    "page_settings[post_id]": "105",137    "page_settings[queried_id]": "105|WP_Post",138    "page_settings[element_id]": "cb310a3",139    "page_settings[page]": "1",140    "listing_type": "elementor",141    "isEditMode": "false",142}143144145def _flatten(prefix: str, obj, out: dict) -> None:146    """Aplati un dict/list en champs de formulaire PHP (a[b][0]=x)."""147    if isinstance(obj, dict):148        for k, v in obj.items():149            _flatten(f"{prefix}[{k}]", v, out)150    elif isinstance(obj, list):151        for i, v in enumerate(obj):152            _flatten(f"{prefix}[{i}]", v, out)153    elif isinstance(obj, bool):154        out[prefix] = "true" if obj else "false"155    else:156        out[prefix] = "" if obj is None else str(obj)157158159class GroupeDallaireConnector(BaseConnector):160    source_id = "groupe_dallaire"161    request_delay = 0.6162    timeout = 8               # IP bloquée par le WAF (timeout TCP) : échouer vite163    max_pages = 25            # garde-fou pagination164    max_details = 150         # garde-fou fiches d'unité (vraies requêtes)165    _proxied = False          # bascule Scrapfly (proxy simple) après 1 timeout166167    # -- POST throttlé ---------------------------------------------------168    def _post(self, url: str, data: dict):169        wait = self.request_delay - (time.time() - self._last_request)170        if wait > 0:171            time.sleep(wait)172        resp = self.session.post(url, data=data, timeout=self.timeout)173        self._last_request = time.time()174        resp.raise_for_status()175        return resp176177    # -- transport avec repli proxy (IP du serveur bloquée par le WAF) ----178    _asp = False              # escalade ASP (résidentiel) après un échec amont179180    def _proxy(self, url: str, method: str = "GET",181               body: str | None = None) -> str:182        """Proxy Scrapfly avec escalade : proxy simple (1 crédit) d'abord ;183        le WAF coupe les rafales (ERR::SCRAPE::UPSTREAM_WEBSITE_ERROR dès la184        2e requête rapprochée — vérifié 2026-08-18), on escalade alors en ASP185        résidentiel (fiable, mais ~325 crédits l'appel de ~1 Mo) pour le186        reste de la passe."""187        headers = ({"Content-Type": "application/x-www-form-urlencoded"}188                   if method == "POST" else None)189        last = 0190        for attempt in range(4):191            if attempt:192                time.sleep(5 * attempt)193            res = self.scrapfly(url, render_js=False, asp=self._asp,194                                method=method, body=body, headers=headers)195            last = res.get("status_code") or 0196            content = res.get("content") or ""197            if 200 <= last < 400 and content:198                return content199            self._asp = True      # erreur amont/WAF : escalade et retente200        raise RuntimeError(f"proxy Scrapfly : HTTP {last} ({url})")201202    def _post_json(self, data: dict) -> dict:203        """POST admin-ajax : direct d'abord, proxy Scrapfly simple en repli."""204        if not self._proxied:205            try:206                return self._post(AJAX, data).json()207            except (requests.ConnectionError, requests.Timeout):208                self._proxied = True    # IP bloquée : proxy pour toute la passe209        return json.loads(self._proxy(AJAX, method="POST", body=urlencode(data)))210211    def _get_html(self, url: str) -> str:212        """GET fiche d'unité : direct d'abord, proxy Scrapfly simple en repli."""213        if not self._proxied:214            try:215                return self.get(url).text216            except (requests.ConnectionError, requests.Timeout):217                self._proxied = True218        return self._proxy(url)219220    # ---------------------------------------------------------------------221    def fetch(self) -> list[Listing]:222        # 1) Premier appel lazy-load : items page 1 + query/widget_settings223        first = self._post_json({224            "action": "jet_engine_ajax",225            "handler": "get_listing",226            **PAGE_SETTINGS,227        })228        html1 = (first.get("data") or {}).get("html", "")229230        nav = None231        m = re.search(r'data-nav="([^"]*)"', html1)232        if m:233            try:234                nav = json.loads(htmllib.unescape(m.group(1)))235            except Exception:236                nav = None237238        listings: dict[str, Listing] = {}239        for lst in self._parse_items(html1):240            listings.setdefault(lst.external_id, lst)241242        # 2) Pagination via jet_smart_filters (si le data-nav est disponible)243        if nav and nav.get("query") and nav.get("widget_settings"):244            page = 2245            while page <= self.max_pages:246                data = {247                    "action": "jet_smart_filters",248                    "provider": "jet-engine/dispo",249                    "paged": str(page),250                }251                _flatten("defaults", nav["query"], data)252                _flatten("settings", nav["widget_settings"], data)253                try:254                    resp = self._post_json(data)255                except Exception:256                    break257                content = resp.get("content") or ""258                new = 0259                for lst in self._parse_items(content):260                    if lst.external_id not in listings:261                        listings[lst.external_id] = lst262                        new += 1263                pag = resp.get("pagination") or {}264                max_pages = int(pag.get("max_num_pages") or 0)265                if new == 0 or (max_pages and page >= max_pages):266                    break267                page += 1268269        # 3) Fiche de l'unité (cache BD) : type d'unité (« 3½ TYPE D'UNITÉ »),270        #    superficie nette (« Pieds carrés »), inclusions réelles271        #    (« Incluant ») et plans (unité + niveau)272        self._fetched = 0273        for lst in listings.values():274            card_key = hashlib.sha1(275                f"{lst.title}|{lst.price_label}|{lst.availability}"276                .encode("utf-8")).hexdigest()277            try:278                payload = self.detail(lst.external_id, card_key,279                                      lambda u=lst.url: self._fetch_detail(u))280            except Exception:281                continue282            self._apply_detail(lst, payload)283284        return list(listings.values())285286    # ---------------------------------------------------------------------287    def _fetch_detail(self, url: str) -> dict:288        """Fiche d'unité : type, superficie nette, inclusions, plans.289        Retour JSON-sérialisable (cache BD)."""290        if self._fetched >= self.max_details:291            raise RuntimeError("budget de fiches d'unité atteint")292        self._fetched += 1293        dhtml = self._get_html(url)294        out: dict = {}295296        dtext = re.sub(r"<script.*?</script>", "", dhtml, flags=re.S)297        dtext = re.sub(r"<style.*?</style>", "", dtext, flags=re.S)298        dtext = re.sub(r"<[^>]+>", "\n", dtext)299        tm = re.search(r"(\d\s*½\s*\+?|Studio)\s*\n+\s*TYPE D['’]UNITÉ", dtext)300        if tm:301            out["unit_type"] = tm.group(1)302        sm = re.search(r"(\d{3,4})\s*\n+\s*Pieds carrés", dtext)303        if sm:304            out["area_sqft"] = float(sm.group(1))   # champ « Pieds carrés »305306        # Inclusions réelles (« Incluant » -> répéteur JetEngine)307        dsoup = BeautifulSoup(dhtml, "html.parser")308        amen = [sp.get_text(" ", strip=True)309                for sp in dsoup.select(".jet-listing-dynamic-repeater__item span")]310        out["amenities"] = [a for a in dict.fromkeys(amen) if a][:15]311312        # Plans : plan de l'unité (jpg) + plan du niveau (NIVEAU_x.png)313        plans = []314        for u in dict.fromkeys(re.findall(315                r"https://faubourgdumoulin\.ca/wp-content/uploads/"316                r"[^\"'\s\\]+\.(?:jpe?g|webp|png)", dhtml, re.I)):317            if re.search(r"logo|_rgb_|descripteur|favicon|cropped-|dalcon|"318                         r"alpha-|-\d+x\d+\.", u, re.I):319                continue320            if u.lower().endswith(".png") and "niveau" not in u.lower():321                continue322            plans.append(u)323        out["images"] = plans[:10]324        return out325326    def _apply_detail(self, lst: Listing, d: dict) -> None:327        """Reporte le payload (frais/cache) sur l'annonce."""328        if not d:329            return330        if d.get("unit_type") and not lst.unit_type:331            lst.unit_type = normalize_unit_type(d["unit_type"])332            if lst.unit_type and "½" not in lst.title \333                    and "Studio" not in lst.title:334                lst.title += f" ({lst.unit_type})"335        if d.get("area_sqft"):336            lst.area_sqft = d["area_sqft"]337        if d.get("amenities"):338            # inclusions réelles de la fiche (remplacent le repli générique)339            extra = [a for a in lst.amenities if a == "En promotion"]340            lst.amenities = d["amenities"] + extra341        if d.get("images"):342            lst.images = list(dict.fromkeys(lst.images + d["images"]))[:15]343344    # ---------------------------------------------------------------------345    def _parse_items(self, content: str) -> list[Listing]:346        out: list[Listing] = []347        if not content:348            return out349        soup = BeautifulSoup(content, "html.parser")350        for item in soup.select(".jet-listing-grid__item[data-post-id]"):351            try:352                a = item.select_one('a[href*="/unites/"]')353                if not a:354                    continue355                url = a["href"]356                slug = url.rstrip("/").split("/")[-1]357358                for st in item.select("style"):359                    st.decompose()360                text = item.get_text(" ", strip=True)361362                # Complexe depuis le slug (ex. sonora-101, noroit-2-151)363                cslug = re.match(r"([a-z]+(?:-2)?)-\d+", slug)364                complexe = COMPLEXES.get(cslug.group(1) if cslug else "", "")365                if not complexe and cslug:366                    complexe = cslug.group(1).replace("-", " ").title()367368                num_m = re.search(r"Unité\s+(\w+)\s*-?", text)369                unit_no = num_m.group(1) if num_m else slug.split("-")[-1]370                floor_m = re.search(r"Étage\s+(\d+)", text)371372                price = None373                price_label = ""374                pm = re.search(r"(\d{3,5})\s*\$\s*(/mois\*?)", text)375                if pm:376                    price = parse_price(pm.group(1) + "$")377                    price_label = (pm.group(1) + "$" + pm.group(2))378                    if "*" in pm.group(2):379                        price_label += (" (chauffé, éclairé, climatisé, "380                                        "stationnement int.)")381382                avail_m = re.search(r"Disponibilité\s*:\s*([^|]+?)(?:Unité|$)",383                                    text)384                availability = (f"Disponibilité : {avail_m.group(1).strip()}"385                                if avail_m else "Disponible")386387                promo = "En promotion" in text388389                # Images : logo du complexe exclu, plan de l'unité conservé390                images: list[str] = []391                unit_type = ""392                for img in item.select("img[src]"):393                    src = img["src"]394                    if not src.startswith("http"):395                        continue396                    if re.search(r"logo|_rgb_|descripteur|\.svg$", src, re.I):397                        continue398                    full = re.sub(r"-\d+x\d+(\.(?:jpg|jpeg|png|webp))$",399                                  r"\1", src)400                    images.append(full)401                    # type d'unité encodé dans le nom du plan402                    tm = (re.search(r"pieces[-_](\d)\.5", src, re.I)403                          or re.search(r"_(\d)\.5\b", src))404                    if tm and not unit_type:405                        unit_type = normalize_unit_type(f"{tm.group(1)} 1/2")406                images = list(dict.fromkeys(images))407408                desc_parts = [f"Complexe {complexe}" if complexe else ""]409                if floor_m:410                    desc_parts.append(f"Étage {floor_m.group(1)}")411                if promo:412                    desc_parts.append("En promotion")413                desc_parts = [d for d in desc_parts if d]414415                # repli générique (remplacé par la liste « Incluant » réelle416                # de la fiche d'unité quand elle est disponible)417                amenities = ["Eau chaude incluse",418                             "Internet haute vitesse inclus",419                             "Stationnement extérieur ou intérieur",420                             "Accès aux aires communes"]421                if promo:422                    amenities.append("En promotion")423424                details: dict = {}425                if floor_m:426                    details["floor"] = int(floor_m.group(1))427428                out.append(Listing(429                    source=self.source_id,430                    external_id=slug,431                    url=url,432                    title=f"Faubourg du Moulin ({complexe or 'complexe'}) — "433                          f"Unité {unit_no}"434                          f"{' (' + unit_type + ')' if unit_type else ''}",435                    address=ADDRESS,436                    sector=SECTOR,437                    city=CITY,438                    unit_type=unit_type,439                    price=price,440                    price_label=price_label,441                    availability=availability,442                    description=" | ".join(desc_parts),443                    amenities=amenities,444                    details=details,445                    images=images,446                ))447            except Exception:448                continue449        return out450
Files main
Menu

Theme