SPB Git

Repository Public

alfid.py 13.4 KB 340 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/alfid.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/alfid.py : connecteur Groupe Alfid (alfidlouer.ca)91#   Gestionnaire montréalais (Plateau, Ville-Marie, Verdun, Anjou, CDN).92#   Plateforme Rentsync / The Lift System : découverte des immeubles via l'API93#   officielle du site (api.theliftsystem.com/v2/search, jeton public embarqué94#   dans le JS), puis parsing des fiches /properties/<slug> rendues serveur —95#   rangées div.suite (type, chambres, salles de bain, prix, pi²), id stable96#   via le modal « Inquire Now » (#modal-suite-<id>), photos par suite ou97#   galerie de l'immeuble (assets.rentsync.com/alfid_group). Le parsing des98#   rangées est partagé avec Douek (douek.py), même gabarit Rentsync.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import html as htmllib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing108from .base import BaseConnector109110API = "https://api.theliftsystem.com/v2/search"111AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"      # jeton public (main.js du site)112CLIENT_ID = "1162"113CITY_IDS = "1863,69,3218"                # Montréal, Anjou, Verdun114115_MODAL_RE = re.compile(r"#modal-suite-(\d+)")116_HALF_RE = re.compile(r"(\d)\s*(?:½|1/2|[.,]5)")117_GALLERY_RE = re.compile(118    r'https://assets\.rentsync\.com/[a-z0-9_]+/images/gallery/'119    r'[0-9]+/[^"\'\s\\)]+\.(?:jpg|jpeg|png|webp)', re.I)120121# Nombre de chambres -> type d'unité (convention QC : n½ = n-2 chambres)122_BED_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}123124125def _clean(txt: str) -> str:126    txt = htmllib.unescape(htmllib.unescape(txt or ""))127    txt = re.sub(r"<[^>]+>", " ", txt)128    return re.sub(r"\s+", " ", txt).strip()129130131class AlfidConnector(BaseConnector):132    source_id = "alfid"133    request_delay = 0.6134    max_buildings = 25           # garde-fou de crawl (9 immeubles au flux)135136    # -- API de recherche (backend officiel du site) ---------------------------137    def _search(self) -> list[dict]:138        params = {139            "locale": "fr",140            "client_id": CLIENT_ID,141            "auth_token": AUTH_TOKEN,142            "city_ids": CITY_IDS,143            "geocode": "",144            "min_bed": "-1", "max_bed": "100",145            "min_bath": "-1", "max_bath": "10",146            "min_rate": "0", "max_rate": "100000",147            "property_types": "apartments, houses",148            "order": "min_rate ASC",149            "limit": "66", "offset": "0",150            "count": "false",151            "show_all_properties": "true",152        }153        data = self.get(API, params=params).json()154        return data if isinstance(data, list) else []155156    def fetch(self) -> list[Listing]:157        listings: list[Listing] = []158        seen: set = set()159        for i, b in enumerate(self._search()):160            if i >= self.max_buildings:161                break162            try:163                bid = b.get("id")164                if bid in seen:165                    continue166                seen.add(bid)167                addr = b.get("address") or {}168                if (addr.get("province_code") or "").upper() != "QC":169                    continue170                if int(b.get("availability_count") or 0) <= 0:171                    continue             # aucune unité disponible172                listings.extend(self._parse_building(b))173            except Exception:174                continue175        return listings176177    # -- rangées de suites du gabarit Rentsync (partagé avec Douek) -------------178    @staticmethod179    def _suite_rows(soup: BeautifulSoup) -> list[dict]:180        """Extrait les rangées div.suite : id stable (modal), type, chambres,181        salles de bain, prix, pi², photos propres à la suite."""182        rows: list[dict] = []183        for div in soup.select("div.suite"):184            modal = div.select_one('a.open-suite-modal[href^="#modal-suite-"]')185            m = _MODAL_RE.search(modal.get("href", "")) if modal else None186            if not m:187                continue188            row: dict = {"id": m.group(1)}189            type_el = div.select_one(".suite-type")190            row["type"] = _clean(type_el.get_text(" ", strip=True)191                                 if type_el else "")192            for field, sel in (("bed", ".suite-bed .value"),193                               ("bath", ".suite-bath .value"),194                               ("rate", ".suite-rate .value"),195                               ("sqft", ".suite-sqft .value")):196                el = div.select_one(sel)197                row[field] = _clean(el.get_text(" ", strip=True)) if el else ""198            photos = [a.get("href") or ""199                      for a in div.select("a.suite-photo[href]")]200            row["photos"] = [u for u in dict.fromkeys(photos)201                             if u.startswith("http")][:25]202            rows.append(row)203        return rows204205    def _row_to_listing(self, row: dict, *, url: str, name: str, address: str,206                        sector: str, city: str, description: str = "",207                        amenities: list[str] | None = None,208                        images: list[str] | None = None,209                        pets: str | None = None, details: dict | None = None,210                        lat: float | None = None,211                        lng: float | None = None) -> Listing:212        label = row["type"]213        # Type d'unité : « 3.5 » dans le libellé sinon nombre de chambres214        unit_type = ""215        hm = _HALF_RE.search(label)216        if hm:217            unit_type = f"{hm.group(1)}½"218        else:219            try:220                unit_type = _BED_TYPE.get(int(row.get("bed") or ""), "")221            except (TypeError, ValueError):222                # libellé Rentsync « 2 Bed 1 Bath » ou « 2 Bedroom »223                bm = re.search(r"(\d+)\s*Bed", label, re.I)224                if bm:225                    unit_type = _BED_TYPE.get(int(bm.group(1)), "")226                elif re.search(r"bachelor|studio", label, re.I):227                    unit_type = "Studio"228229        price = None230        price_label = ""231        digits = re.sub(r"[^\d.]", "", row.get("rate") or "")232        if digits:233            try:234                price = float(digits)235            except ValueError:236                price = None237            price_label = f"À partir de {row['rate']}/mois"238        if price is not None and not (100 <= price <= 20000):239            price = None240241        baths = (row.get("bath") or "").strip()242        try:243            bathrooms = float(baths) if baths else None244        except ValueError:245            bathrooms = None246247        sq = re.sub(r"[^\d.]", "", row.get("sqft") or "")248        try:249            sqft = float(sq) if sq else None250        except ValueError:251            sqft = None252253        return Listing(254            source=self.source_id,255            external_id=str(row["id"]),256            url=url,257            title=f"{name} — {label}" if label else name,258            address=address,259            sector=sector,260            city=city,261            unit_type=unit_type,262            bathrooms=bathrooms,263            price=price,264            price_label=price_label,265            area_sqft=sqft,266            pets=pets,267            description=description,268            amenities=list(amenities or []),269            details=dict(details or {}),270            images=row.get("photos") or list(images or []),271            lat=lat,272            lng=lng,273        )274275    # -- fiche immeuble : suites rendues serveur --------------------------------276    def _parse_building(self, b: dict) -> list[Listing]:277        url = (b.get("permalink") or "").strip()278        if not url:279            return []280281        addr = b.get("address") or {}282        name = _clean(b.get("name") or "")283        address = _clean(addr.get("address") or "")284        city = _clean(addr.get("city") or "") or "Montréal"285        postal = _clean(addr.get("postal_code") or "")286        if address:287            address = f"{address}, {city}, QC" + (f" {postal}" if postal288                                                  else "")289        sector = _clean(addr.get("neighbourhood") or "")290        if sector.isupper():291            sector = sector.title()292        if sector.lower() in ("", city.lower(), "montreal", "montréal"):293            sector = ""294295        description = _clean((b.get("details") or {}).get("overview")296                             or "")[:600]297        pets = None298        if isinstance(b.get("pet_friendly"), bool):299            pets = "oui" if b["pet_friendly"] else "non"300301        details: dict = {}302        contact = b.get("contact") or {}303        cinfo = {}304        if _clean(contact.get("phone") or ""):305            cinfo["phone"] = _clean(contact["phone"])306        if _clean(contact.get("email") or ""):307            cinfo["email"] = _clean(contact["email"])308        if cinfo:309            details["contact"] = cinfo310311        geo = b.get("geocode") or {}312        try:313            lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))314        except (TypeError, ValueError):315            lat = lng = None316317        html = self.get(url).text318        soup = BeautifulSoup(html, "html.parser")319320        amenities = [el.get_text(" ", strip=True)321                     for el in soup.select(".amenities .amenity-holder, "322                                           ".amenity-holder")]323        amenities = [a for a in dict.fromkeys(amenities) if a][:25]324325        # Galerie de l'immeuble (dédupliquée par nom de fichier)326        images: list[str] = []327        seen_files: set[str] = set()328        for u in _GALLERY_RE.findall(html):329            fname = u.rsplit("/", 1)[-1]330            if fname not in seen_files:331                seen_files.add(fname)332                images.append(u)333        images = images[:25]334335        return [self._row_to_listing(336            row, url=url, name=name, address=address, sector=sector,337            city=city, description=description, amenities=amenities,338            images=images, pets=pets, details=details, lat=lat, lng=lng)339            for row in self._suite_rows(soup)]340
Files main
Menu

Theme