SPB Git

Repository Public

sept_elements.py 10.8 KB 259 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/sept_elements.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/sept_elements.py : connecteur Les 7 Éléments91#   (condoles7elements.com — 1998, rue Marie-Anne-Gaudreau, Lebourgneuf,92#    Québec ; condos locatifs Propriétés Mach). Plateforme Vortex Solution93#    rendue serveur : la page d'accueil liste les unités disponibles en blocs94#    <div class="uniteItem"> (type 3½/4½, numéro d'unité, date de95#    disponibilité, plan PDF DATA/UNITE/<n>.pdf). Pas de prix affiché sur le96#    site — le plan PDF de chaque unité fournit par contre les superficies97#    (nette/brute/balcon), extraites par position avec pdfplumber via le98#    cache BD des pages détail. Sert aussi de classe de base au connecteur99#    `consolata` (La Consolata, même plateforme Vortex).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import io105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type110from .base import BaseConnector111112# éléments de navigation à exclure des listes <li> de commodités113_NAV_RE = re.compile(r"accueil|nous joindre|galerie|unit[ée]s|plans|"114                     r"disponibilit|english|fran[çc]ais|politique", re.I)115PHONE_RE = re.compile(r"\b(\d{3})[\s.\-](\d{3})[\s.\-](\d{4})\b")116117118class SeptElementsConnector(BaseConnector):119    source_id = "sept_elements"120    request_delay = 0.6121    max_details = 30     # garde-fou plans PDF (vraies requêtes par sync)122123    BASE = "https://www.condoles7elements.com"124    NAME = "Les 7 Éléments"125    ADDRESS = "1998, rue Marie-Anne-Gaudreau, Québec, G2K 0M3"126    SECTOR = "Lebourgneuf"127    CITY = "Québec"128129    def fetch(self) -> list[Listing]:130        listings: list[Listing] = []131        html = self.get(f"{self.BASE}/").text132        soup = BeautifulSoup(html, "html.parser")133        self._fetched = 0134135        # photos de l'immeuble (DATA/PHOTO/*.jpg, hors logos/icônes)136        images = []137        for u in dict.fromkeys(re.findall(138                r'(?:src|href)="((?:DATA/PHOTO|gx/m)/[^"]+'139                r"\.(?:jpe?g|png|webp))\"", html, re.I)):140            if re.search(r"logo|icon|favicon|Mob~", u, re.I):141                continue142            images.append(f"{self.BASE}/{u.lstrip('/')}")143        images = images[:20]144145        # commodités : listes <li> du contenu (filtrées de la navigation)146        amenities = []147        for li in soup.find_all("li"):148            txt = re.sub(r"\s+", " ", li.get_text(" ", strip=True))149            if txt and len(txt) < 80 and not li.find("a") \150                    and not _NAV_RE.search(txt) and txt not in amenities:151                amenities.append(txt)152        amenities = amenities[:20]153154        # contact (téléphone affiché en texte)155        details_common: dict = {}156        pm = PHONE_RE.search(soup.get_text(" ", strip=True))157        if pm:158            details_common["contact"] = {159                "phone": f"{pm.group(1)}-{pm.group(2)}-{pm.group(3)}"}160161        for item in soup.select("div.uniteItem"):162            try:163                type_el = item.select_one(".uniteType")164                unit_type = normalize_unit_type(165                    type_el.get_text(strip=True)) if type_el else ""166                vals = [v.get_text(strip=True)167                        for v in item.select(".uniteItemValeur")168                        if v.get_text(strip=True)]169                unit_no = next((v for v in vals170                                if re.fullmatch(r"[\dA-Za-z\-]{1,12}", v)), "")171                if not unit_no:172                    continue173                availability = next(174                    (v for v in vals175                     if re.search(r"occupation|imm[ée]diate|libre|\d{4}",176                                  v, re.I) and v != unit_no), "")177178                plan_el = item.select_one('a[href*="DATA/UNITE/"]')179                plan_url = f"{self.BASE}/{plan_el['href'].lstrip('/')}" \180                    if plan_el and plan_el.get("href") else ""181182                details = dict(details_common)183                area = None184                if plan_url:185                    details["plan_pdf"] = plan_url186                    key = hashlib.sha1(187                        f"{plan_url}|{availability}".encode()).hexdigest()188                    try:189                        d = self.detail(unit_no, key,190                                        lambda u=plan_url: self._plan_pdf(u))191                        area = d.get("area_net")192                        if d.get("area_gross"):193                            details["superficie_brute_pi2"] = d["area_gross"]194                        if d.get("balcony"):195                            details["balcon_pi2"] = d["balcony"]196                    except Exception:197                        pass198199                listings.append(Listing(200                    source=self.source_id,201                    external_id=unit_no,202                    url=f"{self.BASE}/",203                    title=f"{unit_type} — unité {unit_no}, {self.NAME}",204                    address=self.ADDRESS,205                    sector=self.SECTOR,206                    city=self.CITY,207                    unit_type=unit_type,208                    availability=availability,209                    area_sqft=area,210                    amenities=list(amenities),211                    details=details,212                    images=images,213                ))214            except Exception:215                continue216        return listings217218    # -- plan PDF d'une unité : superficies extraites par position ------------------219    def _plan_pdf(self, url: str) -> dict:220        """Superficie Nette / Brute / Balcon (pi²) du cartouche du plan.221222        Les libellés sont dans une colonne fixe ; la valeur est le nombre223        aligné verticalement (±6 pt) à droite du libellé.224        """225        if self._fetched >= self.max_details:226            raise RuntimeError("budget de plans PDF atteint")227        self._fetched += 1228        import pdfplumber229        raw = self.get(url).content230        if not raw.startswith(b"%PDF"):    # lien mort servi en page HTML 200231            return {}232        out: dict = {}233        with pdfplumber.open(io.BytesIO(raw)) as pdf:234            words = pdf.pages[0].extract_words()235        for label, field, lo, hi in (("Nette", "area_net", 300, 3000),236                                     ("Brute", "area_gross", 300, 3000),237                                     ("Balcon", "balcony", 20, 500)):238            anchor = next((w for w in words239                           if w["text"].startswith(label)), None)240            if anchor is None:241                continue242            frags = sorted((w for w in words243                            if anchor["x1"] - 2 < w["x0"] < anchor["x1"] + 160244                            and abs(w["top"] - anchor["top"]) < 6245                            and re.fullmatch(r"\d{1,4}", w["text"])),246                           key=lambda w: w["x0"])247            # certains cartouches scindent la valeur (« 1 » + « 189 » = 1189) :248            # recoller les fragments de chiffres contigus (< 8 pt d'écart)249            num = ""250            prev_x1 = None251            for w in frags:252                if prev_x1 is not None and w["x0"] - prev_x1 > 8:253                    break254                num += w["text"]255                prev_x1 = w["x1"]256            if num and lo <= float(num) <= hi:257                out[field] = float(num)258        return out259
Files main
Menu

Theme