SPB Git

Repository Public

centurion.py 17.6 KB 406 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/centurion.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-08-2714#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/centurion.py : connecteur Centurion / CP Living (cpliving.com)91#   REIT national (Centurion Property Associates) — région de Québec : le92#   Quartier QB, 2551 chemin des Quatre-Bourgeois (Sainte-Foy), 684 unités.93#   Le site est propulsé par Rentsync : la page de recherche référence un94#   proxy legacy `widgets/search/api_proxy.php?client_id=21&city_id=2310`95#   (404 aujourd'hui) mais son JS (scripts/main.js) appelle en réalité le96#   flux JSON officiel `https://api.theliftsystem.com/v2/search` avec un97#   auth_token embarqué. On lit client_id/city_id sur la page, le token dans98#   main.js (repli : constantes), puis on interroge le flux directement —99#   aucune exécution JavaScript nécessaire, Cloudflare accepte le UA de base.100#   Filtre région : city_ids 2310 (Ville de Québec) + 1039 (Gatineau, ajouté101#   à l'expansion provinciale 2026-08) + garde-fou province/ville.102#   La fiche propriété (rendu serveur) fournit la galerie photo, via le cache103#   BD self.detail() (revisitée seulement quand le flux change).104#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,105#   le flux est interrogé SANS city_ids (tout le parc Centurion, ~104106#   propriétés dont ~52 en Ontario : Toronto/GTA, Ottawa, Kitchener-Waterloo,107#   Barrie, Huntsville…) ; les entrées province_code=="ON" sont acceptées108#   (plafond séparé max_properties_on), le garde-fou QC (_QC_CITIES +109#   province_code=="QC") reste appliqué tel quel aux entrées québécoises.110#   Sans la variable, comportement strictement identique (city_ids QC).111# -----------------------------------------------------------------------------112from __future__ import annotations113114import hashlib115import os116import re117118from bs4 import BeautifulSoup119120from ..schema import Listing, infer_city, normalize_unit_type, strip_accents121from .base import BaseConnector122123# Expansion Ontario 2026-08 — gate d'environnement (défaut : QC seulement)124_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"125126BASE = "https://www.cpliving.com"127SEARCH_PAGE = f"{BASE}/apartments-for-rent/quebec-city"128LIFT_API = "https://api.theliftsystem.com/v2/search"129130# Valeurs observées sur la page/main.js — repli si l'extraction dynamique casse131DEFAULT_CLIENT_ID = "21"132DEFAULT_CITY_ID = "2310"          # Ville de Québec dans la base Lift/Rentsync133GATINEAU_CITY_ID = "1039"         # Gatineau (expansion provinciale 2026-08)134DEFAULT_AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"135136# Garde-fou région : villes couvertes — agglomération Québec/Lévis + Gatineau137# (clé sans accents, suffixe « QC » du flux retiré par _city_key)138_QC_CITIES = {139    "quebec", "ville de quebec", "quebec city", "sainte-foy", "ste-foy",140    "sillery", "beauport", "charlesbourg", "cap-rouge", "levis",141    "l-ancienne-lorette", "saint-augustin-de-desmaures",142    "gatineau", "hull", "aylmer",143}144145# jeton d'authentification dans main.js : `s="&client_id=21",e="&auth_token=…"`146_TOKEN_RE = r'client_id={cid}",\w+="&auth_token=([A-Za-z0-9]+)"'147_MAINJS_RE = re.compile(r'src="(/scripts/main\.js[^"]*)"')148# galerie de la fiche propriété (img + backgrounds CSS)149_IMG_RE = re.compile(150    r"https://assets\.rentsync\.com/[^\"'\\)\s]+\.(?:jpg|jpeg|png|webp)", re.I)151_SKIP_IMG = re.compile(r"logo|icon|favicon|badge|/thumb", re.I)152153154def _city_key(city: str) -> str:155    key = strip_accents((city or "").strip().lower())156    return re.sub(r"\s+(?:qc|on)$", "", key)  # le flux accole parfois la province157158159class CenturionConnector(BaseConnector):160    source_id = "centurion"161    request_delay = 0.7162    max_properties = 30       # garde-fou (1 propriété à Québec aujourd'hui)163    max_images = 20164    # Expansion Ontario 2026-08 (gaté LOUKA_ONTARIO) : plafond séparé pour le165    # parc ontarien (~52 propriétés au flux) — le budget QC reste intact166    max_properties_on = 100167168    # -- paramètres du flux (page + main.js, avec replis) ----------------------169    def _feed_params(self) -> tuple[str, str, str]:170        """(client_id, city_id, auth_token) lus sur le site, replis constants."""171        client_id, city_id, token = (DEFAULT_CLIENT_ID, DEFAULT_CITY_ID,172                                     DEFAULT_AUTH_TOKEN)173        try:174            page = self.get(SEARCH_PAGE).text175            soup = BeautifulSoup(page, "html.parser")176            data = soup.find("div", class_="search-data")177            if data:178                client_id = (data.get("data-client-id") or client_id).strip()179                city_id = (data.get("data-city-id") or city_id).strip()180            m = _MAINJS_RE.search(page)181            if m:182                js = self.get(BASE + m.group(1)).text183                mt = re.search(_TOKEN_RE.format(cid=re.escape(client_id)), js)184                if mt:185                    token = mt.group(1)186        except Exception:187            pass    # replis : les constantes observées188        return client_id, city_id, token189190    def fetch(self) -> list[Listing]:191        client_id, city_id, token = self._feed_params()192        params = {193            "client_id": client_id,194            "auth_token": token,195            "city_ids": f"{city_id},{GATINEAU_CITY_ID}",196            "show_all_properties": "true",197            "show_custom_fields": "true",198            "show_amenities": "true",199            "show_promotions": "true",200            "limit": "1000",201        }202        if _ONTARIO:203            # Expansion Ontario 2026-08 : sans city_ids, le flux renvoie tout204            # le parc Centurion (~104 propriétés) — le garde-fou QC ci-dessous205            # reste appliqué tel quel, les entrées ON sont acceptées en plus.206            del params["city_ids"]207        props = self.get(LIFT_API, params=params,208                         headers={"Accept": "application/json",209                                  "Referer": BASE + "/"}).json()210211        listings: list[Listing] = []212        if not _ONTARIO:213            # comportement historique, strictement inchangé214            for p in props[: self.max_properties]:215                try:216                    addr = p.get("address") or {}217                    if (addr.get("province_code") or "").upper() != "QC":218                        continue    # REIT national : rester dans la province219                    if _city_key(addr.get("city", "")) not in _QC_CITIES:220                        continue    # garde-fou région Québec/Lévis221                    listings.append(self._listing(p))222                except Exception:223                    continue224            return listings225226        # LOUKA_ONTARIO=1 : QC (mêmes garde-fous/plafond) + Ontario (plafond227        # séparé) — le flux mêle les provinces, on compte donc par province228        qc_n = on_n = 0229        for p in props:230            try:231                addr = p.get("address") or {}232                prov = (addr.get("province_code") or "").upper()233                if prov == "QC":234                    if _city_key(addr.get("city", "")) not in _QC_CITIES:235                        continue    # garde-fou région Québec/Lévis236                    if qc_n >= self.max_properties:237                        continue238                    qc_n += 1239                    listings.append(self._listing(p))240                elif prov == "ON":241                    if on_n >= self.max_properties_on:242                        continue243                    on_n += 1244                    listings.append(self._listing(p, province="ON"))245                # autres provinces (BC/AB/NS/MB…) : hors périmètre246            except Exception:247                continue248        return listings249250    # -- une annonce par propriété ---------------------------------------------251    def _listing(self, p: dict, province: str = "QC") -> Listing:252        pid = str(p.get("id"))253        addr = p.get("address") or {}254        url = p.get("permalink") or SEARCH_PAGE255        name = (p.get("name") or "").strip()256257        # adresse complète : rue + ville + code postal (tous fournis au flux)258        ck = _city_key(addr.get("city", ""))259        if province == "QC" and ck in ("quebec", "ville de quebec",260                                       "quebec city"):261            city = "Québec"262        else:   # retirer le suffixe province du flux (« Gatineau QC »)263            city = re.sub(rf"\s+{province}$", "",264                          (addr.get("city") or "").strip(), flags=re.I)265        street = (addr.get("address") or "").strip()266        postal = (addr.get("postal_code") or "").strip()267        full_addr = ", ".join(x for x in (street, city) if x)268        if postal:269            # adresse suffixée par la province (« ON » pour l'Ontario)270            full_addr += f", {province} {postal}"271        elif province == "ON" and full_addr:272            full_addr += ", ON"273        sector = (addr.get("neighbourhood") or "").strip()274275        # coordonnées GPS structurées du flux276        geo = p.get("geocode") or {}277        try:278            lat = float(geo["latitude"]) if geo.get("latitude") else None279            lng = float(geo["longitude"]) if geo.get("longitude") else None280        except (TypeError, ValueError):281            lat = lng = None282283        # sommaire des unités disponibles (rempli seulement s'il y a vacance)284        stats = ((p.get("statistics") or {}).get("suites") or {})285        rates = stats.get("rates") or {}286        beds = stats.get("bedrooms") or {}287        baths = stats.get("bathrooms") or {}288        sqft = stats.get("square_feet") or {}289        price = float(rates["min"]) if rates.get("min") else None290        price_label = ""291        if price is not None:292            price_label = (f"À partir de {price:.0f} $"293                           if rates.get("max") and rates["max"] != rates["min"]294                           else f"{price:.0f} $ /mois")295        # type d'unité : seulement si la gamme est sans ambiguïté296        unit_type = ""297        if beds.get("min") is not None and beds.get("min") == beds.get("max"):298            n = int(beds["min"])299            unit_type = "Studio" if n == 0 else normalize_unit_type(300                f"{n} chambres")301        # superficie : le flux publie parfois « 0.0 » (Gatineau) — ignorer302        area = None303        try:304            v = float(sqft.get("min") or 0)305            if 80 <= v <= 20000:306                area = v307        except (TypeError, ValueError):308            pass309310        # disponibilité : libellé du flux (« No Vacancy », « X Vacancies »…)311        availability = (p.get("availability_status_label") or "").strip()312        avail_date = None313        mad = str(p.get("min_availability_date") or "").strip()314        if re.fullmatch(r"20\d{2}-\d{2}-\d{2}", mad[:10]):315            avail_date = mad[:10]316317        # description : aperçu HTML du flux (rendu texte)318        details_src = p.get("details") or {}319        desc = BeautifulSoup(details_src.get("overview") or "",320                             "html.parser").get_text(" ", strip=True)321        promo = p.get("promotion") or {}322        promo_txt = (promo.get("title") or promo.get("name") or "").strip() \323            if isinstance(promo, dict) else ""324        if promo_txt:325            desc = f"Promotion : {promo_txt}. {desc}".strip()326327        # commodités : liste du flux + champ personnalisé Rentsync (CSV)328        amenities: list[str] = []329        for a in p.get("amenities") or []:330            t = (a.get("name") if isinstance(a, dict) else str(a) or "").strip()331            if t and t not in amenities:332                amenities.append(t)333        cf = p.get("custom_fields") or {}334        for t in (cf.get("amenities") or "").split(","):335            t = t.strip()336            if t and t not in amenities:337                amenities.append(t)338339        # champs structurés du flux340        details: dict = {}341        contact = p.get("contact") or {}342        if contact.get("phone"):343            details["contact"] = {"phone": contact["phone"]}344        if contact.get("email"):345            details.setdefault("contact", {})["email"] = contact["email"]346        # pet_friendly=false ne distingue pas « interdit » de « non renseigné »347        pets = "oui" if p.get("pet_friendly") is True else None348349        # galerie photo de la fiche propriété — via le cache BD : revisitée350        # seulement quand la ligne du flux change351        feed_key = hashlib.sha1("|".join(str(x) for x in (352            p.get("availability_count"), p.get("availability_status"),353            rates.get("min"), rates.get("max"), mad, p.get("photo"),354        )).encode("utf-8")).hexdigest()355        d = self.detail(pid, feed_key, lambda: self._fetch_gallery(url))356        images = list(d.get("images") or [])357        photo = (p.get("photo_path") or "").strip()358        if photo and photo not in images:359            images.insert(0, photo)360361        return Listing(362            source=self.source_id,363            external_id=pid,364            url=url,365            title=name,366            address=full_addr,367            sector=sector,368            # infer_city (secteurs Lévis) n'a de sens qu'au Québec369            city=(infer_city(sector, default=city or "Québec")370                  if province == "QC" else (city or "Toronto")),371            province=province,372            unit_type=unit_type,373            price=price,374            price_label=price_label,375            availability=availability,376            availability_date=avail_date,377            area_sqft=area,378            pets=pets,379            description=desc[:600] + (380                f" Salles de bain : {baths['min']:g}+."381                if baths.get("min") else ""),382            amenities=amenities[:25],383            details=details,384            images=images[: self.max_images],385            lat=lat,386            lng=lng,387        )388389    def _fetch_gallery(self, url: str) -> dict:390        """Scrape la galerie photo (assets.rentsync.com) de la fiche propriété."""391        out: dict = {"images": []}392        try:393            page = self.get(url).text394        except Exception:395            return out396        images: list[str] = []397        for u in _IMG_RE.findall(page):398            if _SKIP_IMG.search(u):399                continue400            # variante pleine résolution de la galerie (…/gallery/full/…)401            u = re.sub(r"/gallery/\d{3,4}/", "/gallery/full/", u)402            if u not in images:403                images.append(u)404        out["images"] = images[: self.max_images]405        return out406
Files main
Menu

Theme