SPB Git

Repository Public

jutras.py 14.9 KB 340 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/jutras.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-1814#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/jutras.py : connecteur Habitations Jutras (jutras.com)91#   Promoteur-gestionnaire au Centre-du-Québec et en Estrie. WordPress + Avada92#   (Fusion Builder) : /condos-a-louer/ liste les projets locatifs93#   (/condo/<slug>/) ; chaque page projet expose une section « LES UNITÉS »94#   (ancre id="prix") avec, par type d'unité (3½/4½/5½) : superficie,95#   chambres, stationnements et « À partir de X$/mois ». Une annonce par96#   (projet, type). Ville réelle tirée du <title> ou de la phrase « situé97#   à/dans … » de la page projet. Le projet Prisme (page spéciale98#   /condos-a-louer/drummondville/prisme/) est parsé par regex type+prix.99#   Exclu : Huit Cents (immeuble 50 ans et plus). robots.txt permissif.100#   NB : certaines cartes placent leurs lignes (dont le prix !) dans des101#   <li><div class="fusion-li-item-content"><b>…</b></div> plutôt que des <p>102#   -> les deux formes sont lues. Galerie du projet (.fusion-gallery,103#   miniatures -WxH ramenées à l'original) partagée par ses annonces.104#   Aucune adresse civique par projet chez la source (ville seulement).105# -----------------------------------------------------------------------------106from __future__ import annotations107108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://jutras.com"116LIST_URL = f"{BASE}/condos-a-louer/"117PRISME_URL = f"{BASE}/condos-a-louer/drummondville/prisme/"118119# villes du parc Jutras (Centre-du-Québec / Estrie) — vocabulaire fermé,120# utilisé pour lire la ville RÉELLE du <title> ou du texte de la page121_CITIES = ["Drummondville", "Sherbrooke", "Nicolet", "Notre-Dame-du-Bon-Conseil",122           "East Angus", "Victoriaville", "Bécancour", "Trois-Rivières"]123124_TYPE_TOKEN = re.compile(r"^(\d)\s*½$")125_AREA_RE = re.compile(r"^(\d{3,4})(?:\s*à\s*(\d{3,4}))?\s*pi\s*2?\s*$", re.I)126_PRICE_RE = re.compile(r"partir de\s*[\d\s]+\$", re.I)127# page Prisme : « 3 ½ À partir de 1050 $/mois »128_PRISME_UNIT_RE = re.compile(r"(\d)\s*½\s*À partir de\s*([\d\s]+\$\s*/\s*mois)")129130131class JutrasConnector(BaseConnector):132    source_id = "jutras"133    request_delay = 0.7134    max_pages = 20      # garde-fou : nombre max de pages projet visitées135136    def fetch(self) -> list[Listing]:137        listings: list[Listing] = []138139        # 1) répertoire des projets : liens /condo/<slug>/ + nom d'affichage140        html = self.get(LIST_URL).text141        soup = BeautifulSoup(html, "html.parser")142        projects: dict[str, str] = {}      # slug -> nom du projet143        for a in soup.select('a[href*="/condo/"]'):144            m = re.search(r"/condo/([^/#?]+)/?", a.get("href", ""))145            name = a.get_text(" ", strip=True)146            if m and name and m.group(1) not in projects:147                projects[m.group(1)] = name148149        # 2) chaque page projet : section « LES UNITÉS » (ancre id="prix")150        for slug, name in list(projects.items())[: self.max_pages]:151            try:152                page = self.get(f"{BASE}/condo/{slug}/").text153            except Exception:154                continue155            listings.extend(self._parse_project(slug, f"{BASE}/condo/{slug}/",156                                                name, page))157158        # 3) projet Prisme (Drummondville) : page spéciale hors /condo/159        try:160            page = self.get(PRISME_URL).text161            listings.extend(self._parse_prisme(page))162        except Exception:163            pass164165        return listings166167    # -- ville réelle du projet --------------------------------------------------168    @staticmethod169    def _project_city(title: str, body_text: str) -> str:170        for c in _CITIES:                      # <title> : « … à louer à Sherbrooke »171            if c.lower() in title.lower():172                return c173        # sinon : phrase « situé … » de la page projet (en ignorant les174        # repères « à X minutes de Y ») — « … situé dans le charmant village175        # de Notre-Dame-du-Bon-Conseil »176        for m in re.finditer(r"[Ss]itu[ée][^.]{0,220}", body_text):177            phrase = re.sub(r"\d+\s+minutes?\s+de\s+\S+", "", m.group(0))178            for c in _CITIES:                  # « village/ville de X » d'abord179                if re.search(r"(?:village|ville|municipalité)\s+de\s+"180                             + re.escape(c), phrase, re.I):181                    return c182            for c in _CITIES:183                if c.lower() in phrase.lower():184                    return c185        return ""186187    # -- galerie du projet (og:image + .fusion-gallery, originaux sans -WxH) ----188    @staticmethod189    def _project_images(soup) -> list[str]:190        images: list[str] = []191        og = soup.select_one('meta[property="og:image"][content]')192        if og and str(og["content"]).startswith("http"):193            images.append(og["content"])194        for im in soup.select(".fusion-gallery img"):195            u = str(im.get("data-orig-src") or im.get("src") or "")196            u = re.sub(r"-\d{2,4}x\d{2,4}(?=\.\w)", "", u)197            if u.startswith("http") and u not in images:198                images.append(u)199        return images[:14]200201    # -- prose de présentation du projet (paragraphes longs de la page) ---------202    @staticmethod203    def _project_blurb(soup) -> str:204        paras: list[str] = []205        for p in soup.find_all("p"):206            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))207            if 150 < len(t) < 600 and not re.search(208                    r"cookie|champ|validation|confidentialité|indique les",209                    t, re.I) and t not in paras:210                paras.append(t)211            if len(paras) >= 2:212                break213        return " ".join(paras)214215    # -- page projet standard (/condo/<slug>/) ------------------------------------216    def _parse_project(self, slug: str, url: str, name: str,217                       html: str) -> list[Listing]:218        i = html.find('id="prix"')219        if i < 0:220            return []                          # pas de section unités → rien221        soup = BeautifulSoup(html, "html.parser")222        title_tag = soup.title.get_text() if soup.title else ""223        if re.search(r"50 ans|a[îi]n[ée]s|retraite", title_tag, re.I):224            return []                          # immeuble pour aînés : exclu225        city = self._project_city(title_tag, soup.get_text(" ", strip=True))226227        images = self._project_images(soup)228        blurb = self._project_blurb(soup)229230        # tokens texte de la section unités (jusqu'aux inclusions) — lignes en231        # <p> OU en <b> de puce Avada (fusion-li-item-content, prix des cartes)232        section = BeautifulSoup(html[i:i + 80000], "html.parser")233        tokens: list[str] = []234        for el in section.find_all(["p", "h2", "h3", "h4", "b"]):235            if el.name == "b" and el.find_parent(["p", "h2", "h3", "h4"]):236                continue                       # déjà couvert par son parent237            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))238            if not t:239                continue240            # fin de la section unités : inclusions/galerie/formulaire241            if re.search(r"Inclusions|commodités|Caractéristiques|LOOKBOOK|"242                         r"Réservez|Téléchargez|Galerie", t, re.I):243                break244            if el.name not in ("p", "b") or re.match(r"^LES UNITÉS$|^Découvrez", t):245                continue                       # titres de section : ignorés246            tokens.append(t)247248        # en-tête de section : dispo projet + mention de prix « à partir de »249        avail_proj, price_proj, intro = "", "", []250        cards: list[dict] = []251        cur: dict | None = None252        for t in tokens:253            m = _TYPE_TOKEN.match(t)254            if m:255                cur = {"type": f"{m.group(1)} ½", "lines": []}256                cards.append(cur)257                continue258            if cur is None:259                intro.append(t)260                if re.search(r"[Oo]ccupation|[Dd]éménagez|[Ee]mménagez", t) \261                        and not avail_proj:262                    avail_proj = t263                if _PRICE_RE.search(t) and not price_proj:264                    price_proj = t265            elif not re.search(r"^Voir (le|la|les)|Prix sujets", t, re.I):266                cur["lines"].append(t)267268        out: list[Listing] = []269        for idx, card in enumerate(cards):270            unit_type = normalize_unit_type(card["type"])271            area_sqft, availability, price_label = None, "", ""272            lines: list[str] = []273            for t in card["lines"]:274                ma = _AREA_RE.match(t)275                if ma and area_sqft is None:276                    area_sqft = float(ma.group(1))   # borne basse si « X à Y pi² »277                elif _PRICE_RE.search(t) and not price_label:278                    price_label = t279                elif re.search(r"[Oo]ccupation", t) and not availability:280                    availability = t281                lines.append(t)282            if not availability:283                availability = avail_proj          # dispo affichée au projet284            # mention projet « Location à partir de X $ par mois » : ne285            # s'applique qu'au type le moins cher (1re carte), jamais aux autres286            if not price_label and idx == 0 and price_proj:287                price_label = price_proj288289            out.append(Listing(290                source=self.source_id,291                external_id=f"{slug}-{card['type'].replace(' ½', '-1-2')}",292                url=f"{url}#prix",293                title=f"{name} — {card['type']}",294                sector="",295                city=city,296                unit_type=unit_type,297                price=parse_price(price_label),298                price_label=price_label,299                availability=availability,300                area_sqft=area_sqft,301                description=(" · ".join(intro + lines)[:900]302                             + (f"\n{blurb}" if blurb else ""))[:1600],303                images=images,304            ))305        return out306307    # -- page spéciale Prisme -------------------------------------------------308    def _parse_prisme(self, html: str) -> list[Listing]:309        soup = BeautifulSoup(html, "html.parser")310        text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))311        images = self._project_images(soup)312        blurb = self._project_blurb(soup)313        m = re.search(r"(?:Emménagez|Déménagez|Occupation)[^.]{0,60}?"314                      r"(?:dès|d[eè]s le)\s+[^.]{3,40}?(?=\s+voir|\s+3\s*½|\.)",315                      text)316        availability = m.group(0).strip() if m else ""317318        out: list[Listing] = []319        for mt in _PRISME_UNIT_RE.finditer(text):320            n, label = mt.group(1), re.sub(r"\s+", " ", mt.group(2)).strip()321            ext_id = f"prisme-{n}-1-2"322            if any(l.external_id == ext_id for l in out):323                continue324            price_label = f"À partir de {label}"325            out.append(Listing(326                source=self.source_id,327                external_id=ext_id,328                url=PRISME_URL,329                title=f"Prisme — {n} ½",330                sector="",331                city="Drummondville",     # « Condos locatifs à Drummondville »332                unit_type=normalize_unit_type(f"{n} ½"),333                price=parse_price(price_label),334                price_label=price_label,335                availability=availability,336                description=blurb,337                images=images,338            ))339        return out340
Files main
Menu

Theme