SPB Git

Repository Public

kare.py 8.5 KB 224 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/kare.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/kare.py : connecteur Kare Gestion Immobilière (gestionkare.com)91#   Gestionnaire de Sherbrooke (Estrie) — ~54 unités : Sherbrooke (Les92#   Nations, Fleurimont, Rock Forest, Lennoxville), Waterloo, Windsor,93#   Richmond, Magog + quelques hors Estrie (Drummondville, Châteauguay).94#   SPA Angular avec SSR : la page /units/ embarque l'état hydraté dans95#   <script id="ng-state"> — on y lit la réponse JSON complète de96#   /api/units (id, title, address, city, sublocality, price, availability97#   ISO, amenities booléens, images CDN, lat/lng, promotion). Repli : GET98#   direct sur l'API (kare-test-dhpzr.ondigitalocean.app — hôte lu dans le99#   ng-state quand possible). URL détail = /units/<id>--<ville>-<type>100#   (même slugification que le front). external_id = id (UID Kare) — stable.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import json105import re106107from ..schema import Listing, normalize_unit_type, strip_accents108from .base import BaseConnector109110BASE = "https://www.gestionkare.com"111LIST_URL = f"{BASE}/units/"112API_URL = "https://kare-test-dhpzr.ondigitalocean.app/api/units"113114NG_STATE_RE = re.compile(115    r'<script[^>]*id="ng-state"[^>]*>([\s\S]*?)</script>', re.I)116UNIT_RE = re.compile(r"(\d)\s*(?:1/2|½|et\s+demie?)", re.I)117BEDS_RE = re.compile(r"(\d)\s*[Cc]hambres?")118119120def _slug(text: str) -> str:121    # même esprit que le front Angular : minuscules, tirets122    s = strip_accents((text or "").lower())123    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")124125126class KareConnector(BaseConnector):127    source_id = "kare"128    request_delay = 0.8129130    def fetch(self) -> list[Listing]:131        units = self._units_from_ng_state()132        if not units:133            units = self.get(API_URL).json()134        listings: list[Listing] = []135        for u in units or []:136            listing = self._to_listing(u)137            if listing is not None:138                listings.append(listing)139        return listings140141    def _units_from_ng_state(self) -> list[dict]:142        try:143            html = self.get(LIST_URL).text144            m = NG_STATE_RE.search(html)145            if not m:146                return []147            state = json.loads(m.group(1))148        except Exception:149            return []150        for entry in state.values():151            if isinstance(entry, dict) \152                    and str(entry.get("u", "")).endswith("/api/units") \153                    and isinstance(entry.get("b"), list):154                return entry["b"]155        return []156157    def _to_listing(self, u: dict) -> Listing | None:158        uid = u.get("id") or ""159        price = u.get("price")160        title = re.sub(r"\s+", " ", u.get("title") or u.get("name") or "")161        if not uid or not title:162            return None163164        city = (u.get("city") or "").strip()165        utype = (u.get("type") or "").strip()166167        # typologie : « 5 1/2 à louer » dans le titre, sinon champ type168        unit_type = ""169        um = UNIT_RE.search(title)170        if um:171            unit_type = normalize_unit_type(f"{um.group(1)} ½")172        elif re.search(r"studio", utype, re.I):173            unit_type = "Studio"174        elif re.search(r"chambre\s+uniquement", utype, re.I):175            unit_type = "Chambre"176177        bedrooms = None178        bm = BEDS_RE.search(utype)179        if bm:180            bedrooms = float(bm.group(1))181            if re.search(r"demie?", utype, re.I):182                bedrooms += 0.5183184        address = re.sub(r",\s*Canada\s*$", "", u.get("address") or "")185        amenities = [k for k, v in (u.get("amenities") or {}).items() if v]186        pets = None187        if "Animal autorisé" in amenities:188            pets = "oui"189            amenities.remove("Animal autorisé")190191        avail = (u.get("availability") or "").strip()192        details: dict = {}193        if u.get("promotion"):194            details["promotion"] = u["promotion"]195        if u.get("sublocality"):196            details["sublocality"] = u["sublocality"]197198        images = [im for im in (u.get("images") or []) if im][:12]199        url = f"{BASE}/units/{uid}--{_slug(city)}-{_slug(utype)}"200201        return Listing(202            source=self.source_id,203            external_id=uid,204            url=url,205            title=title,206            address=address,207            sector=u.get("sublocality") or "",208            city=city,209            unit_type=unit_type,210            bedrooms=bedrooms,211            bathrooms=float(u["bathrooms"]) if u.get("bathrooms") else None,212            price=float(price) if price else None,213            availability=f"Libre le {avail}" if avail else "",214            availability_date=avail or None,215            area_sqft=float(u["surface"]) if u.get("surface") else None,216            pets=pets,217            description=(u.get("description") or "").strip(),218            amenities=amenities,219            details=details,220            images=images,221            lat=u.get("latitude"),222            lng=u.get("longitude"),223        )224
Files main
Menu

Theme