SPB Git

Repository Public

lachance.py 12.7 KB 306 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lachance.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/lachance.py : connecteur Les Entreprises Lachance (lachance.qc.ca)91#   Constructeur-gestionnaire de l'Estrie : Sherbrooke (Fleurimont, Brompton,92#   Rock-Forest/St-Élie, Université), Magog, Orford, East Angus, Waterville.93#   Craft CMS (SEOmatic) : découverte par le sitemap sectionnel dédié94#   `forRentBuildingEntry` (une page par immeuble), chaque page immeuble liste95#   TOUTES ses unités en cartes `a.card-for-rent` : prix (avec promo barrée),96#   date de disponibilité (`.available-notice` — « Loué » quand non offert),97#   adresse, étage, superficie/chambres/sdb (icônes), type (h3.size-title).98#   Fiches unité visitées via self.detail() (cache BD, plafond max_details) :99#   description riche + galerie complète (img.img-swiper).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://lachance.qc.ca"112SITEMAP_URL = f"{BASE}/sitemaps-1-section-forRentBuildingEntry-1-sitemap.xml"113114_LOC_RE = re.compile(r"<loc>([^<]+)</loc>")115_AREA_RE = re.compile(r"^([\d\s,]+)\s*pi2?\b", re.I)116117# « Sherbrooke (Fleurimont) », « East-Angus », « Orford », « Waterville »…118_CITY_SECTOR_RE = re.compile(r"^\s*(.+?)\s*(?:\((.+)\))?\s*$")119120121def _split_city_sector(raw: str) -> tuple[str, str]:122    """« Sherbrooke (Fleurimont) » -> (Sherbrooke, Fleurimont) ; « East-Angus »123    -> (East Angus, ""). Jamais de ville inventée : on retourne le texte source."""124    # « #105 Sherbrooke (Fleurimont) » / « Orford #1300 » : retirer le numéro125    # d'unité résiduel accolé à la ville126    raw = re.sub(r"^\s*#?\d+[A-Za-z]?\s+(?=[A-ZÉÈÀ])", "", raw or "")127    raw = re.sub(r"\s*#\s*\d+[A-Za-z]?\s*$", "", raw)128    m = _CITY_SECTOR_RE.match(raw)129    if not m:130        return "", ""131    city = m.group(1).replace("East-Angus", "East Angus").strip(" ,")132    return city, (m.group(2) or "").strip()133134135class _DetailBudget(Exception):136    """Budget de fiches unité atteint pour cette synchronisation."""137138139class LachanceConnector(BaseConnector):140    source_id = "lachance"141    request_delay = 0.6142    max_buildings = 100      # garde-fou : pages immeuble du sitemap143    max_details = 40         # garde-fou : vraies requêtes de fiches unité144145    def fetch(self) -> list[Listing]:146        # 1) Découverte : sitemap sectionnel forRentBuildingEntry (une URL par147        #    immeuble ; on ignore les fiches PDF également listées)148        xml = self.get(SITEMAP_URL).text149        building_urls = []150        for loc in _LOC_RE.findall(xml):151            if loc.lower().endswith(".pdf") or "/documents/" in loc:152                continue153            if loc.startswith(f"{BASE}/logements-a-louer/") and loc not in building_urls:154                building_urls.append(loc)155156        # 2) Pages immeuble : cartes unité (on saute les logements « Loué »)157        listings: dict[str, Listing] = {}158        for burl in building_urls[: self.max_buildings]:159            try:160                html = self.get(burl).text161            except Exception:162                continue163            soup = BeautifulSoup(html, "html.parser")164            for card in soup.select("a.card-for-rent"):165                try:166                    lst = self._parse_card(card)167                except Exception:168                    continue169                if lst and lst.external_id not in listings:170                    listings[lst.external_id] = lst171172        # 3) Fiches unité (cache BD) : description riche + galerie complète173        self._detail_fetches = 0174        for lst in listings.values():175            key = hashlib.sha1(176                f"{lst.price_label}|{lst.availability}|{lst.unit_type}"177                .encode("utf-8")).hexdigest()178179            def fetch_fn(u=lst.url):180                if self._detail_fetches >= self.max_details:181                    raise _DetailBudget()182                self._detail_fetches += 1183                return self._fetch_detail(u)184185            try:186                payload = self.detail(lst.external_id, key, fetch_fn)187            except _DetailBudget:188                continue189            except Exception:190                continue191            if payload.get("description"):192                lst.description = payload["description"]193            if payload.get("images"):194                lst.images = payload["images"]195196        return list(listings.values())197198    # -- carte unité (page immeuble) -------------------------------------------199    def _parse_card(self, card) -> Listing | None:200        href = (card.get("href") or "").split("?")[0].rstrip("/")201        m = re.search(r"/logements-a-louer/([\w\-%.]+)$", href)202        if not m:203            return None204        slug = m.group(1)205206        # disponibilité : « Dès maintenant », « 1 septembre 2026 »… ; « Loué »207        # (ou bandeau absent) = unité non offerte -> on saute208        notice = card.select_one(".available-notice")209        availability = notice.get_text(" ", strip=True) if notice else ""210        if not availability or re.search(r"lou[ée]", availability, re.I):211            return None212213        # prix : promo = prix courant en rouge, prix régulier barré214        # (text-decoration-line-through) ; price_label garde le texte affiché215        price = None216        price_label = ""217        h4 = card.select_one(".min-height-price h4")218        if h4:219            price_label = " ".join(h4.get_text(" ", strip=True).split())220            spans = h4.find_all("span")221            current = [s for s in spans222                       if "text-decoration-line-through" not in (s.get("class") or [])]223            effective = (current[-1].get_text(" ", strip=True)224                         if current else price_label)225            price = parse_price(effective) or parse_price(price_label)226227        # adresse : h3 de la carte, ex. « 1331, rue Quatre-Saisons,228        # Sherbrooke (Fleurimont) » — dernière portion = ville (secteur)229        addr_el = card.select_one("h3.font-size-14")230        address = " ".join(addr_el.get_text(" ", strip=True).split()) if addr_el else ""231        parts = [p.strip() for p in address.split(",") if p.strip()]232        city, sector = _split_city_sector(parts[-1]) if parts else ("", "")233234        # étage (libellé structuré de la carte)235        amenities: list[str] = []236        for p in card.select("p.font-size-14"):237            t = " ".join(p.get_text(" ", strip=True).split())238            if t.lower().startswith("étage"):239                amenities.append(t.replace("Étage: ", "Étage : "))240                break241242        # pied de carte : superficie (icône building), chambres (bed), sdb (bath)243        area = None244        for rd in card.select(".rent-detail"):245            svg = rd.select_one("svg")246            cls = " ".join(svg.get("class") or []) if svg else ""247            txt = " ".join(rd.get_text(" ", strip=True).split())248            if "building" in cls:249                m2 = _AREA_RE.match(txt)250                if m2:251                    try:252                        val = float(m2.group(1).replace(" ", "").replace(",", ""))253                        if 80 <= val <= 20000:254                            area = val255                    except ValueError:256                        pass257            elif "bed" in cls and txt:258                amenities.append(f"{txt} chambre(s)")259            elif "bath" in cls and txt:260                amenities.append(f"{txt} salle(s) de bain")261262        # type d'unité : bandeau h3.size-title de la carte (« 4 ½ », « Studio »)263        type_el = card.select_one("h3.size-title")264        unit_type = normalize_unit_type(265            type_el.get_text(" ", strip=True) if type_el else "")266267        img = card.select_one("img.img-card-for-rent")268        images = [img["src"]] if img and img.get("src", "").startswith("http") else []269270        return Listing(271            source=self.source_id,272            external_id=slug,273            url=f"{BASE}/logements-a-louer/{slug}",274            title=address or slug.replace("-", " "),275            address=address,276            sector=sector,277            city=city,278            unit_type=unit_type,279            price=price,280            price_label=price_label,281            availability=availability,282            area_sqft=area,283            amenities=amenities,284            images=images,285        )286287    # -- fiche unité -------------------------------------------------------------288    def _fetch_detail(self, url: str) -> dict:289        """Description riche (bloc .text-editor) + galerie (img.img-swiper)."""290        html = self.get(url).text291        soup = BeautifulSoup(html, "html.parser")292        payload: dict = {}293294        editor = soup.select_one(".col-info-desctiption .text-editor, .text-editor")295        if editor:296            txt = editor.get_text("\n", strip=True)297            payload["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]298299        images: list[str] = []300        for img in soup.select("img.img-swiper[src]"):301            src = img["src"]302            if src.startswith("http") and "/a-louer/" in src and src not in images:303                images.append(src)304        payload["images"] = images[:30]305        return payload306
Files main
Menu

Theme