SPB Git

Repository Public

groupe_jacques.py 12.7 KB 293 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_jacques.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/groupe_jacques.py : connecteur Groupe Jacques (groupejacques.com)91#   Promoteur-gestionnaire de Victoriaville. CMS custom (arborescence /fr/,92#   blocs « grid-stack ») : les pages projet /fr/condos-locatifs/* et93#   /fr/appartements/* exposent des cartes par type d'unité (h2 « 4½ -94#   Disponible / Complet », superficie « 1024 à 1479 pi² », « À partir de95#   1522 $ /mois ») — les types « Complet » sont sautés. La page96#   /fr/appartements/appartements-a-louer/ ajoute 4 immeubles (L'Éden,97#   Terrasses De Coursol, De Bigarré, De la Paix) avec adresse, description98#   et GPS (lien Google Maps). Le volet « résidences pour aînés » est EXCLU.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type, parse_price, strip_accents107from .base import BaseConnector108109BASE = "https://www.groupejacques.com"110LIST_URL = f"{BASE}/fr/appartements/appartements-a-louer/"111112# pages projet admissibles (les /fr/residences-pour-aines/ sont exclues)113_PROJECT_PATH = re.compile(r"^/fr/(?:condos-locatifs|appartements)/([^/]+)/$")114_TYPE_H2 = re.compile(r"^(\d)\s*½\s*(?:-\s*(.+))?$")115_AREA_RE = re.compile(r"(\d[\d\s]{2,6})(?:\s*à\s*\d[\d\s]{2,6})?\s*pi\b", re.I)116_PRICE_RE = re.compile(r"À partir de\s*[\d\s]+\s*\$\s*/?\s*mois", re.I)117_GMAPS_LATLNG = re.compile(r"!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)")118_GMAPS_AT = re.compile(r"@(-?\d+\.\d+),(-?\d+\.\d+)")119120121def _slug(text: str) -> str:122    s = strip_accents(text.lower()).replace("½", "-1-2")123    return re.sub(r"-{2,}", "-", re.sub(r"[^a-z0-9]+", "-", s)).strip("-")124125126class GroupeJacquesConnector(BaseConnector):127    source_id = "groupe_jacques"128    request_delay = 0.7129    max_pages = 12      # garde-fou : nombre max de pages projet visitées130131    def fetch(self) -> list[Listing]:132        listings: list[Listing] = []133134        # 1) page « Appartements à louer » : immeubles + liens des projets135        html = self.get(LIST_URL).text136        soup = BeautifulSoup(html, "html.parser")137        listings.extend(self._parse_buildings(soup))138139        paths: dict[str, str] = {}       # slug -> chemin /fr/…/140        for a in soup.select("a[href]"):141            href = a["href"].replace(BASE, "")142            m = _PROJECT_PATH.match(href)143            if m and m.group(1) != "appartements-a-louer":144                paths.setdefault(m.group(1), href)145146        # 2) pages projet : cartes par type d'unité147        for slug, path in list(paths.items())[: self.max_pages]:148            try:149                page = self.get(f"{BASE}{path}").text150            except Exception:151                continue152            listings.extend(self._parse_project(slug, page))153154        return listings155156    # -- page projet : cartes h2 « 4½ - Disponible » -----------------------------157    def _parse_project(self, slug: str, html: str) -> list[Listing]:158        soup = BeautifulSoup(html, "html.parser")159        url = ""160        canon = soup.select_one('link[rel="canonical"][href]')161        title_tag = soup.title.get_text() if soup.title else ""162        if re.search(r"a[îi]n[ée]s|retraite|manoir|seigneurie", title_tag, re.I):163            return []                                # volet aînés : exclu164        project = title_tag.split(" - ")[0].strip() or slug165        url = (canon["href"] if canon else166               f"{BASE}/fr/condos-locatifs/{slug}/")167168        text = re.sub(r"[\s\xa0]+", " ", soup.get_text(" ", strip=True))169        # adresse du projet : « … est situé au 414, rue de Bigarré, Victoriaville. »170        address = ""171        m = re.search(r"[Ss]itu[ée]?s?\s+au\s+(\d[\w\s-]*,\s*(?:rue|boul\w*|"172                      r"av\w*|chemin)[^,.]*(?:,\s*(?:à\s+)?[A-Z][\w-]+)?)", text)173        if m:174            address = m.group(1).replace(", à ", ", ").strip(" ,")175        # description : paragraphe « Le projet »176        description = ""177        for p in soup.find_all("p"):178            t = re.sub(r"[\s\xa0]+", " ", p.get_text(" ", strip=True))179            if len(t) > 150:180                description = t[:900]181                break182        img = soup.select_one('img[src*="fichiersUpload"][width="100%"]') \183            or soup.select_one('img[src*="fichiersUpload"]')184        images = [img["src"]] if img and img.get("src", "").startswith("http") else []185186        out: list[Listing] = []187        for h2 in soup.find_all(["h2", "h3"]):188            ht = re.sub(r"[\s\xa0]+", " ", h2.get_text(" ", strip=True))189            m = _TYPE_H2.match(ht)190            if not m:191                continue192            n, suffix = m.group(1), (m.group(2) or "").strip()193            if re.search(r"complet", suffix, re.I):194                continue                             # type complet : sauté195            availability = suffix if re.search(r"disponible", suffix, re.I) else ""196            variant = "" if availability else suffix  # ex. « Flex »197198            card = h2.find_parent(class_="grid-stack-item-content") or h2.parent199            ctext = re.sub(r"[\s\xa0]+", " ", card.get_text(" ", strip=True))200            price_label = ""201            mp = _PRICE_RE.search(ctext)202            if mp:203                price_label = mp.group(0)204            area_sqft = None205            ma = _AREA_RE.search(ctext)206            if ma:207                area_sqft = float(ma.group(1).replace(" ", ""))  # borne basse208209            ext_id = _slug(f"{slug}-{n}-1-2" + (f"-{variant}" if variant else ""))210            if any(l.external_id == ext_id for l in out):211                continue212            out.append(Listing(213                source=self.source_id,214                external_id=ext_id,                  # slug projet + type (stable)215                url=url,216                title=f"{project} — {ht}",217                address=address,218                sector="",219                city="Victoriaville",   # tout le parc locatif Groupe Jacques220                unit_type=normalize_unit_type(f"{n} ½"),221                price=parse_price(price_label),222                price_label=price_label,223                availability=availability,224                area_sqft=area_sqft,225                description=description,226                images=images,227            ))228        return out229230    # -- page « Appartements à louer » : immeubles -------------------------------231    def _parse_buildings(self, soup: BeautifulSoup) -> list[Listing]:232        out: list[Listing] = []233        for block in soup.select(".grid-stack-item-content"):234            btext = re.sub(r"[\s\xa0]+", " ", block.get_text(" ", strip=True))235            head = block.find("h4")236            if not head or "Victoriaville" not in btext or len(btext) < 80:237                continue238            if re.search(r"Nom complet|Groupe Jacques", btext):239                continue                             # formulaire / pied de page240            header = re.sub(r"[\s\xa0]+", " ", head.get_text(" ", strip=True))241            if not re.search(r"rue|boulevard|avenue", header, re.I):242                continue243244            # « L'Éden : 155, rue St-Georges, Victoriaville » -> nom + adresse245            if ":" in header:246                name, address = (x.strip() for x in header.split(":", 1))247            else:248                name, address = header, header249            ext_id = _slug(address)250            if not ext_id or any(l.external_id == ext_id for l in out):251                continue252253            # bandeau « 4½ disponible - Contactez-nous » dans le même bloc254            availability = ""255            h3 = block.find("h3")256            if h3 and re.search(r"disponible", h3.get_text(), re.I):257                availability = re.sub(r"[\s\xa0]+", " ",258                                      h3.get_text(" ", strip=True))259260            paras = [re.sub(r"[\s\xa0]+", " ", p.get_text(" ", strip=True))261                     for p in block.find_all("p")]262            description = "\n".join(p for p in paras if len(p) > 60)[:900]263            # type d'unité seulement si l'immeuble n'offre qu'UNE grandeur264            types = set(re.findall(r"(\d)\s*½", description))265            unit_type = normalize_unit_type(f"{types.pop()} ½") \266                if len(types) == 1 else ""267268            lat = lng = None269            gm = block.select_one('a[href*="google."][href*="maps"]')270            if gm:271                mm = _GMAPS_LATLNG.search(gm["href"]) or _GMAPS_AT.search(gm["href"])272                if mm:273                    lat, lng = float(mm.group(1)), float(mm.group(2))274            img = block.select_one('img[src*="fichiersUpload"][width="100%"]')275            images = [img["src"]] if img and img.get("src", "").startswith("http") else []276277            out.append(Listing(278                source=self.source_id,279                external_id=ext_id,                  # slug de l'adresse (stable)280                url=f"{LIST_URL}#{ext_id}",          # pas de fiche individuelle281                title=header,282                address=address,283                sector="",284                city="Victoriaville",285                unit_type=unit_type,286                availability=availability,           # texte source, si affiché287                description=description,288                images=images,289                lat=lat,290                lng=lng,291            ))292        return out293
Files main
Menu

Theme