Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/appfolio.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/appfolio.py : connecteur GÉNÉRIQUE AppFolio (appfolio.com)91# Certains gestionnaires ontariens publient leur parc sur le portail AppFolio :92# `https://<sous-domaine>.appfolio.com/listings` — HTML rendu serveur (cartes93# `.js-listing-item`), page unique « Showing all available listings », aucun94# rendu JS ni pagination nécessaires. Plutôt que N modules copiés-collés, ce95# module lit le registre data/appfolio_clients.json ({id, name, subdomain…},96# validés en live le 2026-08-27) et GÉNÈRE une sous-classe de BaseConnector97# par client (source_id = "apf_<id>"), déposée dans les globals du module98# pour le registre auto-découvrant (connectors/__init__.py). Même gabarit99# que liftsystem.py / buildium.py.100# NB recherche 2026-08-27 : AppFolio est RARE en Ontario (longue traîne ON101# massivement sur Buildium) — un seul client validé (Fuse, Barrie) après102# balayage Serper + scan des ~240 gestionnaires cartographiés ; le connecteur103# est prêt pour les suivants. Les portails servent tout le Canada/US et les104# adresses sont en texte libre : la province est déduite du CODE POSTAL105# canadien (première lettre K/L/M/N/P = ON, G/H/J = QC), tout le reste est106# ignoré. Filtre résidentiel longue durée (exclusion parking, entreposage,107# commercial, court terme). Galerie photo de la fiche via le cache BD108# self.detail() (images.cdn.appfolio.com/<client>/images/<uuid>/large.jpg).109#110# Expansion Ontario — activer via LOUKA_ONTARIO=1111# (voir gestion-immobiliere-ontario.md) : sans la variable, toutes les112# classes générées sont `disabled` et donc exclues du registre / de la prod.113# -----------------------------------------------------------------------------114from __future__ import annotations115116import hashlib117import json118import os119import re120from pathlib import Path121from urllib.parse import urljoin122123from bs4 import BeautifulSoup124125from ..schema import Listing, normalize_unit_type, parse_price126from .base import BaseConnector127128# Gate expansion Ontario : rien ne s'active en prod sans LOUKA_ONTARIO=1129_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"130131REGISTRY_PATH = Path(__file__).resolve().parents[2] / "data" / \132 "appfolio_clients.json"133134# Code postal canadien dans l'adresse libre — la 1re lettre (district de tri)135# donne la province sans ambiguïté : K/L/M/N/P = Ontario, G/H/J = Québec.136# Les adresses US (« Chicago, IL 60649 ») ne matchent pas -> ignorées.137_POSTAL_RE = re.compile(r"\b([A-Za-z])(\d[A-Za-z])\s?(\d[A-Za-z]\d)\b")138_POSTAL_PROVINCE = {**{c: "ON" for c in "KLMNP"}, **{c: "QC" for c in "GHJ"}}139140# Résidentiel longue durée seulement : stationnements, entreposage, commerces141# et court terme sont hors sujet pour Lou-Ka (logements au mois).142_NON_RESIDENTIAL_RE = re.compile(143 r"\b(parking|stationnement|storage|entreposage|locker|garage only|"144 r"commercial|office space|retail|warehouse)\b", re.I)145_SHORT_TERM_RE = re.compile(146 r"\b(short[\s-]?term|nightly|per night|par nuit|vacation rental|"147 r"weekly rate|airbnb|court terme|campsites?|campground|nature camp)\b",148 re.I)149150# « 3 bd / 1.5 ba » ou « Studio / 1 ba » des cartes AppFolio151_BED_BATH_RE = re.compile(152 r"(studio|\d+(?:\.\d+)?)\s*bd?\s*/\s*(\d+(?:\.\d+)?)\s*ba", re.I)153154# galerie de la fiche détail (préférer les variantes large.jpg)155_GALLERY_IMG_RE = re.compile(156 r"https://images\.cdn\.appfolio\.com/[^\"'\s\\)]+/large\.[a-z]{3,4}", re.I)157158# mots des segments d'adresse qui ne sont PAS une ville (voir _parse_address)159_NOT_CITY = {"", "on", "ontario", "ca", "canada", "qc", "quebec", "québec"}160161162def _load_registry() -> list[dict]:163 """Entrées validées du registre (subdomain présent, status == valide)."""164 try:165 data = json.loads(REGISTRY_PATH.read_text("utf-8"))166 except (OSError, ValueError):167 return []168 return [c for c in data.get("clients") or []169 if c.get("subdomain") and c.get("status") == "valide"]170171172def _parse_address(raw: str) -> tuple[str, str, str] | None:173 """(ville, province, code postal) depuis l'adresse libre AppFolio, ou None174 si hors ON/QC. Formats vus en live : « 241 Nottawasaga Street - 2 (B),175 Orillia L3V 3K2 », « 300 Cundles St West - Upper, Barrie, ON, CA L4N 7C9 »,176 « 37 Peel St - Apt - 808, Barrie, CA L4M 3L1 »."""177 m = _POSTAL_RE.search(raw)178 if not m:179 return None # pas de code postal canadien -> US180 prov = _POSTAL_PROVINCE.get(m.group(1).upper())181 if not prov:182 return None # autre province canadienne183 postal = f"{m.group(1)}{m.group(2)} {m.group(3)}".upper()184 # ville = dernier segment (virgules) qui n'est ni ON/CA/Canada ni le postal185 before = raw[: m.start()].strip()186 for seg in reversed([s.strip() for s in before.split(",")]):187 seg = re.sub(r"\b(ON|QC|CA)\b\.?$", "", seg, flags=re.I).strip()188 if seg.lower() not in _NOT_CITY and not any(ch.isdigit() for ch in seg):189 return seg, prov, postal190 return "", prov, postal191192193class AppfolioConnector(BaseConnector):194 """Base commune des connecteurs AppFolio générés — non enregistrée195 elle-même (source_id vide) ; chaque sous-classe reçoit son entrée de196 registre dans l'attribut de classe `client`."""197198 source_id = "" # les sous-classes générées le définissent199 client: dict = {} # entrée du registre (name, subdomain, site…)200 request_delay = 1.0 # politesse — petits gestionnaires, on y va mollo201 max_listings = 300 # garde-fou (client validé le plus gros : 25)202 max_images = 20203204 @property205 def base_url(self) -> str:206 return f"https://{self.client['subdomain']}.appfolio.com"207208 def fetch(self) -> list[Listing]:209 soup = BeautifulSoup(self.get(self.base_url + "/listings").text,210 "html.parser")211 listings: list[Listing] = []212 for item in soup.select(".js-listing-item"):213 if len(listings) >= self.max_listings: # garde-fou APRÈS filtres214 break215 lst = self._listing(item)216 if lst is not None:217 listings.append(lst)218 return listings219220 # -- une annonce par carte .js-listing-item --------------------------------221 def _listing(self, item) -> Listing | None:222 try:223 link = item.select_one("a.js-link-to-detail") or \224 item.select_one('a[href*="/listings/detail/"]')225 if link is None:226 return None227 href = link.get("href") or ""228 m = re.search(r"/listings/detail/([0-9a-f-]{16,})", href)229 if not m:230 return None231 uid = m.group(1)232 url = urljoin(self.base_url, href)233234 def txt(sel: str) -> str:235 el = item.select_one(sel)236 return el.get_text(" ", strip=True) if el else ""237238 # adresse libre -> ville/province/postal via code postal canadien239 raw_addr = txt(".js-listing-address")240 parsed = _parse_address(raw_addr)241 if parsed is None:242 return None # US ou autre province : hors sujet243 city, prov, postal = parsed244245 title = txt(".js-listing-title")246 description = txt(".js-listing-description")247 if _NON_RESIDENTIAL_RE.search(f"{title} {description[:200]}") or \248 _SHORT_TERM_RE.search(f"{title} {description[:200]}"):249 return None250251 # loyer : bandeau mobile, sinon <dd> sous l'étiquette RENT252 price = parse_price(txt(".js-listing-blurb-rent"))253 area = None254 for box in item.select(".detail-box__item"):255 label = (box.select_one("dt") or box).get_text(" ", strip=True)256 value = box.select_one("dd")257 value = value.get_text(" ", strip=True) if value else ""258 low = label.lower()259 if "rent" in low and price is None:260 price = parse_price(value)261 elif "square" in low:262 try:263 v = float(value.replace(",", "").strip() or 0)264 if 80 <= v <= 20000:265 area = v266 except ValueError:267 pass268269 # « 3 bd / 1.5 ba » / « Studio / 1 ba » — sinon None (inconnu)270 bedrooms = bathrooms = None271 unit_type = ""272 bb = _BED_BATH_RE.search(txt(".js-listing-blurb-bed-bath") or273 item.get_text(" ", strip=True))274 if bb:275 if bb.group(1).lower() == "studio":276 bedrooms, unit_type = 0.0, "Studio"277 else:278 bedrooms = float(bb.group(1))279 unit_type = normalize_unit_type(f"{bedrooms:g} chambres")280 bathrooms = float(bb.group(2))281282 availability = txt(".js-listing-available")283284 # paragraphe « Utilities Included: … / Appliances: … » de la carte285 details: dict = {}286 for p in item.select(".listing-item__body p"):287 for b in p.find_all("span", style=re.compile("bold")):288 key = b.get_text(strip=True).rstrip(":").strip()289 val = (b.next_sibling or "")290 val = str(val).strip() if isinstance(val, str) else ""291 if key and val:292 details[key] = val293294 # aperçu photo de la carte (lazy-load : data-original)295 preview = ""296 img = item.select_one("img.js-listing-image")297 if img:298 preview = (img.get("data-original") or "").strip()299 if "place_holder" in preview:300 preview = ""301302 # fiche détail (description complète + galerie large.jpg) via le303 # cache BD : revisitée seulement quand la carte de la liste change304 feed_key = hashlib.sha1("|".join(str(x) for x in (305 price, availability, preview, raw_addr, description[:80],306 )).encode("utf-8")).hexdigest()307 d = self.detail(uid, feed_key, lambda: self._fetch_detail(url))308 full_desc = (d.get("description") or description).strip()309 images = [u for u in [preview] + list(d.get("images") or []) if u]310 images = list(dict.fromkeys(images)) # dédup en gardant l'ordre311312 address = raw_addr313 return Listing(314 source=self.source_id,315 external_id=uid,316 url=url,317 title=title or address,318 address=address,319 city=city,320 province=prov,321 unit_type=unit_type,322 bedrooms=bedrooms,323 bathrooms=bathrooms,324 price=price,325 price_label=f"{price:.0f} $ /mois" if price else "",326 availability=availability,327 area_sqft=area,328 description=full_desc[:1200],329 details=details,330 images=images[: self.max_images],331 )332 except Exception:333 return None334335 def _fetch_detail(self, url: str) -> dict:336 """Description complète + galerie (large.jpg) de la fiche détail."""337 out: dict = {"images": [], "description": ""}338 if not url:339 return out340 try:341 page = self.get(url).text342 except Exception:343 return out344 soup = BeautifulSoup(page, "html.parser")345 desc = soup.select_one(".listing-detail__description")346 if desc:347 out["description"] = desc.get_text("\n", strip=True)348 images: list[str] = []349 for u in _GALLERY_IMG_RE.findall(page):350 if u not in images:351 images.append(u)352 out["images"] = images[: self.max_images]353 return out354355356# -----------------------------------------------------------------------------357# Génération : une sous-classe par client du registre, déposée dans les globals358# du module — connectors/__init__.py (scan de vars(module)) les découvre alors359# comme n'importe quel connecteur écrit à la main.360# -----------------------------------------------------------------------------361def _make_connector(entry: dict) -> type[AppfolioConnector]:362 cls = type(363 f"Apf{re.sub(r'[^A-Za-z0-9]', '', entry['id']).capitalize()}Connector",364 (AppfolioConnector,),365 {366 "source_id": f"apf_{entry['id']}",367 "client": entry,368 # Expansion Ontario — activer via LOUKA_ONTARIO=1369 # (voir gestion-immobiliere-ontario.md)370 "disabled": not _ONTARIO,371 "__doc__": f"Connecteur AppFolio généré — {entry.get('name')} "372 f"({entry.get('subdomain')}.appfolio.com).",373 },374 )375 return cls376377378def _register_all() -> None:379 for entry in _load_registry():380 cls = _make_connector(entry)381 globals()[cls.__name__] = cls382383384_register_all()385