SPB Git

Repository Public

gesteco.py 10.2 KB 252 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gesteco.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/gesteco.py : connecteur Gesteco (gesteco.ca)91#   Condos locatifs neufs — Granby (Irwin Nord, Faubourg du Séminaire),92#   Waterloo (Sommets de l'Horizon), Bromont, Cowansville. Umbraco (.NET)93#   + app Vue `homeRentalBrowsingApp` : API JSON publique94#   `/umbraco/api/units?locale=fr&page=N&pageSize=100` (pagination par95#   en-têtes X-Total-Pages). Chaque unité expose id, adresse complète, ville,96#   prix (rawBasePrice), date de disponibilité ISO, superficie (livingArea),97#   chambres/sdb, configuration (« 4 ½ + bureau »), chiens permis, promotion,98#   description HTML, images et l'URL de la fiche (`rentalUrl`).99#   Filtres : status == "Available" ET buildingListingType == 1 (location —100#   le type 0 = achat, prix de vente à 6 chiffres, hors périmètre).101#   Aucune page détail nécessaire : l'API contient tout.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type110from .base import BaseConnector111112BASE = "https://gesteco.ca"113API_URL = f"{BASE}/umbraco/api/units"114PAGE_SIZE = 100115116117def _strip_html(raw: str) -> str:118    """Description HTML (Word collé) -> texte lisible, longueur plafonnée."""119    if not raw:120        return ""121    txt = BeautifulSoup(raw, "html.parser").get_text(" ", strip=True)122    return re.sub(r"\s+", " ", txt).strip()[:1500]123124125class GestecoConnector(BaseConnector):126    source_id = "gesteco"127    request_delay = 0.6128    max_pages = 10           # garde-fou de pagination API129130    def fetch(self) -> list[Listing]:131        listings: dict[str, Listing] = {}132        for page in range(1, self.max_pages + 1):133            resp = self.get(API_URL, params={134                "locale": "fr", "page": page, "pageSize": PAGE_SIZE})135            units = resp.json()136            if not units:137                break138            for unit in units:139                try:140                    lst = self._parse_unit(unit)141                except Exception:142                    continue143                if lst and lst.external_id not in listings:144                    listings[lst.external_id] = lst145            # page incomplète = dernière page (l'en-tête X-Total-Pages n'est146            # pas rejouable par les fixtures — on s'appuie sur la taille)147            if len(units) < PAGE_SIZE:148                break149        return list(listings.values())150151    # -- unité (payload API) -----------------------------------------------------152    def _parse_unit(self, u: dict) -> Listing | None:153        # location seulement : type 1 = louer ; type 0 = achat (prix de vente)154        if u.get("status") != "Available" or u.get("buildingListingType") != 1:155            return None156        if u.get("isActive") is False:157            return None158        rental_url = u.get("rentalUrl") or ""159        if not rental_url:160            return None161162        address = (u.get("fullAddress") or "").strip()163        city = (u.get("city") or "").strip()164165        # type d'unité : configuration structurée (« 4 ½ + bureau »)166        configs = u.get("unitUnitConfigurations") or []167        raw_type = (configs[0].get("unitConfigurationName") or "") if configs else ""168        unit_type = normalize_unit_type(raw_type)169170        price = None171        price_label = ""172        raw_price = u.get("rawBasePrice")173        if isinstance(raw_price, (int, float)) and 100 <= raw_price <= 20000:174            price = float(raw_price)175            price_label = f"{raw_price:g} $ /mois"176177        # disponibilité ISO de l'API (« 2026-07-01T04:00:00 »)178        availability = (u.get("availabilityDate") or "").split("T")[0]179180        area = None181        living = u.get("livingArea")182        if isinstance(living, (int, float)) and 80 <= living <= 20000:183            area = float(living)184185        # commodités affichables issues des champs structurés de l'API186        amenities: list[str] = []187        if raw_type:188            amenities.append(raw_type)189        bedrooms = u.get("bedrooms")190        if isinstance(bedrooms, (int, float)) and bedrooms:191            amenities.append(f"{bedrooms:g} chambre(s)")192        bathrooms = u.get("bathrooms")193        if isinstance(bathrooms, (int, float)) and bathrooms:194            amenities.append(f"{bathrooms:g} salle(s) de bain")195        if u.get("floorName"):196            amenities.append(f"Étage : {u['floorName']}")197        if u.get("hasChargingStation"):198            amenities.append("Borne de recharge disponible")199200        # champs structurés fidèles (jamais déduits)201        details: dict = {}202        if u.get("dogAllowed") is not None:203            details["dog_allowed"] = bool(u["dogAllowed"])204        if u.get("projectName"):205            details["project"] = u["projectName"]206207        # description (HTML de l'API) + promotion affichée sur la fiche —208        # champs français natifs (les champs « localized » ressortent en anglais209        # malgré locale=fr)210        description = _strip_html(u.get("description")211                                  or u.get("localizedDescription") or "")212        promo = (u.get("promotions") or u.get("localizedPromotions") or "").strip()213        if promo:214            description = (f"Promotion : {promo}" +215                           (f" | {description}" if description else ""))[:1500]216217        # images : galerie de l'unité, photo de l'immeuble, plan de la config218        images: list[str] = []219        for img in (u.get("images") or []):220            src = img.get("url") if isinstance(img, dict) else img221            if isinstance(src, str) and src.startswith("http") and src not in images:222                images.append(src)223        for src in ([u.get("buildingImageUrl")] +224                    [c.get("planImageUrl") for c in configs]):225            if isinstance(src, str) and src.startswith("http") and src not in images:226                images.append(src)227228        street = (u.get("street") or u.get("localizedStreet") or "").strip()229        unit_no = (u.get("unitNumber") or "").strip()230        title = address.rsplit(",", 1)[0] if address else street231        if unit_no and street and unit_no not in title:232            title = f"{title}, unité {unit_no}"233234        return Listing(235            source=self.source_id,236            external_id=str(u["id"]),237            url=f"{BASE}{rental_url}",238            title=title,239            address=address,240            sector="",241            city=city,242            unit_type=unit_type,243            price=price,244            price_label=price_label,245            availability=availability,246            area_sqft=area,247            description=description,248            amenities=amenities,249            details=details,250            images=images[:30],251        )252
Files main
Menu

Theme