SPB Git

Repository Public

cinq_etoiles.py 9.7 KB 231 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cinq_etoiles.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/cinq_etoiles.py : connecteur Gestion Cinq Étoiles91#   (appartementslocatifs.ca) — 5 immeubles locatifs neufs à Blainville :92#   L'Émeraude (842 Curé-Labelle), Le Cassiopée (832 Curé-Labelle), L'Azur93#   (33 Gaëtan-Mailhiot), Le Célesta (11 Gaëtan-Mailhiot), L'Élysée94#   (40 Gaëtan-Mailhiot). Site GoDaddy Website Builder rendu serveur : la95#   page d'accueil liste les immeubles (nav), chaque page immeuble affiche96#   « <NOM> à partir de N$/mois », l'adresse civique, la ligne des97#   typologies (« Logements 3 1/2 et 3 1/2 + den et 4 1/2 ») et les98#   inclusions. Photos sur le CDN img1.wsimg.com (variantes /:/rs=…99#   dédupliquées). Granularité TYPOLOGIE par immeuble ; le prix « à partir100#   de » n'est associé qu'à la plus petite typologie (jamais inventé).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing109from .base import BaseConnector110111BASE = "https://appartementslocatifs.ca"112CITY = "Blainville"113114# « L'AZUR, à partir de 1575$ » / « LE CASSIOPÉE À PARTIR DE 1510$/ MOIS »115NAME_PRICE_RE = re.compile(116    r"^(.{2,40}?),?\s*à partir de\s*([\d  ]{3,6})\s*\$", re.I)117# ligne composée uniquement de typologies : « Logements 3 1/2 + den et 4 1/2 »118TYPES_LINE_RE = re.compile(119    r"^(?:Logements?\s+)?((?:\d\s*(?:1/2|½)(?:\s*\+\s*den)?)"120    r"(?:\s*(?:et|,)\s*\d\s*(?:1/2|½)(?:\s*\+\s*den)?)*)\s*$", re.I)121TYPE_TOKEN_RE = re.compile(r"(\d)\s*(?:1/2|½)(\s*\+\s*den)?", re.I)122# « 33 Gaëtan-Mailhiot, Blainville, QC , J7C 0W9 » / « Situé au 842, boul. … »123ADDR_RE = re.compile(124    r"^(?:Situé au\s+)?(\d{1,5}[^\n]{3,60}?),?\s*Blainville\b", re.I)125IMG_RE = re.compile(126    r"(?:https?:)?//img1\.wsimg\.com/isteam/ip/[^\"'\s\\,)]+?\.(?:jpe?g|png|webp)",127    re.I)128129# l'adresse de L'Élysée n'apparaît que sur la page d'accueil130FALLBACK_ADDR = {"l%C3%A9lys%C3%A9e": "40 Gaëtan-Mailhiot"}131EXCLUDED_PATHS = {"/", "/service"}132133134class CinqEtoilesConnector(BaseConnector):135    source_id = "cinq_etoiles"136    request_delay = 0.8137138    def fetch(self) -> list[Listing]:139        listings: list[Listing] = []140        try:141            home = self.get(BASE + "/").text142        except Exception:143            return listings144        soup = BeautifulSoup(home, "html.parser")145        paths = []146        for a in soup.select("a[href]"):147            href = a.get("href") or ""148            if (href.startswith("/") and href not in EXCLUDED_PATHS149                    and href not in paths and "#" not in href):150                paths.append(href)151        for path in paths:152            try:153                listings.extend(self._building(path))154            except Exception:155                continue                       # une page cassée ne bloque pas156        return listings157158    # -- page immeuble : nom, prix « à partir de », adresse, typologies --------159    def _building(self, path: str) -> list[Listing]:160        url = BASE + path161        html = self.get(url).text162        soup = BeautifulSoup(html, "html.parser")163        for tag in soup.select("title, script, style"):164            tag.decompose()                    # le <title> contient des typologies165        lines = [ln for ln in soup.get_text("\n", strip=True).split("\n") if ln]166167        name, price, price_label = "", None, ""168        address = FALLBACK_ADDR.get(path.lstrip("/"), "")169        types: list[str] = []170        amenities: list[str] = []171        for i, line in enumerate(lines):172            m = NAME_PRICE_RE.match(line)173            if m and not name:174                name = m.group(1).strip(" ,–-").title()175                price_label = line.strip()176                try:177                    price = float(re.sub(r"[  ]", "", m.group(2)))178                except ValueError:179                    price = None180            m = TYPES_LINE_RE.match(line)181            if m and not types:182                types = [f"{t[0]}½" + (" + DEN" if t[1] else "")183                         for t in TYPE_TOKEN_RE.findall(m.group(1))]184            m = ADDR_RE.match(line)185            if m and not FALLBACK_ADDR.get(path.lstrip("/")):186                address = m.group(1).strip(" ,")187            if line.lower().startswith("inclusions"):188                rest = line.split(":", 1)[-1].strip() \189                    if ":" in line else line[len("Inclusions"):].strip()190                if len(rest) > 3:191                    amenities.append(rest)192                for nxt in lines[i + 1:i + 4]:193                    if re.match(r"Copyright|Powered|This website", nxt, re.I):194                        break195                    if len(nxt) > 3:196                        amenities.append(nxt)197        if not name or not types:198            return []199200        # photos : dédupliquées sur le chemin de base (avant les variantes /:/)201        images: list[str] = []202        for u in IMG_RE.findall(html):203            full = ("https:" + u) if u.startswith("//") else u204            if full not in images and not re.search(r"logo|favicon", full, re.I):205                images.append(full)206207        # une annonce par typologie ; « à partir de » = plus petite typologie208        out: list[Listing] = []209        for i, ut in enumerate(types):210            first = (i == 0)211            slug = re.sub(r"[^a-z0-9]+", "-",212                          name.lower().replace("é", "e").replace("è", "e")213                          .replace("'", "")).strip("-")214            out.append(Listing(215                source=self.source_id,216                external_id=f"{slug}-{ut.replace('½', '.5').replace(' + DEN', 'den').replace(' ', '')}",217                url=url,218                title=f"{name} — {ut}",219                address=address,220                city=CITY,221                unit_type=ut,222                price=price if first else None,223                price_label=(price_label if first else ""),224                availability="Disponible",225                amenities=list(amenities),226                details=({"price_from": True, "building": name}227                         if first and price else {"building": name}),228                images=images[:15],229            ))230        return out231
Files main
Menu

Theme