Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/roomies.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# Last Modified : 2026-08-1714#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/roomies.py : Roomies.ca — chambres et colocation (segment que les91# gestionnaires ne couvrent pas). Site Laravel/Livewire server-rendered,92# robots.txt entièrement ouvert, aucun anti-bot (curl simple = 200).93# Découverte par les pages villes `/{ville}-qc?page=N` (les sitemaps94# `sitemap/rooms.xml` répondent 504 par intermittence — non fiables).95# Fiche `/rooms/<id>` : JSON-LD `Room` complet (offers.price mensuel,96# availabilityStarts, lat/lng, petsAllowed, chambres/SDB de l'appartement,97# PostalAddress, amenityFeature) + description intégrale dans un div98# `prose` + galerie Cloudinary. On ignore les profils de chercheurs de99# colocataires (/profiles) : seules les chambres offertes sont des annonces.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import datetime104import os105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing110from .base import BaseConnector111from . import _detailutil as du112113BASE = "https://www.roomies.ca"114115# villes québécoises servies (slug -qc) ; une page absente (404) est ignorée116CITIES = {117 "montreal-qc": "Montréal", "quebec-qc": "Québec", "laval-qc": "Laval",118 "gatineau-qc": "Gatineau", "longueuil-qc": "Longueuil",119 "sherbrooke-qc": "Sherbrooke", "trois-rivieres-qc": "Trois-Rivières",120 "levis-qc": "Lévis", "brossard-qc": "Brossard",121 "terrebonne-qc": "Terrebonne", "repentigny-qc": "Repentigny",122 "saint-jean-sur-richelieu-qc": "Saint-Jean-sur-Richelieu",123 "drummondville-qc": "Drummondville", "granby-qc": "Granby",124 "saguenay-qc": "Saguenay",125}126MAX_PAGES = int(os.environ.get("LOUKA_ROOMIES_MAX_PAGES", "20"))127DETAIL_LIMIT = int(os.environ.get("LOUKA_ROOMIES_DETAIL_LIMIT", "250"))128TTL_DAYS = float(os.environ.get("LOUKA_ROOMIES_TTL_DAYS", "5"))129130_ROOM_LINK_RE = re.compile(r'href="(?:https://www\.roomies\.ca)?(/rooms/(\d+))"')131_PHOTO_RE = re.compile(132 r'https://cloudinary\.roomies\.pics/image/upload/[^"\\\s]+?/(\w+)')133134135def _parse_fiche(html: str) -> dict:136 out: dict = {}137 for node in du.ld_nodes(html):138 if node.get("@type") != "Room":139 continue140 name = str(node.get("name") or "")141 out["type_label"] = name.split("|")[0].strip() # « Furnished room in… »142 addr = node.get("address") or {}143 out["address"] = (addr.get("streetAddress") or "").strip()144 out["postal_code"] = (addr.get("postalCode") or "").strip()145 out["lat"] = node.get("latitude")146 out["lng"] = node.get("longitude")147 if node.get("petsAllowed") is not None:148 out["pets"] = "oui" if node["petsAllowed"] else "non"149 details = {}150 if node.get("numberOfBedrooms"):151 details["Chambres (logement)"] = str(node["numberOfBedrooms"])152 if node.get("numberOfBathroomsTotal"):153 details["Salles de bain"] = str(node["numberOfBathroomsTotal"])154 if details:155 out["details"] = details156 feats = node.get("amenityFeature") or []157 amenities = []158 for f in feats:159 if isinstance(f, dict) and f.get("name") and f.get("value") is not False:160 amenities.append(str(f["name"]))161 if f["name"] == "Furnished":162 out["furnished"] = True163 if amenities:164 out["amenities"] = amenities165 offers = node.get("offers") or {}166 try:167 out["price"] = float(offers.get("price"))168 except (TypeError, ValueError):169 pass170 starts = str(offers.get("availabilityStarts") or "")[:10]171 if starts:172 out["availability_date"] = ("now" if starts173 <= datetime.date.today().isoformat()174 else starts)175 if node.get("description"):176 out["description"] = str(node["description"]).strip()[:6000]177178 # description intégrale (le JSON-LD est tronqué à ~250 caractères)179 soup = BeautifulSoup(html, "html.parser")180 prose = soup.find("div", class_=lambda c: c and "prose" in c181 and "break-words" in c)182 if prose:183 full = prose.get_text("\n", strip=True)184 if len(full) > len(out.get("description") or ""):185 out["description"] = full[:6000]186187 # galerie Cloudinary : dédupliquée par identifiant public, format standard188 photos, seen = [], set()189 for pid in _PHOTO_RE.findall(html):190 if pid in seen or len(pid) < 12:191 continue192 seen.add(pid)193 photos.append("https://cloudinary.roomies.pics/image/upload/"194 f"c_fill,f_jpg,fl_lossy,g_auto,h_512,q_auto:good,w_896/{pid}")195 if photos:196 out["images"] = photos197 return out198199200class RoomiesConnector(BaseConnector):201 source_id = "roomies"202 request_delay = 0.8203204 def _city_room_ids(self, slug: str) -> list[str]:205 ids, page = [], 1206 while page <= MAX_PAGES:207 url = f"{BASE}/{slug}" + (f"?page={page}" if page > 1 else "")208 try:209 html = self.get(url).text210 except Exception:211 break212 found = [rid for _, rid in _ROOM_LINK_RE.findall(html)]213 fresh = [r for r in found if r not in ids]214 if not fresh:215 break216 ids.extend(fresh)217 page += 1218 return ids219220 def fetch(self) -> list[Listing]:221 cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS)222 out: dict[str, Listing] = {}223 try:224 for slug, city in CITIES.items():225 for rid in self._city_room_ids(slug):226 if rid in out:227 continue228 url = f"{BASE}/rooms/{rid}"229 payload = cache.get(rid, url, _parse_fiche)230 if not payload or payload.get("gone"):231 continue232 price = payload.get("price")233 avail = payload.get("availability_date")234 type_label = (payload.get("type_label") or "").lower()235 unit_type = ("Studio" if "studio" in type_label236 and "shared" not in type_label else "Chambre")237 lst = Listing(238 source=self.source_id,239 external_id=rid,240 url=url,241 title=(payload.get("type_label") or "Chambre")242 + (f" — {payload['address']}" if payload.get("address") else ""),243 address=payload.get("address") or "",244 city=city,245 unit_type=unit_type,246 price=price,247 price_label=(f"{price:,.0f} $/mois".replace(",", " ")248 if price else ""),249 availability_date=avail,250 availability=("Libre immédiatement" if avail == "now"251 else f"Libre le {avail}" if avail else ""),252 description=payload.get("description") or "",253 amenities=payload.get("amenities") or [],254 details=payload.get("details") or {},255 images=payload.get("images") or [],256 lat=payload.get("lat"),257 lng=payload.get("lng"),258 )259 if payload.get("postal_code"):260 lst.details["Code postal"] = payload["postal_code"]261 if payload.get("pets"):262 lst.pets = payload["pets"]263 if payload.get("furnished"):264 lst.furnished = True265 out[rid] = lst266 finally:267 cache.close()268 return list(out.values())269