Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/uptimo.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/uptimo.py : connecteur Uptimo Gestion immobilière (uptimo.ca)91# Apparts à Sherbrooke (Fleurimont, Mont-Bellevue, Jacques-Cartier…) et92# environs. WordPress Themify + Post Type Builder : l'archive93# /logements-a-louer/ (CPT « propriete », 15 cartes/page, ~6 pages) liste le94# catalogue à louer — cartes .ptb_post avec titre, arrondissement95# (taxonomie) et photo ; l'ID WordPress (classe post-<id>) sert96# d'external_id stable. Les fiches (via self.detail, cache BD) portent les97# champs structurés : « Adresse: », « Ville: », « Prix: »,98# « Type de propriété: » (2 1/2…), salles de bain, description et galerie.99# Aucun statut structuré de disponibilité — la date de libération n'apparaît100# qu'en texte libre dans la description (textmine central).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://www.uptimo.ca"113LIST_URL = f"{BASE}/logements-a-louer/"114115_POST_ID_RE = re.compile(r"\bpost-(\d+)\b")116_VARIANT_IMG = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)117118119class UptimoConnector(BaseConnector):120 source_id = "uptimo"121 request_delay = 0.6122 max_pages = 10 # garde-fou de pagination (6 pages observées)123 max_details = 90 # garde-fou fiches détail (77 propriétés au catalogue)124125 def fetch(self) -> list[Listing]:126 listings: dict[str, Listing] = {}127 for page in range(1, self.max_pages + 1):128 url = LIST_URL if page == 1 else f"{LIST_URL}page/{page}/"129 try:130 html = self.get(url).text131 except Exception:132 break133 soup = BeautifulSoup(html, "html.parser")134 cards = soup.select(".ptb_post")135 if not cards:136 break137 for card in cards:138 try:139 lst = self._parse_card(card)140 except Exception:141 continue142 if lst and lst.external_id not in listings:143 listings[lst.external_id] = lst144145 # fiches détail (cache BD) : adresse, ville, prix, type, description,146 # salles de bain, galerie147 self._fetched = 0148 for lst in listings.values():149 key = hashlib.sha1(150 f"{lst.title}|{lst.sector}|{lst.images[:1]}"151 .encode("utf-8")).hexdigest()152 try:153 payload = self.detail(lst.external_id, key,154 lambda u=lst.url: self._fetch_detail(u))155 except Exception:156 continue157 self._apply_detail(lst, payload)158 return list(listings.values())159160 # -- carte d'archive -------------------------------------------------------------161 def _parse_card(self, card) -> Listing | None:162 link = card.select_one("h3.ptb_post_title a[href]")163 if not link:164 return None165 url = link["href"]166 title = re.sub(r"\s+", " ", link.get_text(" ", strip=True)).strip()167 m = _POST_ID_RE.search(" ".join(card.get("class") or []))168 ext_id = m.group(1) if m else re.sub(r".*/propriete/([^/]+)/?.*", r"\1", url)169170 # arrondissement (taxonomie) : « Sherbrooke-Fleurimont »171 sector = ""172 tax = card.select_one(".ptb_taxonomies_tous_les_arrondissements")173 if tax:174 sector = re.sub(r"\s+", " ", tax.get_text(" ", strip=True)).strip()175 sector = re.sub(r"^Sherbrooke-", "", sector)176177 img = card.select_one("img[src]")178 images = []179 if img and str(img.get("src", "")).startswith("http"):180 images.append(_VARIANT_IMG.sub("", img["src"]))181182 # type d'unité dans le titre le cas échéant (« - Studio », « 3 1/2 »)183 unit_type = normalize_unit_type(title)184 if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",185 unit_type or ""):186 unit_type = ""187188 return Listing(189 source=self.source_id,190 external_id=str(ext_id),191 url=url,192 title=title,193 address="", # complété par la fiche194 sector=sector,195 city="Sherbrooke",196 unit_type=unit_type,197 availability="", # aucun statut structuré publié198 images=images,199 )200201 # -- fiche propriété (modules PTB) ---------------------------------------------202 def _fetch_detail(self, url: str) -> dict:203 if self._fetched >= self.max_details:204 raise RuntimeError("budget de fiches détail atteint")205 self._fetched += 1206 html = self.get(url).text207 soup = BeautifulSoup(html, "html.parser")208 out: dict = {}209210 def module_text(sel: str) -> str:211 el = soup.select_one(sel)212 return re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip() if el else ""213214 addr = module_text(".ptb_proprite_adresse")215 if addr:216 out["address"] = re.sub(r"^Adresse\s*:\s*", "", addr, flags=re.I)217 prix = module_text(".ptb_proprite_prix")218 if prix:219 out["price_label"] = re.sub(r"^Prix\s*:\s*", "", prix, flags=re.I)220221 # taxonomies : « Ville: Sherbrooke », « Type de propriété: 2 1/2 »,222 # « Nombre de salle(s) de bain: 1 »223 for tax in soup.select(".ptb_taxonomies"):224 t = re.sub(r"\s+", " ", tax.get_text(" ", strip=True)).strip()225 if t.lower().startswith("ville"):226 out["city"] = re.sub(r"^Ville\s*:\s*", "", t, flags=re.I)227 elif t.lower().startswith("type de propriété"):228 out["type_raw"] = re.sub(r"^Type de propriété\s*:\s*", "", t,229 flags=re.I)230 elif "salle(s) de bain" in t.lower():231 m = re.search(r"(\d+)\s*$", t)232 if m:233 out["bathrooms"] = int(m.group(1))234235 desc_el = soup.select_one(".ptb_textarea")236 if desc_el:237 out["description"] = re.sub(238 r"[ \t]+", " ", desc_el.get_text("\n", strip=True)).strip()[:1500]239240 images: list[str] = []241 for img in soup.select(".ptb_gallery img[src], "242 ".ptb_proprite_image_principal img[src]"):243 src = _VARIANT_IMG.sub("", str(img.get("src") or ""))244 if src.startswith("http") and src not in images:245 images.append(src)246 out["images"] = images[:20]247 return out248249 def _apply_detail(self, lst: Listing, d: dict) -> None:250 if not d:251 return252 if d.get("address"):253 lst.address = d["address"]254 if d.get("city"):255 # la taxonomie « Ville » mêle parfois la province (« Québec »,256 # « Québec, Sherbrooke ») : ne retenir qu'une ville réelle connue257 m = re.search(r"\b(Sherbrooke|Magog|Windsor|East Angus|Coaticook|"258 r"Ascot Corner|Lennoxville|Richmond)\b",259 d["city"], re.I)260 if m:261 lst.city = m.group(1).title()262 if d.get("price_label"):263 lst.price_label = d["price_label"]264 lst.price = parse_price(re.sub(r"(\d)[,\s](\d{3})", r"\1\2",265 d["price_label"]))266 if d.get("description"):267 lst.description = d["description"]268 if not lst.unit_type and d.get("type_raw"):269 ut = normalize_unit_type(d["type_raw"])270 if re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison", ut or ""):271 lst.unit_type = ut272 if d.get("bathrooms"):273 lst.details = {**lst.details, "bathrooms": d["bathrooms"]}274 if d.get("images"):275 lst.images = list(dict.fromkeys(d["images"] + lst.images))[:20]276