SPB Git

Repository Public

habitations_sf.py 12.7 KB 318 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/habitations_sf.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# 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/habitations_sf.py : connecteur Les Habitations SF (S&F Gestion)91#   (leshabitationssf.com — Saint-Charles-Borromée/Joliette, Lanaudière).92#   Site Wix : les annonces sont des pages dynamiques /copy-of-location/<slug>93#   (collection Wix), rendues côté serveur — le HTML contient le titre, le94#   statut (« Disponible »/« Loué »), chambres/sdb/pi², le prix « … $ / mois »,95#   la description riche (ligne « Adresse: … ») et la galerie wixstatic.96#   Index = liens du répéteur de la page d'accueil ; external_id = slug ;97#   fiches détail via cache BD (clé = hash du répéteur : tout changement98#   d'accueil déclenche la relecture des fiches).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104import unicodedata105from urllib.parse import unquote106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://www.leshabitationssf.com"113LIST_URL = f"{BASE}/"114115# id du média wixstatic (« 5ae170_…~mv2.png ») pour dédupliquer la galerie116_MEDIA_ID = re.compile(r"/media/([^/]+~mv2\.\w+)")117118_CITIES = [119    ("saint-charles", "Saint-Charles-Borromée"),120    ("st-charles", "Saint-Charles-Borromée"),121    ("notre-dame-des-prairies", "Notre-Dame-des-Prairies"),122    ("saint-felix", "Saint-Félix-de-Valois"),123    ("st-felix", "Saint-Félix-de-Valois"),124    ("joliette", "Joliette"),125    ("piedmont", "Piedmont"),126    ("saint-paul", "Saint-Paul"),127]128129_STATUTS_PARTIS = re.compile(r"(?i)^(lou[ée]e?|non disponible|r[ée]serv[ée]e?)$")130131132def _strip_accents(s: str) -> str:133    return "".join(c for c in unicodedata.normalize("NFD", s)134                   if unicodedata.category(c) != "Mn")135136137def _slug(s: str) -> str:138    s = _strip_accents(unquote(s).lower())139    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")140141142def _find_city(txt: str) -> str:143    low = re.sub(r"[\s_]+", "-", _strip_accents(txt.lower()))144    for key, name in _CITIES:145        if key in low:146            return name147    return ""148149150class HabitationsSFConnector(BaseConnector):151    source_id = "habitations_sf"152    request_delay = 0.8153    max_details = 25    # garde-fou fiches détail (vraies requêtes par sync)154155    def fetch(self) -> list[Listing]:156        html = self.get(LIST_URL).text157        soup = BeautifulSoup(html, "html.parser")158        # liens du répéteur d'accueil (ordre conservé, dédupliqués)159        hrefs: list[str] = []160        for a in soup.select('a[href*="copy-of-location/"]'):161            href = a["href"]162            if href.startswith("/"):163                href = BASE + href164            if href not in hrefs:165                hrefs.append(href)166        # clé de cache : hash des liens + du texte du répéteur (prix affichés) —167        # tout changement sur l'accueil déclenche la relecture des fiches168        idx_txt = " ".join(hrefs) + re.sub(169            r"\s+", " ",170            " ".join(el.get_text(" ", strip=True)171                     for el in soup.select('[data-testid="richTextElement"]')))172        index_key = hashlib.sha1(idx_txt.encode("utf-8")).hexdigest()173174        self._fetched = 0175        listings: list[Listing] = []176        for href in hrefs:177            ext = _slug(href.rsplit("/", 1)[-1])178            if not ext:179                continue180            try:181                payload = self.detail(ext, index_key,182                                      lambda u=href: self._fetch_detail(u))183            except Exception:184                continue185            lst = self._build(ext, href, payload)186            if lst is not None:187                listings.append(lst)188        return listings189190    # -- fiche détail (page dynamique Wix) ----------------------------------------191    def _fetch_detail(self, url: str) -> dict:192        if self._fetched >= self.max_details:193            raise RuntimeError("budget de fiches détail atteint")194        self._fetched += 1195        html = self.get(url).text196        soup = BeautifulSoup(html, "html.parser")197        out: dict = {}198199        title_el = soup.find("title")200        out["title"] = re.sub(r"\s+", " ", title_el.get_text(strip=True)) if title_el else ""201202        rts = [re.sub(r"[​]", "",203                      re.sub(r"\s+", " ", el.get_text(" ", strip=True))).strip()204               for el in soup.select('[data-testid="richTextElement"]')]205        rts = [t for t in rts if t]206207        # statut de l'unité (« Disponible » / « Loué »)208        for t in rts:209            if re.match(r"(?i)^(disponible|lou[ée]e?|non disponible|r[ée]serv[ée]e?)$", t):210                out["status"] = t211                break212213        # champs structurés : valeur qui précède « Chambre(s) », « Salle(s) de214        # bain », « Pieds² » ; prix = « <n> $ / mois » dans la séquence215        def before(label_re: str) -> str:216            for i, t in enumerate(rts):217                if re.match(label_re, t, re.I) and i > 0:218                    return rts[i - 1]219            return ""220        out["bedrooms"] = before(r"^chambre")221        out["bathrooms"] = before(r"^salle\(s\) de bain|^salles? de bain")222        out["sqft"] = before(r"^pieds")223        joined = " ".join(rts)224        m = re.search(r"(\d[\d\s,.]*)\s*\$\s*/\s*mois", joined)225        if m:226            out["price_label"] = f"{m.group(1).strip()} $ / mois"227        else:                       # certaines fiches omettent le « $ »228            m = re.search(r"(\d{3,4})\s*/\s*mois", joined)229            if m:230                out["price_label"] = f"{m.group(1)} / mois"231232        # description riche = plus long bloc de texte (contient « Adresse: … »)233        long_txts = [el.get_text("\n", strip=True)234                     for el in soup.select('[data-testid="richTextElement"]')235                     if len(el.get_text(strip=True)) > 200]236        if long_txts:237            out["description"] = max(long_txts, key=len)[:1500]238239        # galerie : images wixstatic grand format, dédupliquées par id de média240        images, seen = [], set()241        for im in soup.find_all("img"):242            src = im.get("src") or ""243            if "wixstatic.com/media/" not in src:244                continue245            m_id = _MEDIA_ID.search(src)246            if not m_id or m_id.group(1) in seen:247                continue248            if not re.search(r"w_(9\d\d|\d{4,})", src):249                continue                     # vignettes/логos : trop petits250            seen.add(m_id.group(1))251            images.append(src)252        out["images"] = images[:20]253        return out254255    # -- assemblage ---------------------------------------------------------------256    def _build(self, ext: str, url: str, d: dict) -> Listing | None:257        if not d:258            return None259        if _STATUTS_PARTIS.match(d.get("status", "")):260            return None                      # unité louée/réservée261        title = d.get("title", "")262        desc = d.get("description", "")263264        # adresse : ligne « Adresse: rue de la Visitation, Saint-Charles-Borromée »265        address, city = "", ""266        m = re.search(r"Adresse\s*:\s*([^\n]+)", desc, re.I)267        if m:268            parts = [p.strip() for p in m.group(1).split(",") if p.strip()]269            city = _find_city(parts[-1]) if parts else ""270            address = ", ".join(parts[:-1]) if city and len(parts) > 1 else m.group(1).strip()271        if not city:272            city = _find_city(title) or _find_city(desc)273274        # disponibilité : ligne « DISPONIBLE DÈS LE 1ER AOUT 2025 » de la fiche275        availability = ""276        m_av = re.search(r"(DISPONIBLE\s+D[ÈE]S[^\n]*|DISPONIBLE\s+(?:LE|MAINTENANT)[^\n]*)",277                         desc, re.I)278        if m_av:279            availability = re.sub(r"\s+", " ", m_av.group(1)).strip()280        elif d.get("status"):281            availability = d["status"]282283        amenities: list[str] = []284        if d.get("bedrooms", "").replace("-", "").strip().isdigit() or \285                re.match(r"^\d+(-\d+)?$", d.get("bedrooms", "")):286            amenities.append(f"{d['bedrooms']} chambre(s)")287        if re.match(r"^\d+([.,]\d+)?$", d.get("bathrooms", "")):288            amenities.append(f"{d['bathrooms']} salle(s) de bain")289290        area = None291        if re.match(r"^\d{3,4}$", d.get("sqft", "")):292            area = float(d["sqft"])293294        price_label = d.get("price_label", "")295        if not price_label:296            # fiche multi-typologies : « 3 1/2 À PARTIR DE 1150$ … » — on297            # reprend la mention la plus basse (convention Lou-Ka « à partir de »)298            fromtags = re.findall(r"à partir de\s*(\d[\d\s]*)\s*\$", desc, re.I)299            if fromtags:300                lo = min(int(x.replace(" ", "")) for x in fromtags)301                price_label = f"À partir de {lo}$"302        return Listing(303            source=self.source_id,304            external_id=ext,305            url=url,306            title=title,307            address=address,308            city=city,309            unit_type=normalize_unit_type(title),310            price=parse_price(price_label),311            price_label=price_label,312            availability=availability,313            area_sqft=area,314            description=desc,315            amenities=amenities,316            images=d.get("images") or [],317        )318
Files main
Menu

Theme