SPB Git

Repository Public

fluet.py 9.7 KB 233 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/fluet.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/fluet.py : connecteur Groupe Fluet (groupefluet.com)91#   Gestionnaire de Saint-Hyacinthe — logements pour préretraités/retraités92#   autonomes (Manoir des Cascades, Seigneurie des Pères, Le Notre-Dame93#   phases I-II-III) + triplex rue Noiseux à Sainte-Marie-Madeleine.94#   Site Wix MAIS rendu serveur : le HTML brut contient le texte des pages —95#   pas besoin de rendu JS. Une page par immeuble, typologies dans le texte96#   (« Offre des logements : 3½, 4½ et 5 ½ »).97#   Granularité : une annonce par immeuble × typologie (aucun prix publié).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type106from .base import BaseConnector107108BASE = "https://www.groupefluet.com"109110# (slug de page, nom d'immeuble, adresse repli, ville, typologies repli)111PAGES = [112    ("manoirdescascades", "Manoir des Cascades",113     "Saint-Hyacinthe", "Saint-Hyacinthe", ["2½", "3½", "4½"]),114    ("seigneurie", "Seigneurie des Pères",115     "2250, rue Girouard Ouest, Saint-Hyacinthe", "Saint-Hyacinthe",116     ["3½", "4½", "5½"]),117    ("copie-de-le-notre-dame", "Le Notre-Dame — Phase 1",118     "900, avenue Raymond, Saint-Hyacinthe", "Saint-Hyacinthe",119     ["3½", "4½", "5½"]),120    ("lenotredame2", "Le Notre-Dame — Phase 2",121     "920, avenue Raymond, Saint-Hyacinthe", "Saint-Hyacinthe",122     ["3½", "4½", "5½"]),123    ("lenotredame3", "Le Notre-Dame — Phase 3",124     "910, avenue Raymond, Saint-Hyacinthe", "Saint-Hyacinthe",125     ["3½", "4½", "5½"]),126    ("general-6", "Triplex rue Noiseux",127     "Rue Noiseux, Sainte-Marie-Madeleine", "Sainte-Marie-Madeleine", ["4½"]),128]129130# « Offre des logements : 3½, 4½ et 5 ½ » / « 19 unités de 2½, 3½ et 4½ »131OFFER_RE = re.compile(132    r"(?:Offre des logements\s*:?|unit[ée]s de)\s*([\d\s½,/et]+)", re.I)133UNIT_TOKEN_RE = re.compile(r"\b(\d)\s*(?:½|1/2)")134IMG_RE = re.compile(135    r"https://static\.wixstatic\.com/media/[\w~%]+\.(?:jpe?g|png|webp)"136    r"/v1/fill/[^\"\s\\)]+\.(?:jpe?g|png|webp)", re.I)137PHONE_RE = re.compile(r"\(?(\d{3})\)?[\s.\-](\d{3})[\s.\-](\d{4})")138139140class FluetConnector(BaseConnector):141    source_id = "fluet"142    request_delay = 0.8143144    def fetch(self) -> list[Listing]:145        listings: list[Listing] = []146        for slug, name, addr_fallback, city, types_fallback in PAGES:147            try:148                listings.extend(self._fetch_building(149                    slug, name, addr_fallback, city, types_fallback))150            except Exception:151                continue152        return listings153154    def _fetch_building(self, slug: str, name: str, addr_fallback: str,155                        city: str, types_fallback: list[str]) -> list[Listing]:156        url = f"{BASE}/{slug}"157        html = self.get(url).text158        soup = BeautifulSoup(html, "html.parser")159        # Wix : retirer les scripts/JSON embarqués avant d'extraire le texte160        for tag in soup(["script", "style", "noscript"]):161            tag.decompose()162        text = re.sub(r"[​]", "", soup.get_text("\n", strip=True))163        flat = re.sub(r"\s+", " ", text)164165        # typologies offertes (texte de la page, sinon repli configuré) —166        # attention au pied de page générique « … à Saint-Hyacinthe 3 ½, 4 ½,167        # 5 ½ » : on ne lit que le motif « Offre des logements/unités de »168        m = OFFER_RE.search(flat)169        unit_types = list(dict.fromkeys(170            normalize_unit_type(f"{n}½")171            for n in UNIT_TOKEN_RE.findall(m.group(1)))) if m else []172        if not unit_types:173            unit_types = list(types_fallback)174175        # adresse civique dans la prose (« Situé 920 Avenue Raymond à176        # Saint-Hyacinthe », « situé au 900, 910, 920 avenue Raymond »)177        address = addr_fallback178        m = re.search(179            r"[Ss]itu[ée]?e?\s+(?:au\s+)?(\d{1,5}[^.!<>]{3,70}?)\s+"180            r"[àa]\s+(Saint-Hyacinthe|Sainte-Marie-Madeleine)", flat)181        if m:182            address = f"{m.group(1).strip().rstrip(',')}, {m.group(2)}"183184        # description : premier paragraphe substantiel après le nom185        description = ""186        for chunk in text.split("\n"):187            if len(chunk) > 140 and "cookie" not in chunk.lower():188                description = chunk.strip()[:900]189                break190191        # commodités : puces après « Ce que nos logements vous réservent »192        # (Manoir/Seigneurie/Triplex) ou après « Offre des logements » (LND)193        amenities: list[str] = []194        seen_head = False195        for chunk in text.split("\n"):196            c = chunk.strip()197            if "vous réservent" in c or OFFER_RE.search(c):198                seen_head = True199                amenities = []      # repartir de l'en-tête le plus proche200                continue201            if seen_head and 8 < len(c) < 160 and not c.startswith("©") \202                    and "press to zoom" not in c.lower():203                amenities.append(c)204            if len(amenities) >= 14 or (seen_head and c.startswith("©")):205                break206        if re.search(r"pr[ée]retrait[ée]s|retrait[ée]s autonomes", flat, re.I):207            amenities.insert(0, "Clientèle préretraitée/retraitée autonome")208209        contact: dict = {}210        m = PHONE_RE.search(flat)211        if m:212            contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"213214        images = [u for u in dict.fromkeys(IMG_RE.findall(html))215                  if not re.search(r"w_(?:1?\d?\d|2\d\d)[,%]|logo", u, re.I)][:16]216217        out: list[Listing] = []218        for ut in unit_types:219            out.append(Listing(220                source=self.source_id,221                external_id=f"{slug}-{ut.replace('½', '.5')}",222                url=url,223                title=f"{name} — {ut}",224                address=address,225                city=city,226                unit_type=ut,227                description=description,228                amenities=list(dict.fromkeys(amenities))[:15],229                details={"contact": dict(contact)} if contact else {},230                images=images,231            ))232        return out233
Files main
Menu

Theme