SPB Git

Repository Public

grilli_citea.py 10.2 KB 250 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/grilli_citea.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/grilli_citea.py : connecteur Groupe Grilli Samuel / Citéa91#   (grillisamuel.com + projetcitea.com) — constructeur-gestionnaire ; son92#   inventaire locatif = le projet Citéa (950-970, avenue Pierre-Dansereau,93#   Terrebonne/Urbanova, 4 phases, condos locatifs tout inclus).94#   Backend : WordPress — l'API REST publique /wp-json/wp/v2/inventaire de95#   grillisamuel.com expose les fiches (content.rendered structuré :96#   caractéristiques, superficie, animaux, semi-meublé, photos). On ne garde97#   que les fiches LOCATIVES (« à louer » dans le texte) — les maisons de98#   Sainte-Julie/Pointe-Claire sont à VENDRE (promesse d'achat), exclues.99#   Les prix « à partir de » par typologie (3½/4½/4½+DEN) sont relevés sur100#   projetcitea.com/condos-locatifs/ et appariés à chaque fiche.101#   Granularité TYPOLOGIE (une annonce par type d'unité du projet).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing110from .base import BaseConnector111112API_URL = "https://grillisamuel.com/wp-json/wp/v2/inventaire?per_page=100&_embed=wp:featuredmedia"113CITEA_URL = "https://projetcitea.com/condos-locatifs/"114115# « 3½ à partir de 1 605$ /mois » (le + DEN distingue la grande variante)116CITEA_PRICE_RE = re.compile(117    r"([2-6])\s*½\s*(\+\s*DEN\s*)?à partir de\s*([\d  ]{4,9})\s*\$\s*/\s*mois",118    re.I)119# typologie de la fiche : « Projet Citéa – 4½ + DEN à louer … »120TYPE_RE = re.compile(r"([2-6])\s*(?:½|1/2)\s*(\+\s*DEN)?", re.I)121RENT_RE = re.compile(r"à louer|locatif", re.I)122SALE_RE = re.compile(r"promesse d[’']achat(?! ou de location)", re.I)123SQFT_RE = re.compile(r"Superficie habitable\s*\|?\s*([\d  ]+)(?:\s*à\s*([\d  ]+))?\s*pi", re.I)124IMG_RE = re.compile(r'(?:src|data-src|href)="(https://grillisamuel\.com/'125                    r'wp-content/uploads/[^"]+\.(?:jpe?g|png|webp))"', re.I)126127128class GrilliCiteaConnector(BaseConnector):129    source_id = "grilli_citea"130    request_delay = 0.8131132    def fetch(self) -> list[Listing]:133        listings: list[Listing] = []134        try:135            posts = self.get(API_URL).json()136        except Exception:137            return listings138        if not isinstance(posts, list):139            return listings140        prices = self._citea_prices()141142        for post in posts:143            try:144                lst = self._from_post(post, prices)145            except Exception:146                continue147            if lst is not None:148                listings.append(lst)149        return listings150151    # -- prix « à partir de » par typologie sur projetcitea.com ----------------152    def _citea_prices(self) -> dict[str, float]:153        prices: dict[str, float] = {}154        try:155            txt = BeautifulSoup(self.get(CITEA_URL).text,156                                "html.parser").get_text(" ", strip=True)157        except Exception:158            return prices159        for n, den, amount in CITEA_PRICE_RE.findall(txt):160            key = f"{n}½" + ("+DEN" if den else "")161            try:162                prices[key] = float(re.sub(r"[  ]", "", amount))163            except ValueError:164                continue165        return prices166167    def _from_post(self, post: dict, prices: dict[str, float]) -> Listing | None:168        title = BeautifulSoup(post.get("title", {}).get("rendered", ""),169                              "html.parser").get_text(" ", strip=True)170        content_html = post.get("content", {}).get("rendered", "")171        text = BeautifulSoup(content_html, "html.parser").get_text("\n", strip=True)172        blob = f"{title}\n{text}"173174        # logements à louer seulement (les maisons à vendre sont exclues)175        if not RENT_RE.search(blob) or SALE_RE.search(blob):176            return None177178        # typologie : mention explicite « 3½ / 4½ (+ DEN) à louer » du descriptif179        tm = TYPE_RE.search(text) or TYPE_RE.search(title)180        unit_type = f"{tm.group(1)}½" if tm else ""181        den = bool(tm and tm.group(2))182        price = prices.get(unit_type + ("+DEN" if den else ""))183184        # adresse dans le titre : « Condo 1 chambre, 970, Avenue …, Terrebonne »185        addr = ""186        city = ""187        am = re.search(r"(\d{2,5}(?:-\d{2,5})?,?\s+(?:rue|avenue|boulevard|chemin|montée)"188                       r"[^,]*),?\s*([A-ZÉÈÀ][\w-]+)?\s*$", title, re.I)189        if am:190            addr = am.group(1).strip()191            city = (am.group(2) or "").strip()192        if not city:193            cm = re.search(r"\b(Terrebonne|Sainte-Julie|Pointe-Claire|Mascouche"194                           r"|Laval)\b", blob)195            city = cm.group(1) if cm else ""196197        area = None198        sm = SQFT_RE.search(text)199        if sm:200            try:201                area = float(re.sub(r"[  ]", "", sm.group(1)))202            except ValueError:203                pass204205        amenities: list[str] = []206        for pat, lbl in ((r"Semi-meublé", "Semi-meublé"),207                         (r"Stationnement intérieur", "Stationnement intérieur"),208                         (r"[Tt]out inclus", "Tout inclus")):209            if re.search(pat, blob):210                amenities.append(lbl)211        pets = None212        pm = re.search(r"(Chiens[^|\n]{0,80}|[Aa]nimaux[^|\n]{0,80})", text)213        if pm:214            pets = "conditions"215            amenities.append(pm.group(1).strip())216217        images = list(dict.fromkeys(IMG_RE.findall(content_html)))[:20]218        if not images:219            emb = (post.get("_embedded", {}).get("wp:featuredmedia") or [{}])[0]220            src = emb.get("source_url", "")221            if src.startswith("http"):222                images = [src]223224        # descriptif : à partir de la section DESCRIPTIF ou du projet225        desc = ""226        dm = re.search(r"(?:DESCRIPTIF|Projet Citéa)[\s:–-]*\n?(.{40,1800})",227                       text, re.S)228        if dm:229            desc = re.sub(r"\s+", " ", dm.group(1)).strip()230231        return Listing(232            source=self.source_id,233            external_id=str(post.get("id")),      # ID WordPress : stable234            url=post.get("link", CITEA_URL),235            title=title,236            address=addr,237            sector="Urbanova" if city == "Terrebonne" else "",238            city=city,239            unit_type=unit_type + (" + DEN" if den else ""),240            price=price,241            price_label=(f"à partir de {price:.0f} $ /mois" if price else ""),242            availability="",243            area_sqft=area,244            pets=pets,245            description=desc[:2000],246            amenities=amenities,247            details={"price_from": True} if price else {},248            images=images,249        )250
Files main
Menu

Theme