SPB Git

Repository Public

viridi.py 13.4 KB 329 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/viridi.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/viridi.py : connecteur Le Viridi (condosleviridi.ca)91#   Immeuble de 89 unités dans l'Écoquartier Pointe-aux-Lièvres (Québec).92#   Le site présente 16 modèles d'unités (types A à O) avec prix93#   « à partir de » par catégorie (Studio/Loft/3½/4½/5½/6½, maison de ville).94#   Une annonce par modèle (pas de liste d'unités individuelles).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import hashlib99import re100101from bs4 import BeautifulSoup102103from ..schema import Listing, normalize_unit_type, parse_price104from .base import BaseConnector105106BASE = "https://condosleviridi.ca"107LIST_URL = f"{BASE}/condos-a-louer-quebec/"108CONTACT_URL = f"{BASE}/nous-joindre/"109SECTOR = "Pointe-aux-Lièvres (Saint-Roch)"110CITY = "Québec"111FALLBACK_ADDRESS = "Écoquartier Pointe-aux-Lièvres, Québec"112113_SKIP_IMG = re.compile(r"logo|favicon|icon|affichez", re.I)114115116class ViridiConnector(BaseConnector):117    source_id = "viridi"118    request_delay = 0.6119    max_detail_requests = 60   # plafond de vraies requêtes « fiche modèle »120121    # ------------------------------------------------------------------122    def _site_info(self) -> tuple[str, dict]:123        """Adresse civique + contact depuis la page Nous joindre.124125        « Adresse du projet : 40, rue de la Pointe-aux-Lièvres, Québec,126        QC G1K 0J7 » + liens tel:/mailto: (structurés dans la page).127        """128        address, contact = "", {}129        try:130            html = self.get(CONTACT_URL).text131        except Exception:132            return address, contact133        m = re.search(134            r"(\d{1,5},?\s(?:rue|avenue|boulevard)[^<>&]{0,50}"135            r"Pointe-aux-Li[eè]vres,?)"136            r"(?:<[^>]*>\s*)*"137            r"(Qu[ée]bec[^<>]{0,30})?", html)138        if m:139            address = m.group(1).strip()140            if m.group(2):141                address += " " + m.group(2).strip()142        m = re.search(r'href="tel:([\d\-. ]{10,})"', html)143        if m:144            digits = re.sub(r"\D", "", m.group(1))[-10:]145            if len(digits) == 10:146                contact["phone"] = f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"147        m = re.search(r'href="mailto:([^"?]+)"', html)148        if m:149            contact["email"] = m.group(1).strip().lower()150        return address, contact151152    # ------------------------------------------------------------------153    def _fetch_model(self, url: str) -> dict:154        """Fiche d'un modèle : description, caractéristiques à icônes, photos."""155        dhtml = self.get(url).text156        dsoup = BeautifulSoup(dhtml, "html.parser")157158        # premier paragraphe descriptif (« Cette unité... », « Ce condo... »)159        description = ""160        el = dsoup.find(string=re.compile(r"Cette unité|Ce (?:condo|loft|modèle)"))161        if el:162            p = el.find_parent("p")163            if p:164                description = p.get_text(" ", strip=True)[:600]165166        # caractéristiques : chaque icône VC est suivie d'un bloc texte167        # (chambres, salles de bain, superficie, inclusions, animaux...)168        amenities: list[str] = []169        for icon in dsoup.select(".vc_icon_element"):170            txt = icon.find_next_sibling("div", class_="wpb_text_column")171            if not txt:172                continue173            t = re.sub(r"\s+", " ", txt.get_text(" ", strip=True))174            if t and len(t) < 120 and t not in amenities:175                amenities.append(t)176177        imgs = re.findall(178            rf'src="({re.escape(BASE)}/wp-content/uploads/[^"]+'179            rf'\.(?:jpg|jpeg|png|webp))"', dhtml, re.I)180        images = [u for u in dict.fromkeys(imgs)181                  if not _SKIP_IMG.search(u)][:10]182        return {"description": description, "amenities": amenities,183                "images": images}184185    # ------------------------------------------------------------------186    def _price_map(self, text: str) -> dict[tuple[str, bool], tuple[float | None, str]]:187        """Construit {(catégorie, maison_de_ville): (prix, libellé)}.188189        Le bloc de prix de la page liste, dans l'ordre :190        Loft 1285$, Studio 1300$, 3½ 1400$, 4½ 1995$,191        4½ MV 2450$, 5½ MV 2800$, 6½ MV 3300$.192        """193        out: dict[tuple[str, bool], tuple[float | None, str]] = {}194        # découpage en lignes propres195        lines = [l.strip() for l in text.split("\n") if l.strip()]196        current: str | None = None197        mv = False198        for line in lines:199            low = line.lower()200            if re.fullmatch(r"(loft|studio|\d\s*½|\d\s*1/2)", low):201                current = ("loft" if low == "loft" else202                           "studio" if low == "studio" else203                           re.search(r"\d", low).group(0))204                mv = False205            elif "maison de ville" in low and current:206                mv = True207            elif current and "à partir de" in low:208                price = parse_price(line)209                label = re.sub(r"\s+", " ", line)210                if mv:211                    label += " (maison de ville)"212                out[(current, mv)] = (price, label)213                current = None214                mv = False215        return out216217    # ------------------------------------------------------------------218    def fetch(self) -> list[Listing]:219        self._detail_requests = 0220        html = self.get(LIST_URL).text221        soup = BeautifulSoup(html, "html.parser")222        prices = self._price_map(soup.get_text("\n", strip=True))223        address, contact = self._site_info()224        if not address:225            address = FALLBACK_ADDRESS226227        # Cartes de modèles : image plan + titre h3 + bouton "Plus d'infos"228        cards: list[tuple[str, str, str]] = []   # (titre, url, img)229        for a in soup.select('a[title="Lien vers le modèle"][href]'):230            href = a["href"].strip()231            if href.startswith("http:"):232                href = "https:" + href[5:]233            wrapper = a.find_parent("div", class_="wpb_wrapper")234            title = img = ""235            if wrapper:236                h3 = wrapper.select_one("h3")237                if h3:238                    title = h3.get_text(" ", strip=True)239                im = wrapper.select_one("img[src]")240                if im:241                    img = im["src"]242            if title and (title, href, img) not in cards:243                cards.append((title, href, img))244245        listings: list[Listing] = []246        for title, url, thumb in cards:247            if not re.search(r"\(type\s", title, re.I):248                continue          # carte non-modèle (ex. bouton de contact)249            try:250                mv = "maison de ville" in title.lower()251                cat = None252                if re.search(r"studio", title, re.I):253                    cat = "studio"254                elif re.search(r"loft", title, re.I):255                    cat = "loft"256                else:257                    d = re.search(r"(\d)\s*½", title)258                    if d:259                        cat = d.group(1)260                price, price_label = prices.get((cat, mv), (None, ""))261                if price is None and cat and not mv:262                    # tolérance si la carte MV/condo ne matche pas exactement263                    price, price_label = prices.get((cat, True), (None, ""))264265                unit_type = normalize_unit_type(title)266                if cat == "studio":267                    unit_type = "Studio"268                elif cat == "loft":269                    unit_type = "Loft"270271                # Fiche du modèle (description, caractéristiques à icônes,272                # photos) via le cache détail : 1 vraie requête par modèle273                # et par changement de carte liste.274                ext_id = url.rstrip("/").split("/")[-1]275                key = hashlib.sha1(276                    f"{title}|{url}|{thumb}|{price_label}".encode("utf-8")277                ).hexdigest()278279                def _fetch(url=url) -> dict:280                    if self._detail_requests >= self.max_detail_requests:281                        return {}282                    self._detail_requests += 1283                    return self._fetch_model(url)284285                try:286                    payload = self.detail(ext_id, key, _fetch) or {}287                except Exception:288                    payload = {}289                description = payload.get("description", "")290                amenities = list(payload.get("amenities") or [])291                images = list(payload.get("images") or [])292293                # « Animaux de compagnie acceptés » : caractéristique à icône294                # explicite de la fiche -> pets structuré295                pets = None296                if any(re.search(r"animaux de compagnie accept",297                                 a, re.I) for a in amenities):298                    pets = "oui"299300                if thumb and thumb not in images and not _SKIP_IMG.search(thumb):301                    # version pleine grandeur de la vignette302                    full = re.sub(r"-\d+x\d+(\.(?:jpg|jpeg|png|webp))$",303                                  r"\1", thumb)304                    images.insert(0, full)305                images = list(dict.fromkeys(images))306307                listings.append(Listing(308                    source=self.source_id,309                    external_id=ext_id,310                    url=url,311                    title=f"Le Viridi — {title}",312                    address=address,313                    sector=SECTOR,314                    city=CITY,315                    unit_type=unit_type,316                    price=price,317                    price_label=price_label,318                    availability="",319                    pets=pets,320                    description=description,321                    amenities=amenities,322                    details={"contact": dict(contact)} if contact else {},323                    images=images,324                ))325            except Exception:326                continue327328        return listings329
Files main
Menu

Theme