SPB Git

Repository Public

utile.py 17.5 KB 429 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/utile.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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/utile.py : connecteur UTILE (utile.org)91#   OBNL de logement étudiant. Immeubles à Montréal (Angus, Griffintown,92#   Milton-Parc, Saint-Laurent, Saint-Patrick, Parc La Fontaine,93#   Des Carrières, Hutchison…), Québec (Cité universitaire, Saint-Sacrement),94#   Trois-Rivières (Jean-XXIII), Rimouski et Sherbrooke (en développement).95#   Site Webflow rendu serveur : une annonce par immeuble ×96#   typologie (Studio, 2 bedroom...) avec prix "From $x/month", photos de la97#   galerie (templates Webflow encodés en URL) et statut de l'immeuble98#   (For rent / Fully rented — balises conditionnelles w-condition-invisible).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104import urllib.parse105106from bs4 import BeautifulSoup107108from ..schema import Listing, parse_price, strip_accents109from .base import BaseConnector110111BASE = "https://www.utile.org"112INDEX_URL = f"{BASE}/en/immeubles"113114STATUSES = ("For rent", "Fully rented", "Under construction", "In development")115116# Ville affichée en fin d'adresse -> nom canonique Lou-Ka (clé sans accents)117_CITY_CANON = {118    "montreal": "Montréal",119    "quebec city": "Québec",120    "quebec": "Québec",121    "trois-rivieres": "Trois-Rivières",122    "sherbrooke": "Sherbrooke",123    "rimouski": "Rimouski",124}125126# Slug d'équipement (page /en/inclusions/<immeuble>---inclusions) -> libellé FR127_EQUIP_FR = {128    "cuisiniere": "Cuisinière",129    "refrigerateur": "Réfrigérateur",130    "lave-vaiselles": "Lave-vaisselle",131    "lave-vaisselle": "Lave-vaisselle",132    "micro-ondes": "Micro-ondes",133    "chauffage": "Chauffage",134    "eau-chaude": "Eau chaude",135    "electricite": "Électricité",136    "internet": "Internet",137    "climatisation": "Climatisation",138    "echangeur-dair": "Échangeur d'air",139    "portail-locataire-en-ligne": "Portail locataire en ligne",140    "buanderie": "Buanderie",141    "salle-de-lavage": "Salle de lavage",142    "gym": "Gym",143    "terrasse": "Terrasse",144    "terrasse-sur-le-toit": "Terrasse sur le toit",145    "ascenseur": "Ascenseur",146    "ascenseurs": "Ascenseurs",147    "ascenceurs": "Ascenseurs",     # coquille dans le slug de la source148    "air-climatise": "Air climatisé",149    "salle-de-colis-securisee": "Salle de colis sécurisée",150    "cour-interieure": "Cour intérieure",151    "salle-commune": "Salle commune",152    "salle-detude": "Salle d'étude",153    "rangement": "Rangement",154    "casier-de-rangement": "Casier de rangement",155    "stationnement-exterieur": "Stationnement extérieur",156    "stationnement-souterrain": "Stationnement souterrain",157    # « stationnement à vélo » ne doit pas être pris pour un stationnement158    # auto par la normalisation -> libellé neutre159    "stationnement-a-velo-interieur": "Espace vélos intérieur",160    "stationnement-a-velo-exterieur": "Espace vélos extérieur",161    "systeme-de-puces-electroniques-et-de-cameras":162        "Système de puces électroniques et de caméras",163    "presence-dun-gestionnaire-sur-place": "Présence d'un gestionnaire sur place",164    "abonnement-annuel-a-lapplication-partage-club":165        "Abonnement annuel à l'application Partage Club",166    "entretien-menager": "Entretien ménager",167}168169# Équipements « Not Included » exprimables sans risque de faux positif170_EQUIP_NEG = {171    "meubles": "Non meublé",172    "internet": "Internet non inclus",173    "chauffage": "Chauffage non inclus",174    "electricite": "Électricité non incluse",175    "eau-chaude": "Eau chaude non incluse",176    "climatisation": "Climatisation non incluse",177}178179180def _equip_label(slug: str) -> str:181    return _EQUIP_FR.get(slug, slug.replace("-", " ").capitalize())182183184_TYPE_MAP = {185    "studio": "Studio",186    "mezzanine studio": "Studio (mezzanine)",187    "1 bedroom": "3½",188    "2 bedroom": "4½",189    "3 bedroom": "5½",190    "4 bedroom": "6½",191}192193194def _visible(el) -> bool:195    """Webflow masque les éléments conditionnels avec w-condition-invisible."""196    for node in [el] + list(el.parents)[:6]:197        if node is None or not hasattr(node, "get"):198            break199        if "w-condition-invisible" in (node.get("class") or []):200            return False201    return True202203204def _unit_type(label: str) -> str:205    key = re.sub(r"\s+", " ", (label or "").strip().lower())206    for k, v in _TYPE_MAP.items():207        if key.startswith(k):208            return v209    m = re.search(r"(\d)\s*bedroom", key)210    if m:211        return f"{int(m.group(1)) + 2}½"212    return label.strip()213214215class UtileConnector(BaseConnector):216    source_id = "utile"217    request_delay = 0.6218    max_buildings = 20       # garde-fou219    max_incl_requests = 30   # plafond de vraies requêtes « inclusions »220221    def fetch(self) -> list[Listing]:222        listings: list[Listing] = []223        self._incl_requests = 0224        try:225            index = self.get(INDEX_URL).text226        except Exception:227            return listings228        slugs = list(dict.fromkeys(229            re.findall(r'href="/en/immeubles/([a-z0-9\-]+)"', index)))230231        for slug in slugs[:self.max_buildings]:232            try:233                listings.extend(self._fetch_building(slug))234            except Exception:235                continue236        return listings237238    # -- inclusions d'un immeuble (page CMS Webflow « nest ») ----------------------239    def _fetch_inclusions(self, url: str) -> dict:240        """Retourne {groupe: [slugs d'équipement]} depuis la page inclusions.241242        Groupes Webflow : equipement-appartement (inclus dans tous les243        appartements), equipement-immeuble (dans l'immeuble),244        equipement-supplement (en sus), equipement-exclus (non inclus).245        """246        html = self.get(url).text247        soup = BeautifulSoup(html, "html.parser")248        groups: dict[str, list[str]] = {}249        for lst in soup.select("[fs-cmsnest-collection]"):250            name = lst.get("fs-cmsnest-collection") or ""251            slugs: list[str] = []252            for a in lst.select('a[href*="/equipement/"]'):253                m = re.search(r"/equipement/([a-z0-9\-]+)", a.get("href") or "")254                if m and m.group(1) not in slugs:255                    slugs.append(m.group(1))256            if name and slugs:257                groups[name] = slugs258        return groups259260    # -- un immeuble -------------------------------------------------------------261    def _fetch_building(self, slug: str) -> list[Listing]:262        url = f"{BASE}/en/immeubles/{slug}"263        html = self.get(url).text264        soup = BeautifulSoup(html, "html.parser")265266        # Secteur + adresse (bloc c-location-tag du hero)267        sector = address = ""268        infos = soup.select(".c-location-tag__adress-wrapper "269                            ".c-location-tag__info")270        if len(infos) >= 2:271            sector = infos[0].get_text(" ", strip=True)272            address = infos[1].get_text(" ", strip=True)273        elif infos:274            address = infos[0].get_text(" ", strip=True)275276        # Marqueur carte « main-building-data » : adresse + lat/lng structurés277        lat = lng = None278        mb = soup.select_one(".main-building-data")279        if mb:280            if not address:281                address = (mb.get("data-address") or "").strip()282            try:283                lat = float(mb.get("data-lat") or "")284                lng = float(mb.get("data-lng") or "")285            except (TypeError, ValueError):286                lat = lng = None287288        # Ville = dernier segment de l'adresse (« Montreal », « Québec City »,289        # « Trois-Rivières », « Rimouski »…), canonisée — depuis l'expansion290        # provinciale, tous les immeubles UTILE sont couverts.291        raw_city = address.rsplit(",", 1)[-1].strip() if "," in address else ""292        city = _CITY_CANON.get(strip_accents(raw_city.lower()), "")293        if not city:294            return []            # ville non reconnue : ne rien inventer295        address = f"{address.rsplit(',', 1)[0].rstrip()}, {city}"296297        # Statut de l'immeuble : tag visible du hero (c-location-tag).298        # Le reste de la page (menu immeubles, cartes « autres projets »)299        # contient les tags de TOUS les immeubles : ne pas les balayer.300        status = ""301        hero = soup.select_one(".c-location-tag__content-wrapper")302        for el in (hero or soup).find_all(string=re.compile(303                r"^(For rent|Fully rented|Under construction|In development)$")):304            if _visible(el.find_parent()):305                status = el.strip()306                if hero is not None:307                    break308        if status in ("Under construction", "In development"):309            return []            # pas encore en location310311        name_el = soup.select_one("h1")312        building = name_el.get_text(" ", strip=True) if name_el else slug313314        # Stats du hero (« Renting from », « Number of apartments »...)315        stats: dict[str, str] = {}316        for st in soup.select(".c-building-stat"):317            if not _visible(st):318                continue319            t = st.select_one(".c-building-stat__title")320            v = st.select_one(".c-building-stat__text")321            if t and v and v.get_text(strip=True):322                stats[t.get_text(" ", strip=True)] = v.get_text(" ", strip=True)323324        # Description (og:description) + début de location annoncé325        desc = ""326        og = soup.find("meta", attrs={"property": "og:description"})327        if og and og.get("content"):328            desc = og["content"].strip()[:600]329        renting_from = stats.get("Renting from", "")330        if renting_from:331            desc = (f"En location à partir du : {renting_from}. " + desc)[:600]332333        # Inclusions par immeuble (page CMS /en/inclusions/<slug>---inclusions,334        # via le cache détail : 1 vraie requête par immeuble et par changement)335        amenities = ["Logement étudiant", "Bail 12 mois"]336        link = soup.select_one('a.c-inclusions__link[href^="/en/inclusions/"]')337        groups: dict = {}338        if link:339            incl_url = BASE + link["href"]340            key = hashlib.sha1(html.encode("utf-8")).hexdigest()341342            def _fetch_incl() -> dict:343                if self._incl_requests >= self.max_incl_requests:344                    return {}345                self._incl_requests += 1346                return self._fetch_inclusions(incl_url)347348            try:349                groups = self.detail(f"bldg:{slug}", key, _fetch_incl) or {}350            except Exception:351                groups = {}352        for eq in groups.get("equipement-appartement", []):353            amenities.append(_equip_label(eq))354        for eq in groups.get("equipement-immeuble", []):355            amenities.append(_equip_label(eq))356        for eq in groups.get("equipement-supplement", []):357            amenities.append(f"{_equip_label(eq)} (en sus)")358        for eq in groups.get("equipement-exclus", []):359            if eq in _EQUIP_NEG:360                amenities.append(_EQUIP_NEG[eq])361        if len(amenities) == 2:      # repli : énoncé général du site362            amenities += ["Non meublé",363                          "Cuisinière et réfrigérateur inclus"]364        amenities = list(dict.fromkeys(amenities))365366        avail_map = {"For rent": "En location",367                     "Fully rented": "Complet (prochaine période de location)"}368        building_avail = avail_map.get(status, status)369370        out: list[Listing] = []371        for card in soup.select(".c-building-apartment__collection-item"):372            try:373                title_el = card.select_one(".c-apartment-details__title")374                price_el = card.select_one(".c-apartment-price__content")375                if not title_el or not price_el:376                    continue377                typology = title_el.get_text(" ", strip=True)378                price_label = price_el.get_text(" ", strip=True)379                from_el = card.select_one(".c-apartment-price__title")380                if from_el and from_el.get_text(strip=True):381                    price_label = (f"{from_el.get_text(strip=True)} "382                                   f"{price_label}")383                price = parse_price(384                    re.sub(r"\$(\d+)", r"\1$", price_label))385386                # "Complet" affiché sur la carte ?387                complet = any(388                    _visible(s.find_parent()) for s in389                    card.find_all(string=re.compile(r"^Complet$")))390391                # Photos : image de la carte + galerie rendue + template392                # Webflow (galerie modale, encodée en URL dans393                # <script type="text/x-wf-template">)394                images: list[str] = []395                for img in card.select("img"):396                    src = img.get("src") or ""397                    if src.startswith("http") and not src.endswith(".svg"):398                        images.append(src)399                for tmpl in card.select('script[type="text/x-wf-template"]'):400                    decoded = urllib.parse.unquote(tmpl.get_text())401                    images.extend(re.findall(402                        r'https://cdn\.prod\.website-files\.com/'403                        r'[^"\s]+?\.(?:jpe?g|png|webp)', decoded))404                images = [u for u in dict.fromkeys(images)405                          if "-p-" not in u]      # variantes responsive406407                type_slug = re.sub(r"[^a-z0-9]+", "-", typology.lower()).strip("-")408                out.append(Listing(409                    source=self.source_id,410                    external_id=f"{slug}-{type_slug}",411                    url=url,412                    title=f"UTILE {building} — {typology}",413                    address=address,414                    sector=sector,415                    city=city,416                    unit_type=_unit_type(typology),417                    price=price,418                    price_label=price_label,419                    availability="Complet" if complet else building_avail,420                    description=desc,421                    amenities=list(amenities),422                    images=images,423                    lat=lat,424                    lng=lng,425                ))426            except Exception:427                continue428        return out429
Files main
Menu

Theme