SPB Git

Repository Public

kangalou.py 16.0 KB 383 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/kangalou.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-2414#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/kangalou.py : Kangalou (kangalou.com) — portail locatif québécois91#   géré (Solutions Kangalou, ~8 700 annonces province entière). Découverte en92#   UNE requête : l'endpoint carte `POST /fr/recherche/ajax/search-map/`93#   (pinsOnly=true) renvoie tous les pins JSON — id, URL de fiche, GPS, ville,94#   type (ti/tn ; 10=Commercial et 11=Garage exclus), « n ½ » (an), prix (mc),95#   photo et l'état loué (ir, exclu). La fiche /fr/annonce/<slug>/<id>/ (SSR,96#   aucun anti-bot) complète : adresse civique, chambres/salles de bain, loyer,97#   étage, superficie, disponibilité, description longue, sections « toggler »98#   (Inclusions, Caractéristiques, Animaux, Sécurité, À proximité, Transport…)99#   et la galerie COMPLÈTE pleine résolution (gr-modal-gallery-src, sans100#   paramètre de redimensionnement) — via TtlDetailCache (budget/TTL). Le101#   budget par défaut couvre tout le parc (~8 000 fiches) : le premier sync est102#   long (~1 h 30), les suivants ne re-visitent que les fiches périmées (TTL).103#   L'API de liste HTML (POST /fr/api/search) existe aussi mais pagine par 29104#   et masque l'état loué (CSS) : les pins sont la source fiable.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import os109import re110111from ..schema import Listing, normalize_unit_type112from .base import BaseConnector113from . import _detailutil as du114115BASE = "https://www.kangalou.com"116PINS_API = f"{BASE}/fr/recherche/ajax/search-map/"117118DETAIL_LIMIT = int(os.environ.get("LOUKA_KANGALOU_DETAIL_LIMIT", "9000"))119TTL_DAYS = float(os.environ.get("LOUKA_KANGALOU_TTL_DAYS", "7"))120MAX_PINS = int(os.environ.get("LOUKA_KANGALOU_MAX", "0"))     # 0 = tout121122# type id -> type d'unité par défaut (le « n ½ » du pin prime quand présent)123_TYPES = {1: "", 2: "Condo", 3: "Maison", 4: "Chambre", 5: "Chalet",124          6: "Studio", 7: "Loft"}125_EXCLUDED_TI = {10, 11}          # Commercial, Garage : pas du résidentiel126127# fiche détail (SSR)128_GPS_RE = re.compile(r'maps/search/\?query=(-?\d+\.\d+)%2C(-?\d+\.\d+)')129_ADDR_RE = re.compile(r'buds--separator[^>]*u-text-size-sm">\s*<span>([^<]+)</span>', re.S)130# galerie : pleine taille dans gr-modal-gallery-src (les <img> sont lazyload) ;131# hébergement variable (images/glide kangalou OU s3 shareimmo/lws…)132_GALLERY_RE = re.compile(r'gr-modal-gallery-src="(https?://[^"]+)"')133_FLAT_FIELD = {134    "loyer": re.compile(r"Loyer:\s*\|\s*([\d\s ,]+\$\s*/\s*mois)"),135    "etage": re.compile(r"Étage:\s*\|\s*(\d{1,2})\b"),136    "sdb": re.compile(r"Nombre de salles? de bain:\s*\|\s*(\d+(?:[.,]5)?)"),137    "chambres": re.compile(r"Nombre de chambres:\s*\|\s*(\d+)"),138    "superficie": re.compile(r"Superficie:\s*\|\s*([\d\s ,.]+)\s*m\s*\|\s*2"),139    "dispo": re.compile(r"Disponibilité:\s*\|\s*([^|]{1,60})"),140}141# description : le titre varie selon le type (« Description du logement /142# du condo / de la maison / du studio… à louer ») — matcher générique.143# Bloc « typography » complet ; borne préférée = le déclencheur « Voir plus »144# (gr-read-more-trigger) pour survivre aux <div> imbriqués, sinon repli sur145# le premier </div> (bloc simple <p>…</p>)146_DESC_FULL_RE = re.compile(147    r'Description d[^<]{0,60}</h2>.*?<div class="typography"[^>]*>'148    r'(.*?)</div>\s*<div gr-read-more-trigger', re.S)149_DESC_RE = re.compile(150    r'Description d[^<]{0,60}</h2>.*?<div class="typography"[^>]*>(.*?)</div>',151    re.S)152153# sections « toggler » de la fiche : <div … gr-toggler-trigger>Titre</div>154# suivi d'items <p><strong>libellé</strong>[<span>valeurs</span>]</p>155_SECTION_ITEM_RE = re.compile(156    r"<p>\s*<strong>(.*?)</strong>(?:\s*<span>(.*?)</span>)?", re.S)157# sections « à proximité » -> details ; le reste (Inclusions, Caractéristiques158# intérieures/extérieures, Détail, Animaux, Sécurité, Buanderie, Autres159# services, Critères importants…) -> amenities160_PROXIMITY_TITLES = {"À proximité", "Transport"}161_PETS_NO = {"Aucun animal autorisé", "Aucun animal accepté", "Animaux refusés"}162_PETS_YES = {"Animaux acceptés", "Animaux autorisés", "Tous animaux autorisés"}163164165def _clean_text(fragment: str) -> str:166    """HTML -> texte propre (br/p/li = sauts de ligne, entités décodées)."""167    import html as _h168    txt = re.sub(r"<br\s*/?>", "\n", fragment)169    txt = re.sub(r"</(?:p|li|div|h\d)>", "\n", txt)170    txt = re.sub(r"<li[^>]*>", "- ", txt)171    txt = re.sub(r"<[^>]+>", " ", txt)172    txt = _h.unescape(txt)173    txt = re.sub(r"[ \t]+", " ", txt)174    txt = re.sub(r" ?\n ?", "\n", txt)175    return re.sub(r"\n{3,}", "\n\n", txt).strip()176177178def _toggler_sections(html: str) -> list[tuple[str, list[tuple[str, str]]]]:179    """[(titre de section, [(libellé, valeur)])] depuis les blocs toggler."""180    import html as _h181    out = []182    for seg in re.split(r"gr-toggler-trigger>", html)[1:]:183        title = _h.unescape(seg.split("<", 1)[0]).strip()184        items = []185        for lab, val in _SECTION_ITEM_RE.findall(seg):186            lab = _h.unescape(re.sub(r"<[^>]+>", " ", lab)).strip()187            val = _h.unescape(re.sub(r"<[^>]+>", " ", val or "")).strip()188            if lab and len(lab) <= 60:189                items.append((lab, val))190        if title and items:191            out.append((title, items))192    return out193194195def _parse_fiche(html: str) -> dict:196    """Champs riches d'une fiche Kangalou (SSR)."""197    out: dict = {}198    m = _GPS_RE.search(html)199    if m:200        out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))201    m = _ADDR_RE.search(html)202    if m:203        import html as _h204        # certaines fiches double-encodent (« Carri&amp;egrave;res ») : deux passes205        out["address"] = _h.unescape(_h.unescape(m.group(1))).strip()206207    flat = du.flatten(html)208    vals = {k: rx.search(flat) for k, rx in _FLAT_FIELD.items()}209    if vals["loyer"]:210        label = re.sub(r"\s+", " ", vals["loyer"].group(1)).strip()211        out["price_label"] = label212        try:213            out["price"] = float(re.sub(r"[^\d,.]", "", label.split("$")[0])214                                 .replace(",", ""))215        except ValueError:216            pass217        if not (100 <= (out.get("price") or 0) <= 20000):218            out.pop("price", None)219    if vals["chambres"]:220        out["bedrooms"] = float(vals["chambres"].group(1))221    if vals["sdb"]:222        out["bathrooms"] = float(vals["sdb"].group(1).replace(",", "."))223    if vals["dispo"]:224        out["availability"] = vals["dispo"].group(1).strip(" .")225    if vals["etage"]:226        out.setdefault("details", {})["floor"] = int(vals["etage"].group(1))227    if vals["superficie"]:228        try:229            m2 = float(vals["superficie"].group(1)230                       .replace(" ", "").replace(" ", "").replace(",", "."))231            if 8 <= m2 <= 2000:232                out["area_sqft"] = round(m2 * 10.7639)233        except ValueError:234            pass235236    m = _DESC_FULL_RE.search(html) or _DESC_RE.search(html)237    if m:238        desc = _clean_text(m.group(1))239        if desc:240            out["description"] = desc[:6000]241242    # sections « toggler » : commodités structurées + proximité + animaux.243    # Libellés jamais interprétés (texte source) ; « libellé : valeurs »244    # quand la section fournit des valeurs (ex. Type de plancher : Céramique).245    amen: list[str] = []246    proximity: dict[str, str] = {}247    pets_labels: list[str] = []248    for title, items in _toggler_sections(html):249        if title in _PROXIMITY_TITLES:250            for lab, val in items:251                proximity[lab] = val252            continue253        for lab, val in items:254            entry = f"{lab} : {val}" if val else lab255            if entry not in amen:256                amen.append(entry)257        if title == "Animaux":258            pets_labels += [lab for lab, _ in items]259    if amen:260        out["amenities"] = amen261    if proximity:262        out.setdefault("details", {})["proximity"] = proximity263264    # animaux / meublé : depuis les libellés structurés seulement (le texte265    # libre est laissé à la normalisation centrale)266    if pets_labels:267        if any(l in _PETS_NO for l in pets_labels):268            out["pets"] = "non"269        elif any(l in _PETS_YES for l in pets_labels):270            out["pets"] = "oui"271        else:                       # chat seulement, petit chien, en cage…272            out["pets"] = "conditions"273    if "Meublé" in amen:274        out["furnished"] = True275276    # galerie (slider--gallery ; les vignettes asnav dupliquées sont exclues)277    ig = html.find("slider--gallery")278    if ig >= 0:279        seg = html[ig:]280        cut = seg.find("slider__asnav")281        if cut > 0:282            seg = seg[:cut]283        photos = []284        for u in _GALLERY_RE.findall(seg):285            if u not in photos:286                photos.append(u)287        if photos:288            out["images"] = photos289290    vt = du.virtual_tour(html)291    if vt:292        out.setdefault("details", {})["virtual_tour"] = vt293    return out294295296class KangalouConnector(BaseConnector):297    source_id = "kangalou"298    request_delay = 0.5299    timeout = 90                    # la réponse pins fait ~6 Mo300301    def _pins(self) -> list[dict]:302        import time303        import requests304        # le POST n'a pas l'escalade résiliente de get() : retenter les305        # lenteurs transitoires du site (ReadTimeout constaté 2026-08-24)306        for attempt in range(3):307            try:308                resp = self.post(PINS_API, data={"pinsOnly": "true"},309                                 headers={"Accept": "application/json",310                                          "X-Requested-With": "XMLHttpRequest"})311                break312            except (requests.ConnectionError, requests.Timeout):313                if attempt == 2:314                    raise315                time.sleep(15 * (attempt + 1))316        return (resp.json() or {}).get("pins") or []317318    @staticmethod319    def _unit_type(pin: dict) -> str:320        an = (pin.get("an") or "").strip()        # « 4 ½ », « 9 ½ + »321        if an:322            ut = normalize_unit_type(an)323            if re.match(r"^\d½$|^6½\+$", ut or ""):324                return ut325        return _TYPES.get(pin.get("ti"), "")326327    def fetch(self) -> list[Listing]:328        pins = self._pins()329        if MAX_PINS:330            pins = pins[:MAX_PINS]331        # key=v2 : parseur enrichi 2026-08-18 (galerie complète déjà en v1 ;332        # ajout loyer/pets/meublé/proximité + description multi-blocs) — force333        # une re-visite du parc complet une seule fois334        cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS,335                                  key="v2")336        out: list[Listing] = []337        try:338            for pin in pins:339                if pin.get("ir"):340                    continue               # déjà loué : pas une offre active341                if pin.get("ti") in _EXCLUDED_TI or not pin.get("id"):342                    continue               # commercial / garage / malformé343                url = pin.get("l") or ""344                if not url:345                    continue346                eid = str(pin["id"])347                price = None348                try:349                    price = float(str(pin.get("mc")).replace(",", ""))350                except (TypeError, ValueError):351                    pass352                if price is not None and not (100 <= price <= 20000):353                    price = None           # affichage « sur demande » etc.354                lat = lng = None355                try:356                    lat, lng = float(pin["lt"]), float(pin["lg"])357                except (KeyError, TypeError, ValueError):358                    pass359                photo = pin.get("p") or ""360                lst = Listing(361                    source=self.source_id,362                    external_id=eid,363                    url=url,364                    title=(pin.get("n") or "").strip(),365                    city=(pin.get("c") or "").strip(),366                    unit_type=self._unit_type(pin),367                    price=price,368                    price_label=(f"{price:,.0f} $/mois".replace(",", " ")369                                 if price else ""),370                    images=[photo] if photo else [],371                    lat=lat,372                    lng=lng,373                )374                payload = cache.get(eid, url, _parse_fiche)375                if payload:376                    du.apply_detail(lst, payload)377                    if payload.get("address"):378                        lst.title = payload["address"]379                out.append(lst)380        finally:381            cache.close()382        return out383
Files main
Menu

Theme