SPB Git

Repository Public

katasa.py 10.1 KB 253 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/katasa.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/katasa.py : connecteur Groupe Katasa (katasa.ca — Gatineau)91#   Développeur-gestionnaire basé à Gatineau. WordPress « portfolio » : une92#   page brochure par immeuble, classée par catégorie. Seules les catégories93#   RÉSIDENTIELLES LOCATIVES sont crawleés (/portfolio_cat/apartments/ et94#   /portfolio_cat/apartment50/ — 50+ actifs sans soins) ; les résidences de95#   retraite (RPA), le commercial, les entrepôts et le parc de maisons96#   mobiles (location de terrain, pas de logement) sont exclus.97#   Donnée exploitable : le tableau « Rates » de la page (typologies en98#   en-tête, « From $ 2,075 » en dessous) -> une annonce par typologie AVEC99#   prix publié. Les brochures sans prix ni disponibilité (ex. Le Chambord)100#   ne produisent aucune annonce — rien n'est inventé.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105from urllib.parse import urljoin106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price, strip_accents110from .base import BaseConnector111112BASE = "https://katasa.ca"113# catégories résidentielles locatives seulement (retirement/commercial exclus)114CATEGORIES = ["/portfolio_cat/apartments/", "/portfolio_cat/apartment50/"]115116# immeubles hors périmètre même dans ces catégories117_EXCLUDE_SLUGS = {"riviera-mobile-home-park", "212nfederalhighway"}118119# secteurs de Gatineau repérables dans le contenu de la page120_SECTOR_WORDS = ["Aylmer", "Hull", "Buckingham", "Plateau", "Masson-Angers"]121122_IMG_RE = re.compile(123    r'https?://katasa\.ca/wp-content/uploads/[^"\'\s\)]+\.(?:jpg|jpeg|webp|png)',124    re.I)125_SKIP_IMG = re.compile(r"logo|icon|favicon|cropped|-\d{2,4}x\d{2,4}\.", re.I)126127128def _slugify(s: str) -> str:129    s = strip_accents(s.lower())130    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")131132133class KatasaConnector(BaseConnector):134    source_id = "katasa"135    request_delay = 1.0136    max_pages = 15137    max_images = 10138139    @staticmethod140    def _unit_type(label: str) -> str:141        t = strip_accents(label.lower())142        if "studio" in t:143            return "Studio"144        m = re.match(r"^(\d+)\s*bed", t)145        if m:146            return normalize_unit_type(f"{m.group(1)} chambres")147        return normalize_unit_type(label)148149    # -- page immeuble -----------------------------------------------------------150    def _parse_building(self, url: str, listings: list[Listing]) -> None:151        html = self.get(url).text152        soup = BeautifulSoup(html, "html.parser")153        slug = url.rstrip("/").rsplit("/", 1)[-1]154155        h1 = soup.find("h1")156        name = (h1.get_text(" ", strip=True) if h1 else slug).strip()157158        # tableau « Rates » : en-têtes = typologies, cellules = « From $ 2,075 »159        pairs: list[tuple[str, str]] = []160        for table in soup.find_all("table"):161            cells = [re.sub(r"\s+", " ", c.get_text(" ", strip=True))162                     for c in table.find_all(["th", "td"])]163            prices = [c for c in cells if re.search(r"\$\s*[\d,]{3,}", c)]164            labels = [c for c in cells if c and c not in prices]165            if prices and len(labels) == len(prices):166                pairs = list(zip(labels, prices))167                break168        if not pairs:169            return   # brochure sans prix publié : aucune annonce170171        # contenu éditorial (en dehors des menus/pied de page)172        body = BeautifulSoup(html, "html.parser")173        for tag in body.select("header, footer, nav"):174            tag.decompose()175        text = body.get_text("\n", strip=True)176177        # secteur de Gatineau si l'agence le nomme dans le contenu178        sector = ""179        for w in _SECTOR_WORDS:180            if re.search(rf"(?i)\b{re.escape(name)}\s+{w}\b|\b{w}\b.{{0,20}}{re.escape(name)}", text):181                sector = w182                break183        if not sector:184            for w in _SECTOR_WORDS:185                if re.search(rf"(?i)\b{w}\b", text.split("Nearby")[0]):186                    sector = w187                    break188189        og = soup.find("meta", attrs={"property": "og:description"})190        blurb = (og.get("content", "").strip() if og else "")191        if not blurb:   # premier paragraphe éditorial substantiel de la page192            for p in soup.select("div.uncont p"):193                t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))194                if len(t) > 80:195                    blurb = t196                    break197198        # « Included amenities: • Cable TV … » (puces rédigées par l'agence)199        amenities = [re.sub(r"\s+", " ", a.strip("• ").strip())200                     for a in re.findall(r"•\s*([^\n•]{3,80})", text)][:15]201202        images = [u for u in dict.fromkeys(_IMG_RE.findall(html))203                  if not _SKIP_IMG.search(u)][: self.max_images]204205        for label, price_label in pairs:206            key = _slugify(label)207            if not key:208                continue209            listings.append(Listing(210                source=self.source_id,211                external_id=f"{slug}:{key}",212                url=url,213                title=f"{name} — {label}",214                sector=sector,215                city="Gatineau",216                unit_type=self._unit_type(label),217                price=parse_price(price_label),218                price_label=price_label,219                description=blurb[:800],220                amenities=amenities,221                images=images,222            ))223224    # -- fetch -----------------------------------------------------------------225    def fetch(self) -> list[Listing]:226        urls: list[str] = []227        for cat in CATEGORIES:228            try:229                html = self.get(BASE + cat).text230            except Exception:231                continue232            soup = BeautifulSoup(html, "html.parser")233            # items de la catégorie seulement (le menu de navigation liste234            # TOUS les immeubles, y compris retraite/commercial : ignoré)235            for a in soup.select(".t-entry-title a[href*='/portfolio/']"):236                u = urljoin(BASE, a["href"]).split("#")[0].split("?")[0]237                slug = u.rstrip("/").rsplit("/", 1)[-1]238                if slug in _EXCLUDE_SLUGS or u in urls:239                    continue240                urls.append(u)241242        listings: list[Listing] = []243        for url in urls[: self.max_pages]:244            try:245                self._parse_building(url, listings)246            except Exception:247                continue248249        uniq: dict[str, Listing] = {}250        for lst in listings:251            uniq.setdefault(lst.external_id, lst)252        return list(uniq.values())253
Files main
Menu

Theme