Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/apartments_com.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2213# Last Modified : 2026-08-2214#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/apartments_com.py : Apartments.com (CoStar) — réseau US avec un91# vrai parc québécois (~500 propriétés / 8 400 unités via /qc/, surtout de92# grands gestionnaires). Le site est verrouillé par Akamai (403 en direct,93# via Scrapfly ET via Oxylabs — sondé 2026-08-18/22) : le scraping est94# délégué à l'ACTEUR APIFY MAISON gorgeous_thistle/ka-apartments-com95# (source : actors/ka-apartments-com de ce repo) qui passe par le Web96# Unlocker Bright Data — HTML server-rendered, pas de rendu JS.97# UNE annonce = UNE PROPRIÉTÉ (immeuble) : prix « à partir de » (minimum98# des plans d'unités), tous les plans dans details["plans"]. Les fiches99# détail sont lues en FRANÇAIS (/fr/) : description, GPS, commodités,100# galerie. Cache détail 30 j + CADENCE : l'inventaire CoStar bouge101# lentement, l'acteur ne tourne qu'aux LOUKA_APTS_INTERVAL_H heures ;102# entre deux runs on ré-émet les annonces actives depuis la BD (coût 0).103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import os108import re109import time110111import requests as _requests112113from ..schema import Listing114from .base import BaseConnector115from . import _detailutil as du116117APIFY_API = "https://api.apify.com/v2"118ACTOR = os.environ.get("LOUKA_APTS_ACTOR", "gorgeous_thistle~ka-apartments-com")119120SEARCH_URLS = ["https://www.apartments.com/qc/"] # toute la province121MAX_PAGES = int(os.environ.get("LOUKA_APTS_MAX_PAGES", "25"))122DETAIL_LIMIT = int(os.environ.get("LOUKA_APTS_DETAIL_LIMIT", "250"))123TTL_DAYS = float(os.environ.get("LOUKA_APTS_TTL_DAYS", "30"))124INTERVAL_H = float(os.environ.get("LOUKA_APTS_INTERVAL_H", "12"))125CONCURRENCY = int(os.environ.get("LOUKA_APTS_CONCURRENCY", "4"))126RUN_TIMEOUT = int(os.environ.get("LOUKA_APTS_RUN_TIMEOUT", "3600")) # s127128DETAIL_KEY = "v1"129PRICE_MIN, PRICE_MAX = 300, 12000 # garde-fous de loyer mensuel130131_MONEY_RX = re.compile(r"\$\s*([\d\s, ]+)")132_BEDS_LABEL_RX = re.compile(r"(\d+)\s*(?:bed|lit|c\.?\s*à\.?\s*c)", re.I)133_SQFT_RX = re.compile(r"([\d\s, ]+)\s*(?:pi²|sq\s*ft)", re.I)134135136def _money(text: str | None) -> float | None:137 m = _MONEY_RX.search(text or "")138 if not m:139 return None140 try:141 return float(re.sub(r"[^\d]", "", m.group(1)))142 except ValueError:143 return None144145146def _beds_count(label: str) -> float | None:147 low = (label or "").casefold()148 if "studio" in low or "bachelor" in low:149 return 0.0150 m = _BEDS_LABEL_RX.search(low)151 return float(m.group(1)) if m else None152153154def _unit_type(beds: float | None) -> str:155 if beds is None:156 return ""157 if beds <= 0:158 return "Studio"159 return "6½+" if beds >= 4 else f"{int(beds) + 2}½"160161162def _fmt_price(price: float) -> str:163 return f"{price:,.0f} $/mois".replace(",", " ")164165166def _split_address(addr: str) -> tuple[str, str]:167 """« 1411 St Du Fort, Montréal, QC H3H 2N7 » -> (rue, ville)."""168 parts = [p.strip() for p in (addr or "").split(",") if p.strip()]169 if len(parts) >= 3:170 return ", ".join(parts[:-2]), parts[-2]171 return addr or "", ""172173174class ApartmentsComConnector(BaseConnector):175 source_id = "apartments_com"176 request_delay = 1.0177178 # -- orchestration de l'acteur Apify --------------------------------------179 def _run_actor(self, payload: dict, token: str) -> list[dict]:180 """Lance l'acteur, attend la fin, retourne les items du dataset."""181 r = _requests.post(182 f"{APIFY_API}/acts/{ACTOR}/runs?waitForFinish=120",183 json=payload, timeout=180,184 headers={"Authorization": f"Bearer {token}"})185 r.raise_for_status()186 run = r.json()["data"]187 deadline = time.time() + RUN_TIMEOUT188 while run["status"] in ("READY", "RUNNING") and time.time() < deadline:189 time.sleep(10)190 run = _requests.get(191 f"{APIFY_API}/actor-runs/{run['id']}", timeout=60,192 headers={"Authorization": f"Bearer {token}"}).json()["data"]193 if run["status"] != "SUCCEEDED":194 raise RuntimeError(f"acteur {ACTOR} : run {run['id']} "195 f"terminé en {run['status']}")196 items: list[dict] = []197 offset = 0198 while True:199 batch = _requests.get(200 f"{APIFY_API}/datasets/{run['defaultDatasetId']}/items"201 f"?limit=1000&offset={offset}", timeout=120,202 headers={"Authorization": f"Bearer {token}"}).json()203 items.extend(batch)204 if len(batch) < 1000:205 return items206 offset += 1000207208 # -- cadence / ré-émission -------------------------------------------------209 def _last_ok_sync(self, cache: du.TtlDetailCache) -> float:210 row = cache.con.execute(211 "SELECT MAX(ts) AS t FROM sync_log WHERE source=? AND ok=1"212 " AND found > 0", (self.source_id,)).fetchone()213 return row["t"] or 0.0214215 def _active_rows(self, cache: du.TtlDetailCache) -> list:216 return cache.con.execute(217 "SELECT external_id, url, title, address, sector, city, unit_type,"218 " bedrooms, bathrooms, price, price_label, availability,"219 " availability_date, area_sqft, pets, furnished, description,"220 " amenities, details, images, lat, lng"221 " FROM listings WHERE source=? AND active=1", (self.source_id,)222 ).fetchall()223224 def _listing_from_row(self, r) -> Listing:225 def js(s, default):226 try:227 return json.loads(s) if s else default228 except ValueError:229 return default230 return Listing(231 source=self.source_id, external_id=r["external_id"],232 url=r["url"], title=r["title"] or "", address=r["address"] or "",233 sector=r["sector"] or "", city=r["city"] or "",234 unit_type=r["unit_type"] or "", bedrooms=r["bedrooms"],235 bathrooms=r["bathrooms"], price=r["price"],236 price_label=r["price_label"] or "",237 availability=r["availability"] or "",238 availability_date=r["availability_date"],239 area_sqft=r["area_sqft"], pets=r["pets"],240 furnished=(None if r["furnished"] is None else bool(r["furnished"])),241 description=r["description"] or "",242 amenities=js(r["amenities"], []), details=js(r["details"], {}),243 images=js(r["images"], []), lat=r["lat"], lng=r["lng"],244 )245246 # -- payload détail -> champs Listing ---------------------------------------247 @staticmethod248 def _std_detail(d: dict) -> dict:249 std = {k: d[k] for k in ("description", "images", "lat", "lng",250 "amenities") if d.get(k)}251 if d.get("street"):252 std["address"] = d["street"]253 if d.get("city"):254 std["city"] = d["city"]255 plans, seen = [], set()256 for pl in d.get("plans") or []: # grille dupliquée desktop/mobile257 sig = (pl.get("key"), pl.get("name"), pl.get("rent"))258 if sig not in seen:259 seen.add(sig)260 plans.append(pl)261 rents = [p for p in (_money(pl.get("rent")) for pl in plans)262 if p is not None and PRICE_MIN <= p <= PRICE_MAX]263 if rents:264 std["price"] = min(rents)265 std["price_label"] = (f"à partir de {_fmt_price(min(rents))}"266 if len(plans) > 1 else _fmt_price(min(rents)))267 # immeuble multi-plans : minimum, cohérent avec le prix « à partir268 # de » — et ça évite que finalize() devine n'importe quoi dans la269 # description marketing (« appartements de 1 à 4 chambres »)270 beds = {pl.get("beds") for pl in plans if pl.get("beds") is not None}271 baths = {pl.get("baths") for pl in plans if pl.get("baths") is not None}272 if beds:273 std["bedrooms"] = min(beds)274 if len(beds) == 1:275 std["unit_type"] = _unit_type(std["bedrooms"])276 if baths:277 std["bathrooms"] = min(baths)278 if len(plans) == 1:279 m = _SQFT_RX.search(" ".join(plans[0].get("details") or []))280 if m:281 try:282 std["area_sqft"] = float(re.sub(r"[^\d]", "", m.group(1)))283 except ValueError:284 pass285 avails = [pl.get("availability") or "" for pl in plans]286 now = next((a for a in avails287 if "maintenant" in a.casefold() or "now" in a.casefold()),288 "")289 if now or any(avails):290 std["availability"] = now or next(a for a in avails if a)291 if plans:292 std["details"] = {"plans": [293 {k: pl[k] for k in ("name", "rent", "beds", "baths",294 "details", "availability") if k in pl}295 for pl in plans]}296 return std297298 # -- pipeline principal ------------------------------------------------------299 def fetch(self) -> list[Listing]:300 token = os.environ.get("APIFY_TOKEN")301 bd_token = os.environ.get("BRIGHTDATA_API_KEY")302 if not token:303 raise RuntimeError("APIFY_TOKEN manquant (voir .env)")304 if not bd_token:305 raise RuntimeError("BRIGHTDATA_API_KEY manquant (voir .env)")306307 cache = du.TtlDetailCache(self, budget=0, ttl_days=TTL_DAYS,308 key=DETAIL_KEY, fetch_html=lambda _u: "")309 try:310 # inventaire lent + acteur payant : entre deux vrais runs on311 # ré-émet les actives telles quelles (aucune requête réseau)312 age_h = (time.time() - self._last_ok_sync(cache)) / 3600313 actives = self._active_rows(cache)314 if actives and age_h < INTERVAL_H:315 return [self._listing_from_row(r) for r in actives]316317 fresh = {r["external_id"] for r in cache.con.execute(318 "SELECT external_id FROM detail_cache"319 " WHERE source=? AND key=? AND fetched_at > ?",320 (self.source_id, DETAIL_KEY,321 time.time() - TTL_DAYS * 86400)).fetchall()}322 # rattrapage : actives jamais enrichies (sans GPS ou description)323 extra = [f'{r["external_id"]}|{r["url"]}' for r in actives324 if r["external_id"] not in fresh325 and (r["lat"] is None or not (r["description"] or "").strip())]326327 items = self._run_actor({328 "searchUrls": SEARCH_URLS,329 "maxPages": MAX_PAGES,330 "getDetails": True,331 "maxDetails": DETAIL_LIMIT,332 "skipDetailIds": sorted(fresh),333 "extraDetailIds": extra[:DETAIL_LIMIT],334 "brightdataToken": bd_token,335 "brightdataZone": os.environ.get("BRIGHTDATA_ZONE",336 "web_unlocker1"),337 "concurrency": CONCURRENCY,338 }, token)339340 for it in items:341 if it.get("kind") == "detail" and it.get("id"):342 payload = {k: v for k, v in it.items()343 if k not in ("kind",) and v is not None}344 cache.put(str(it["id"]), payload)345346 out: dict[str, Listing] = {}347 for it in items:348 if it.get("kind") != "listing":349 continue350 pid = str(it["id"])351 street, city = _split_address(it.get("address") or "")352 rents = [(r.get("beds") or "", _money(r.get("price")))353 for r in it.get("rents") or []]354 prices = [p for _b, p in rents355 if p is not None and PRICE_MIN <= p <= PRICE_MAX]356 from_price = any("+" in (r.get("price") or "")357 for r in it.get("rents") or [])358 beds = {b for b in (_beds_count(lbl) for lbl, _p in rents)359 if b is not None}360 lst = Listing(361 source=self.source_id,362 external_id=pid,363 url=(it.get("url") or "").replace(364 "www.apartments.com/", "www.apartments.com/fr/", 1),365 title=(it.get("title") or street)[:200],366 address=street,367 city=city,368 price=min(prices) if prices else None,369 price_label=((f"à partir de {_fmt_price(min(prices))}"370 if from_price or len(prices) > 1371 else _fmt_price(min(prices)))372 if prices else ""),373 unit_type=_unit_type(beds.pop() if len(beds) == 1374 else None),375 amenities=it.get("amenities") or [],376 images=[it["image"]] if it.get("image") else [],377 )378 detail, _f = cache.peek(pid)379 if detail:380 du.apply_detail(lst, self._std_detail(detail))381 if detail.get("name"):382 lst.title = detail["name"][:200]383 if lst.price is None or not (PRICE_MIN <= lst.price384 <= PRICE_MAX):385 continue # « Call for Rent » : pas affichable386 out[pid] = lst387 return list(out.values())388 finally:389 cache.close()390