SPB Git

Repository Public

aube.py 11.8 KB 300 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/aube.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/aube.py : connecteur Aubé Immobilier (aubeimmo.com)91#   Gestionnaire de Québec (Sainte-Foy, Limoilou) ; site de location92#   www.appartements-quebec.ca = portail Building Stack en marque blanche93#   (même code .NET que les portails *.bstk.io des connecteurs summum.py /94#   org_dupuis.py / urban_services.py) :95#     - /Listing/Listings embarque `var units = [...]` (ApartmentId stable,96#       prix, pi², chambres, sdb, adresse complète avec GPS, contact) ;97#     - les pages immeuble /b/<id> donnent la date de disponibilité par98#       unité et les commodités de l'immeuble (cache self.detail).99#   Petit parc : une poignée d'unités affichées à la fois. Le portail publie100#   « Ville de Québec » comme ville -> ramené à « Québec ».101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import html as _html106import json107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing112from .base import BaseConnector113114BASE = "https://www.appartements-quebec.ca"115LIST_URL = f"{BASE}/Listing/Listings"116117_WS_RE = re.compile(r"\s+")118# graphies du portail -> toponyme officiel119_CITY_FIX = {"Ville de Québec": "Québec", "Quebec": "Québec",120             "Quebec City": "Québec"}121122123def _extract_json(html: str, marker: str):124    """Décode la structure JSON qui suit `marker` dans un script inline."""125    i = html.find(marker)126    if i < 0:127        return None128    try:129        data, _ = json.JSONDecoder().raw_decode(html[i + len(marker):].lstrip())130    except Exception:131        return None132    return data133134135def _sqft(raw) -> float | None:136    try:137        v = float(str(raw).strip().replace(" ", "").replace(",", "."))138    except (TypeError, ValueError):139        return None140    return v if 80 <= v <= 20000 else None141142143class AubeConnector(BaseConnector):144    source_id = "aube"145    request_delay = 0.6146    max_buildings = 30           # garde-fou pages immeuble147    max_images = 12148149    # -- page immeuble /b/<id> : dates de disponibilité + commodités -----------150    def _building_page(self, pub: str, key: str) -> dict:151        """{ 'dates': {unité: dispo}, 'amenities': [...], 'images': [...] }."""152        def _fetch() -> dict:153            html = self.get(f"{BASE}/b/{pub}").text154            soup = BeautifulSoup(html, "html.parser")155            dates: dict[str, str] = {}156            for a in soup.select("ul.wpb-tabs-menu a.apartment-view-potential"):157                spans = [s.get_text(" ", strip=True) for s in a.find_all("span")]158                if len(spans) >= 6 and spans[0]:159                    dates[spans[0]] = spans[5]        # Unité -> Disponible160            amenities: list[str] = []161            for li in soup.select(".facilities ul li label"):162                t = _WS_RE.sub(" ", li.get_text(" ", strip=True))163                if 3 <= len(t) <= 90 and t not in amenities:164                    amenities.append(t)165            imgs = list(dict.fromkeys(re.findall(166                r"https://wfiles\.buildingstack\.com/resources/image/\w+",167                html)))168            return {"dates": dates, "amenities": amenities[:20],169                    "images": imgs[:10]}170171        try:172            return self.detail(pub, key, _fetch)173        except Exception:174            return {}175176    # -- fetch ------------------------------------------------------------------177    def fetch(self) -> list[Listing]:178        html = self.get(LIST_URL).text179        units = _extract_json(html, "var units =") or []180181        # regrouper par immeuble (résidentiel, Québec seulement — prudence)182        by_pub: dict[str, list[dict]] = {}183        for u in units:184            addr = u.get("Address") or {}185            prov = ((addr.get("Province") or {}).get("ProvinceCode") or "")186            if prov and prov.upper() != "QC":187                continue188            if not (u.get("Apartment") or {}).get("IsResidential", True):189                continue                  # commercial / stationnement190            pub = str((u.get("Building") or {})191                      .get("PublicListBuildingName") or "")192            if pub:193                by_pub.setdefault(pub, []).append(u)194195        bldg_info: dict[str, dict] = {}196        for pub, us in sorted(by_pub.items())[: self.max_buildings]:197            key = hashlib.sha1(json.dumps(198                sorted((str(x.get("ApartmentId")),199                        str((x.get("Apartment") or {}).get("Price")))200                       for x in us)).encode("utf-8")).hexdigest()[:16]201            bldg_info[pub] = self._building_page(pub, key)202203        listings: list[Listing] = []204        for pub, us in by_pub.items():205            info = bldg_info.get(pub) or {}206            for u in us:207                try:208                    lst = self._listing(u, pub, info)209                    if lst:210                        listings.append(lst)211                except Exception:212                    continue213214        uniq: dict[str, Listing] = {}215        for lst in listings:216            uniq.setdefault(lst.external_id, lst)217        return list(uniq.values())218219    # -- une annonce par unité ----------------------------------------------------220    def _listing(self, u: dict, pub: str, info: dict) -> Listing | None:221        apt = u.get("Apartment") or {}222        adr = u.get("Address") or {}223        bld = u.get("Building") or {}224        ext_id = str(u.get("ApartmentId") or "")225        if not ext_id:226            return None227        num = str(apt.get("UnitName") or "").strip()228        bname = _WS_RE.sub(" ", _html.unescape(229            str(u.get("BuildingName") or ""))).strip()230231        beds = apt.get("NumberOfBedrooms") or 0232        baths = apt.get("NumberOfBathrooms") or 0233        unit_type = "Studio" if not beds else f"{int(beds) + 2}½"234235        dispo = (info.get("dates") or {}).get(num, "")236        if not dispo:237            availability = "Disponible"238        elif re.search(r"\d", dispo):     # « sept. 01, 2026 »239            availability = f"Libre {dispo}"240        else:                             # « Disponible dès maintenant! »241            availability = dispo242243        area = _sqft(apt.get("Area"))244        desc = " — ".join(x for x in [245            f"{area:g} pi²" if area else "",246            f"{beds} chambre(s)" if beds else "",247            f"{baths} salle(s) de bain" if baths else ""] if x)248249        details: dict = {"bedrooms": int(beds), "bathrooms": int(baths)}250        if isinstance(u.get("ParkingsIsAvailable"), bool):251            details["parking"] = {"available": u["ParkingsIsAvailable"]}252        if isinstance(u.get("StoragesIsAvailable"), bool):253            details["storage"] = u["StoragesIsAvailable"]254        contacts = bld.get("ListingEmployeesContacts") or []255        if contacts:256            c = contacts[0]257            contact = {k: v for k, v in [258                ("name", c.get("FullName")),259                ("phone", c.get("FormattedPhoneNumber")),260                ("email", c.get("Email"))] if v}261            if contact:262                details["contact"] = contact263264        imgs: list[str] = []265        prev = str(u.get("PreviewUrl") or "")266        if prev.startswith("http"):267            imgs.append(prev)268        imgs += [x for x in (info.get("images") or []) if x not in imgs]269270        try:271            lat, lng = float(adr.get("Latitude")), float(adr.get("Longitude"))272        except (TypeError, ValueError):273            lat = lng = None274275        city = _html.unescape(str(adr.get("City") or "")).strip()276        city = _CITY_FIX.get(city, city)277278        burl = str(u.get("BuildingUrl") or "")279        url = BASE + burl if burl.startswith("/") else f"{BASE}/b/{pub}"280        return Listing(281            source=self.source_id,282            external_id=ext_id,283            url=url,284            title=(f"{bname} — Unité {num}" if num else bname),285            address=_html.unescape(str(adr.get("Full") or "")),286            sector="",287            city=city,288            unit_type=unit_type,289            price=float(apt.get("Price") or 0) or None,290            price_label=str(apt.get("PriceFormatted") or ""),291            availability=availability,292            area_sqft=area,293            description=desc[:600],294            amenities=list(info.get("amenities") or []),295            details=details,296            images=imgs[: self.max_images],297            lat=lat,298            lng=lng,299        )300
Files main
Menu

Theme