Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/sentinelle.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/sentinelle.py : connecteur La Sentinelle (lasentinellelevis.com)91# Immeuble de 144 condos locatifs au 7002, boul. Guillaume-Couture92# (Vieux-Lévis). La page /projet/ contient un TABLEAU structuré des unités93# (numéro, étage, superficie pi², type, prix, statut, lien fiche) : on ne94# visite que les fiches des unités « Disponible », via self.detail(...)95# (cache BD, clé = ligne du tableau) — la fiche apporte la date de96# disponibilité, la liste des commodités (ul.uk-list-disc), les photos97# et le plan.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, infer_city, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://lasentinellelevis.com"110LIST_URL = f"{BASE}/projet/"111SECTOR = "Vieux-Lévis"112ADDRESS = "7002, boul. Guillaume-Couture, Lévis, G6V 0C1"113PHONE = "418-741-3737" # lien tel: du pied de page (bureau de location)114115_SKIP_IMG = re.compile(r"logo|favicon|icon|brochu|promenade", re.I)116_STATUS_RE = re.compile(r"^(Disponible|Loué|Réservé)$", re.I)117118119class _BudgetReached(Exception):120 """Plafond de requêtes « fiche » atteint pour cette synchronisation."""121122123class SentinelleConnector(BaseConnector):124 source_id = "sentinelle"125 request_delay = 0.6126 max_details = 60 # plafond de vraies requêtes fiche par sync127128 def fetch(self) -> list[Listing]:129 html = self.get(LIST_URL).text130 soup = BeautifulSoup(html, "html.parser")131 self._fetches = 0132133 listings: list[Listing] = []134 seen: set[str] = set()135136 # Tableau des unités : <tr data-url=".../unite-NNN/"><td>104</td>137 # <td>Étage 1</td><td>1241</td><td>4½+</td><td>1695$</td>138 # <td>Disponible</td>...139 rows = soup.select("tr[data-url*='/unite-']")140 for tr in rows:141 try:142 lst = self._row_listing(tr)143 except Exception:144 continue145 if lst and lst.external_id not in seen:146 seen.add(lst.external_id)147 listings.append(lst)148 if rows:149 return listings150151 # Repli (si le tableau disparaît) : balayer les liens de fiches152 unit_urls = sorted(set(re.findall(153 rf'href="({re.escape(BASE)}/projet/etage-\d+/unite-\d+/)"', html)))154 for url in unit_urls[: self.max_details]:155 unit_no = url.rstrip("/").split("-")[-1]156 if f"unite-{unit_no}" in seen:157 continue158 try:159 payload = self._fetch_detail(url)160 except Exception:161 continue162 if payload.get("status") not in (None, "Disponible"):163 continue164 lst = self._build(unit_no, url, payload)165 seen.add(lst.external_id)166 listings.append(lst)167 return listings168169 # -- ligne du tableau -------------------------------------------------------170 def _row_listing(self, tr) -> Listing | None:171 url = (tr.get("data-url") or "").split("?")[0]172 m = re.search(r"/unite-(\d+)/?$", url)173 if not m:174 return None175 unit_no = m.group(1)176 cells = [td.get_text(" ", strip=True) for td in tr.find_all("td")]177178 row: dict = {}179 for c in cells:180 if _STATUS_RE.match(c):181 row["status"] = c.capitalize()182 elif re.match(r"^\d[\d\s]*\$$", c):183 row["price_label"] = c184 elif re.match(r"^Étage\s+\d+$", c):185 row["floor"] = int(re.search(r"\d+", c).group(0))186 elif re.match(r"^\d\s*(?:½|1/2)\s*\+?$", c):187 row["type"] = c188 elif re.match(r"^\d{3,5}$", c) and c != unit_no:189 v = float(c)190 if 80 <= v <= 20000:191 row["sqft"] = v192193 if row.get("status") and row["status"] != "Disponible":194 return None # loué / réservé : pas une annonce active195196 # Fiche de l'unité (cache BD : re-téléchargée si la ligne change)197 key = hashlib.sha1(("|".join(cells)).encode("utf-8")).hexdigest()198 try:199 payload = self.detail(f"unite-{unit_no}", key,200 lambda u=url: self._fetch_detail(u))201 except Exception: # _BudgetReached inclus : rien de caché202 payload = {}203 return self._build(unit_no, url, payload, row)204205 # -- fiche --------------------------------------------------------------------206 def _fetch_detail(self, url: str) -> dict:207 """Télécharge une fiche d'unité (appelé seulement hors cache)."""208 if self._fetches >= self.max_details:209 raise _BudgetReached()210 self._fetches += 1211 dhtml = self.get(url).text212 soup = BeautifulSoup(dhtml, "html.parser")213 text = soup.get_text("\n", strip=True)214 payload: dict = {}215216 m = re.search(r"Unité\s+(\d+)\s*-\s*(\d\s*(?:½|1/2)\s*\+?)", text)217 if m:218 payload["type"] = m.group(2).strip()219 fm = re.search(r"Étage\s+(\d+)", text)220 if fm:221 payload["floor"] = int(fm.group(1))222 sm = re.search(r"\n(Disponible|Loué|Réservé)\n", text)223 if sm:224 payload["status"] = sm.group(1)225226 am = re.search(r"Disponible à partir de\s*:\s*([^\n]+)", text)227 if am:228 payload["availability"] = \229 f"Disponible à partir de : {am.group(1).strip()}"230231 pm = re.search(r"^([\d\s ]{3,})\$\s*$", text, re.M)232 if pm:233 payload["price_label"] = pm.group(0).strip()234235 sqm = re.search(r"Superficie\s+([\d\s]+)pi", text)236 if sqm:237 try:238 v = float(sqm.group(1).replace(" ", ""))239 if 80 <= v <= 20000:240 payload["sqft"] = v241 except ValueError:242 pass243244 # commodités : liste à puces de la fiche (ul.uk-list-disc)245 amenities: list[str] = []246 for ul in soup.select("ul.uk-list-disc"):247 for li in ul.find_all("li"):248 t = li.get_text(" ", strip=True)249 if t and not t.lower().startswith("superficie") \250 and t not in amenities:251 amenities.append(t)252 payload["amenities"] = amenities[:15]253254 if "espace bureau" in text.lower():255 payload["office"] = True256257 imgs = re.findall(258 rf'(?:src|href)="({re.escape(BASE)}/wp-content/uploads/'259 rf'[^"]+\.(?:jpg|jpeg|png|webp))"', dhtml, re.I)260 payload["images"] = [u for u in dict.fromkeys(imgs)261 if not _SKIP_IMG.search(u)][:10]262 return payload263264 # -- assemblage -----------------------------------------------------------265 def _build(self, unit_no: str, url: str, payload: dict,266 row: dict | None = None) -> Listing:267 row = row or {}268 raw_type = payload.get("type") or row.get("type") or ""269 unit_type = normalize_unit_type(raw_type)270271 price_label = row.get("price_label") \272 or payload.get("price_label") or ""273 price = parse_price(price_label)274275 availability = payload.get("availability") \276 or (row.get("status") or "Disponible")277278 area = row.get("sqft") or payload.get("sqft")279 floor = row.get("floor") or payload.get("floor")280281 desc_parts = []282 if floor:283 desc_parts.append(f"Étage {floor}")284 if area:285 desc_parts.append(f"Superficie {area:.0f} pi²")286 if "+" in raw_type or payload.get("office"):287 desc_parts.append("Avec espace bureau")288289 details: dict = {"contact": {"phone": PHONE}}290 if floor and 0 < int(floor) <= 60:291 details["floor"] = int(floor)292293 return Listing(294 source=self.source_id,295 external_id=f"unite-{unit_no}",296 url=url,297 title=f"La Sentinelle — Unité {unit_no}"298 f"{' (' + unit_type + ')' if unit_type else ''}",299 address=ADDRESS,300 sector=SECTOR,301 city=infer_city(SECTOR, default="Lévis"),302 unit_type=unit_type,303 price=price,304 price_label=price_label,305 availability=availability,306 area_sqft=float(area) if area else None,307 description=" | ".join(desc_parts),308 amenities=list(payload.get("amenities") or []),309 details=details,310 images=list(payload.get("images") or []),311 )312