Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/kass.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/kass.py : connecteur KASS Property Management (kassproperties.com)91# Gestionnaire Ottawa-Gatineau. WordPress + thème immobilier Houzez (même92# famille que gimcote.py) : l'archive /city/gatineau/ liste les cartes du93# parc québécois — prix, ville, lits/sdb/pi², galerie (data-images),94# étiquettes de statut. Les cartes « Rented » sont sautées, de même que le95# widget « propriétés similaires » d'Ottawa (cartes SANS étiquette de96# statut) : les villes ontariennes sont exclues du périmètre Lou-Ka.97# La fiche détail (cache BD) ajoute la description, le bloc « Details »98# structuré (Move-in Date, Pet Friendly, Smoking, superficie, type), les99# commodités et l'adresse civique complète.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import html as htmllib105import json106import re107108from bs4 import BeautifulSoup109110from ..schema import (Listing, normalize_unit_type, parse_area_sqft,111 parse_price, strip_accents)112from .base import BaseConnector113114BASE = "https://kassproperties.com"115LIST_URL = f"{BASE}/city/gatineau/"116117_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)118# secteurs de Gatineau repérables dans le titre ou l'adresse119_SECTORS = ["Hull", "Aylmer", "Buckingham", "Masson-Angers", "Plateau"]120121122def _pets_value(raw: str) -> str | None:123 k = strip_accents((raw or "").strip().lower())124 if not k:125 return None126 if k.startswith(("no", "non")):127 return "non"128 if k.startswith(("yes", "oui")):129 return "oui"130 return "conditions"131132133class KassConnector(BaseConnector):134 source_id = "kass"135 request_delay = 1.0136 max_pages = 5137 max_details = 20138 max_images = 20139140 def fetch(self) -> list[Listing]:141 listings: dict[str, Listing] = {}142 for page in range(1, self.max_pages + 1):143 url = LIST_URL if page == 1 else f"{LIST_URL}page/{page}/"144 try:145 html = self.get(url).text146 except Exception:147 break148 soup = BeautifulSoup(html, "html.parser")149 before = len(listings)150 for card in soup.select("div.item-listing-wrap"):151 try:152 self._parse_card(card, listings)153 except Exception:154 continue155 if len(listings) == before: # plus de résultats d'archive156 break157158 # fiches détail Houzez (cache BD)159 self._fetched = 0160 for lst in listings.values():161 key = hashlib.sha1(162 f"{lst.title}|{lst.price_label}|{lst.url}"163 .encode("utf-8")).hexdigest()[:20]164 try:165 payload = self.detail(lst.external_id, key,166 lambda u=lst.url: self._fetch_detail(u))167 except Exception:168 continue169 self._apply_detail(lst, payload)170 return list(listings.values())171172 # -- carte Houzez ------------------------------------------------------------173 def _parse_card(self, card, listings: dict[str, Listing]) -> None:174 # cartes d'archive seulement : le widget « similaires » (Ottawa) n'a175 # pas d'étiquette de statut176 status = [a.get_text(strip=True)177 for a in card.select("a[href*='/status/']")]178 if not any(re.search(r"(?i)for rent", s) for s in status):179 return180 labels = [a.get_text(strip=True)181 for a in card.select("a[href*='/label/']")]182 if any(re.search(r"(?i)rented|lou[ée]", s) for s in labels + status):183 return # déjà loué184185 addr_el = card.select_one("address.item-address")186 card_city = addr_el.get_text(" ", strip=True) if addr_el else ""187 if not re.search(r"(?i)gatineau|hull|aylmer|buckingham", card_city):188 return # villes ontariennes exclues189190 link = card.select_one("h2.item-title a[href]")191 if not link:192 return193 url = link["href"]194 title = link.get_text(" ", strip=True)195 ext = str(card.get("data-hz-id") or "")196 if not ext:197 m = re.search(r"/property/([^/]+)/?", url)198 ext = m.group(1) if m else ""199 if not ext or ext in listings:200 return201 if re.search(r"(?i)parking|storage|commercial|office", title):202 return # non résidentiel203204 price_el = card.select_one("li.item-price")205 price_label = price_el.get_text(" ", strip=True) if price_el else ""206207 # lits/sdb/pi² de la carte208 beds = sqft = ""209 amen_bits: list[str] = []210 for li in card.select("ul.item-amenities li"):211 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))212 if re.match(r"(?i)^bed", t):213 beds = t214 elif "sqft" in t.lower():215 sqft = t216 if t:217 amen_bits.append(t)218 unit_type = ""219 m = re.search(r"(\d+)", beds)220 if m:221 unit_type = normalize_unit_type(f"{m.group(1)} chambres")222223 # secteur si l'agence le nomme dans le titre224 sector = ""225 for s in _SECTORS:226 if re.search(rf"(?i)\b{s}\b", title):227 sector = s228 break229230 # galerie complète (attribut data-images, JSON Houzez)231 images: list[str] = []232 raw = card.get("data-images") or ""233 if raw:234 try:235 items = json.loads(htmllib.unescape(raw))236 urls = [it.get("image", "") if isinstance(it, dict) else str(it)237 for it in items]238 except Exception:239 urls = re.findall(r"https?:[^\"',\\]+", htmllib.unescape(raw))240 for u in urls:241 u = u.replace("\\/", "/").strip()242 if u.startswith("http"):243 u = _SIZE_SUFFIX.sub("", u)244 if u not in images:245 images.append(u)246 if not images:247 thumb = card.select_one("img.wp-post-image[src]")248 if thumb:249 images = [_SIZE_SUFFIX.sub("", thumb["src"])]250251 listings[ext] = Listing(252 source=self.source_id,253 external_id=ext,254 url=url,255 title=title,256 sector=sector,257 city="Gatineau",258 unit_type=unit_type,259 price=parse_price(price_label.replace(",", "")),260 price_label=price_label,261 description=" — ".join(amen_bits),262 images=images[: self.max_images],263 )264265 # -- fiche détail Houzez -------------------------------------------------------266 def _fetch_detail(self, url: str) -> dict:267 if self._fetched >= self.max_details:268 raise RuntimeError("budget de fiches détail atteint")269 self._fetched += 1270 soup = BeautifulSoup(self.get(url).text, "html.parser")271 out: dict = {}272273 desc_el = soup.select_one("#property-description-wrap")274 if desc_el:275 txt = desc_el.get_text("\n", strip=True)276 txt = re.sub(r"^Description\n", "", txt)277 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]278279 out["amenities"] = [a.get_text(" ", strip=True)280 for a in soup.select("#property-features-wrap li")281 if a.get_text(strip=True)][:25]282283 # bloc « Details » : Move-in Date, Pet Friendly, Smoking, Size, Type284 for li in soup.select("#property-detail-wrap li"):285 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))286 lab = strip_accents(t.lower())287 val = re.sub(r"^[^ ]+( [^ ]+)? ", "", t).strip()288 if lab.startswith("move-in date"):289 out["availability"] = t.replace("Move-in Date", "").strip()290 elif lab.startswith("pet friendly"):291 out["pets_raw"] = t.replace("Pet Friendly", "").strip()292 elif lab.startswith("smoking"):293 out["smoking_raw"] = t.replace("Smoking", "").strip()294 elif lab.startswith("property size"):295 out["size_raw"] = val296 elif lab.startswith("property type"):297 out["type_raw"] = t.replace("Property Type", "").strip()298299 for li in soup.select("#property-address-wrap li"):300 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))301 if t.lower().startswith("address:"):302 out["address"] = t.split(":", 1)[1].strip()303 return out304305 def _apply_detail(self, lst: Listing, d: dict) -> None:306 if not d:307 return308 if d.get("description"):309 lst.description = d["description"]310 if d.get("amenities"):311 lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))312 if d.get("availability"):313 lst.availability = d["availability"]314 # format Houzez « 1-Sep-24 » (année sur 2 chiffres) : la315 # normalisation commune ignorerait l'année et projetterait une316 # date future — on la résout ici (date passée -> « now »)317 m = re.match(r"^(\d{1,2})-([A-Za-z]{3})-(\d{2})$",318 d["availability"].strip())319 if m:320 from datetime import date321 months = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5,322 "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10,323 "nov": 11, "dec": 12}324 mo = months.get(m.group(2).lower())325 if mo:326 dt = date(2000 + int(m.group(3)), mo, int(m.group(1)))327 lst.availability_date = ("now" if dt <= date.today()328 else dt.isoformat())329 if d.get("address"):330 lst.address = d["address"]331 if not lst.sector:332 for s in _SECTORS:333 if re.search(rf"(?i)\b{s}\b", d["address"]):334 lst.sector = s335 break336 if lst.area_sqft is None and d.get("size_raw"):337 lst.area_sqft = parse_area_sqft(d["size_raw"])338 pets = _pets_value(d.get("pets_raw", ""))339 if pets:340 lst.pets = pets341 details: dict = {}342 if d.get("type_raw"):343 details["building_type"] = d["type_raw"]344 smoking = strip_accents(d.get("smoking_raw", "").lower())345 if smoking.startswith("no"):346 details["smoking"] = False347 elif smoking:348 details["smoking_raw"] = d["smoking_raw"]349 if details:350 lst.details = details351