Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/res_cogir.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2914#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/res_cogir.py : Résidences Cogir (residencescogir.com) — 8591# résidences privées pour aînés (RPA) partout au Québec : réseaux Jazz,92# ex-Sélection (Domaine des Forges, Jardins de Renoir…), Villa, etc.93# Domaine DISTINCT de cogir.net (le connecteur `cogir` couvre le locatif94# traditionnel Cogir Immobilier — aucun doublon avec les RPA d'ici).95# Site rendu serveur mais derrière un WAF (403 en direct) : tout passe par96# Scrapfly ASP sans rendu JS. Le sitemap.xml liste les fiches97# /residences-aines-<ville>/<slug> (les Venvi « -ontario » sont exclues) ;98# chaque fiche expose le tableau « Modèles disponibles » (Type | Plan |99# À partir ($)), l'adresse civique (lien Google Maps), le téléphone, les100# coordonnées GPS (widget Walk Score) et la galerie. Une annonce Lou-Ka par101# résidence × typologie, prix plancher « à partir de » ; la superficie est102# récupérée du nom de fichier du plan (« …_3.5_typeA_702pc.jpg »).103# -----------------------------------------------------------------------------104from __future__ import annotations105106import html as _html107import re108import time109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type113from .base import BaseConnector114115SITEMAP = "https://residencescogir.com/sitemap.xml"116117_RES_URL_RE = re.compile(118 r"https://residencescogir\.com/residences-aines-[a-z0-9-]+/[a-z0-9-]+$")119_ADDR_RE = re.compile(120 r'fa-location-dot[^<]*</i>\s*([^<]{10,120})<')121_LAT_RE = re.compile(r"lat['\"]?\s*[:=]\s*(-?\d+\.\d+)")122_LNG_RE = re.compile(r"lng['\"]?\s*[:=]\s*(-?\d+\.\d+)")123_PHONE_RE = re.compile(r'href="tel:([\d\s\-().+]{7,20})"')124_PRICE_RE = re.compile(r"([\d][\d\s,]{2,8})\s*\$")125_AREA_IN_PLAN_RE = re.compile(r"_(\d{3,4})\s*pc", re.I)126_IMG_RE = re.compile(127 r"https://residencescogir\.com/uploads/residence/"128 r"(?:banner_fr|gallery_imgs|image)/[^\"\s\\']+\.(?:jpe?g|png|webp)", re.I)129130131class ResidencesCogirConnector(BaseConnector):132 source_id = "res_cogir"133 request_delay = 0.8134 timeout = 60135 max_images = 15136137 def _get_html(self, url: str) -> str:138 """HTML via Scrapfly ASP (WAF sur tout le domaine), sans rendu JS —139 les fiches sont rendues serveur."""140 return self.get_scrapfly(url, render_js=False)141142 # -- fiche résidence -------------------------------------------------------------143 def _parse_residence(self, url: str, html: str) -> list[Listing]:144 soup = BeautifulSoup(html, "html.parser")145 slug = url.rstrip("/").rsplit("/", 1)[-1]146147 # nom : <title> « Jazz Lévis | Résidences Cogir | … »148 name = slug.replace("-", " ").title()149 t = soup.find("title")150 if t is not None:151 first = _html.unescape(t.get_text()).split("|")[0].strip()152 if 2 <= len(first) <= 60:153 name = first154155 # adresse « 7, rue Saint Thomas, Lévis, Quebec, G6V 5R1 » (lien Maps)156 address = city = ""157 m = _ADDR_RE.search(html)158 if m:159 full = re.sub(r"\s+", " ", _html.unescape(m.group(1))).strip()160 full = full.replace(" ", " ")161 parts = [p.strip() for p in full.split(",") if p.strip()]162 if len(parts) >= 4: # …, ville, province, code163 city = parts[-3]164 address = ", ".join(parts[:-3])165 else:166 address = full167 if not city: # repli : segment d'URL168 seg = url.rstrip("/").rsplit("/", 2)[-2]169 city = seg.replace("residences-aines-", "").replace("-", " ").title()170171 lat = lng = None172 ml, mg = _LAT_RE.search(html), _LNG_RE.search(html)173 if ml and mg:174 try:175 lat, lng = float(ml.group(1)), float(mg.group(1))176 except ValueError:177 lat = lng = None178179 contact: dict = {}180 m = _PHONE_RE.search(html)181 if m:182 contact["phone"] = m.group(1).strip()183184 # description : premier paragraphe long de la fiche185 desc = ""186 for p in soup.find_all("p"):187 txt = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()188 if len(txt) >= 120 and "crédit d" not in txt.lower():189 desc = txt190 break191192 images = [u for u in dict.fromkeys(_IMG_RE.findall(html))193 if not re.search(r"logo|icon", u, re.I)][: self.max_images]194195 # tableau(x) « Modèles disponibles » : Type | Plans | À partir ($)196 out: list[Listing] = []197 seen: set[str] = set()198 for table in soup.select("section.model-table table"):199 for tr in table.find_all("tr"):200 tds = tr.find_all("td")201 if len(tds) < 2:202 continue203 raw_type = re.sub(r"\s+", " ",204 tds[0].get_text(" ", strip=True)).strip()205 if not raw_type or len(raw_type) > 30:206 continue207 pm = _PRICE_RE.search(tds[-1].get_text(" ", strip=True))208 if not pm:209 continue210 try:211 price = float(pm.group(1).replace(" ", "")212 .replace(" ", "").replace(",", ""))213 except ValueError:214 continue215 if not 400 <= price <= 20000:216 continue217 area = None218 a = tr.find("a", href=True)219 if a is not None:220 am = _AREA_IN_PLAN_RE.search(a["href"])221 if am:222 area = float(am.group(1))223 eid = f"{slug}-{re.sub(r'[^a-z0-9]+', '-', raw_type.lower()).strip('-')}"224 if eid in seen: # même typologie répétée225 continue226 seen.add(eid)227 out.append(Listing(228 source=self.source_id,229 external_id=eid,230 url=url,231 title=f"{raw_type} — {name}",232 address=address,233 city=city,234 unit_type=normalize_unit_type(raw_type),235 price=price,236 price_label=f"À partir de {price:,.0f} $ par mois"237 .replace(",", " "),238 availability="Modèles disponibles",239 area_sqft=area,240 description=desc,241 details={"Résidence pour aînés": "oui",242 **({"contact": contact} if contact else {})},243 images=images,244 lat=lat,245 lng=lng,246 ))247 return out248249 def fetch(self) -> list[Listing]:250 # Un raté transitoire Scrapfly sur le sitemap (contenu vide, vu251 # 2026-08-29) produisait un faux « 0 trouvé ok » : retry court, puis252 # erreur franche plutôt qu'un zéro silencieux.253 urls: list[str] = []254 for attempt in range(3):255 xml = self._get_html(SITEMAP)256 urls = sorted({u for u in re.findall(r"<loc>([^<]+)</loc>", xml)257 if _RES_URL_RE.match(u) and "-ontario/" not in u})258 if urls:259 break260 if attempt < 2:261 time.sleep(5 * (attempt + 1))262 else:263 raise RuntimeError(264 "sitemap sans URL de résidence après 3 essais Scrapfly")265 out: list[Listing] = []266 for url in urls:267 try:268 html = self._get_html(url)269 if html:270 out.extend(self._parse_residence(url, html))271 except Exception:272 continue273 if not out:274 raise RuntimeError(275 f"0 annonce extraite des {len(urls)} fiches du sitemap")276 return out277