Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/somex_saintnicolas.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0813# Last Modified : 2026-10-2214#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/somex_saintnicolas.py : connecteur Somex Saint-Nicolas91# (somexsaintnicolas.com, Groupe Mahlex / OÏKOS Construction) — 407 unités à92# terme au 710, Route des Rivières, Saint-Nicolas (Lévis). Site WordPress/93# Elementor ; la page « Plans » embarque le module de plans Livya94# (app.livya.com, client « hulix », projet « somex »).95# Depuis la refonte Livya du 2026-10-22, le flux RSC de la page plans ne96# contient plus les unités ET le client hulix n'a PAS de module inventaire97# SSR (unitSelectorSummaries: []) : les unités ne sont chargées QUE côté98# client (api.realvuu.com, robots.txt interdit — on ne l'appelle pas).99# On rend donc la page plans en navigateur (Scrapfly render_js, patron100# quartier_sila) : le DOM rendu contient une vue TABLEAU complète (colonnes101# Nom/Étage/Chambres/Salles de bain/Superficie/Prix/Statut — les loyers102# restent publiés par hulix) qui sert de source de vérité, plus une grille103# de cartes (lazy-loadée, donc partielle) dont on tire les photos de plans.104# external_id = UUID unitId Livya (data-unit-id), identique à l'historique —105# zéro churn (recoupé 145/145 au 2026-10-22). Adresse/GPS : métadonnées de106# l'immeuble « Somex », toujours SSR dans le RSC de la page ; type d'unité107# dérivé des chambres (1 → 3½, 2 → 4½ — recoupé 145/145 avec l'historique).108# La page WordPress /appartements/ fournit une galerie de photos d'unités109# types, repli d'images valable pour toutes les unités.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import html as _html114import re115import json116import time117from urllib.parse import unquote118119from ..schema import Listing, infer_city120from .base import BaseConnector121122BASE = "https://www.somexsaintnicolas.com"123PLANS_URL = f"{BASE}/plans/"124GALLERY_URL = f"{BASE}/appartements/"125LIVYA = "https://app.livya.com"126SECTOR = "Saint-Nicolas"127128# Valeurs observées dans le module de la page /plans/ — replis si129# l'extraction dynamique casse (gabarit WP changé)130DEFAULT_CLIENT = "hulix"131DEFAULT_PROJECT = "somex"132DEFAULT_ENTITY = "5e51343d-a93a-4982-a155-6c14ae1ff73e"133134# conteneur du module plans sur la page WordPress135_CONTAINER_RE = re.compile(r'<div[^>]*livya-module-container-plans[^>]*>', re.I)136_ATTR_RE = re.compile(r'data-(project|entity|lang)="([^"]*)"')137_CLIENT_RE = re.compile(r'data-client="([^"]+)"')138# fragments RSC de Next.js : self.__next_f.push([1,"…"])139_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')140141# vue tableau du DOM rendu (complète) + cartes de la grille (photos de plans)142_ROW_RE = re.compile(r'<tr data-unit-id="([0-9a-f-]{36})"')143_TH_RE = re.compile(r'<th[^>]*>(.*?)</th>', re.S)144_TD_RE = re.compile(r'<td[^>]*>(.*?)</td>', re.S)145_CARD_RE = re.compile(r'<div[^>]*data-unit-id="([0-9a-f-]{36})"')146_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')147_COUNT_RE = re.compile(r'(\d+)\s*résultats?')148149_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,150 "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,151 "novembre": 11, "décembre": 12}152_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)153154# photos d'unités types de la page /appartements/ (galerie du projet)155_WP_IMG_RE = re.compile(156 r"https://www\.somexsaintnicolas\.com/wp-content/uploads/"157 r"[^\"'\s\\?]+?\.(?:jpe?g|webp)")158_WP_IMG_SKIP_RE = re.compile(159 r"logo|favicon|icon|blueprint|mhalex|oikos|pacifica|qnd_|social_preview|"160 r"-\d+x\d+\.", re.I)161162# scrolle tous les conteneurs à overflow interne (grille lazy-loadée : le163# scroll de la fenêtre ne charge rien — auto_scroll Scrapfly inopérant)164_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"165 "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")166167168def _cell_text(cell: str) -> str:169 return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", cell))).strip()170171172def _cell_num(s: str) -> float | None:173 digits = re.sub(r"[^\d.]", "", s or "")174 try:175 return float(digits) if digits else None176 except ValueError:177 return None178179180def _unit_type(beds: float | None) -> str:181 """Type dérivé des chambres (recoupé 145/145 avec l'historique JSON) :182 — -> Studio, 1 -> 3½, 2 -> 4½…"""183 if beds is None or beds < 1:184 return "Studio"185 return f"{int(beds) + 2}½"186187188class SomexSaintNicolasConnector(BaseConnector):189 source_id = "somex_saintnicolas"190 request_delay = 0.8191 max_units = 500 # garde-fou (407 unités à terme)192193 # -- page WordPress : paramètres du module Livya + téléphone -------------------194 def _module(self) -> tuple[str, str, str, str, str]:195 """(client, project, lang, entity, html de /plans/) — replis constants."""196 client, project, lang, entity = (DEFAULT_CLIENT, DEFAULT_PROJECT,197 "fr", DEFAULT_ENTITY)198 wp = ""199 try:200 wp = self.get(PLANS_URL).text201 except Exception:202 return client, project, lang, entity, wp203 mc = _CLIENT_RE.search(wp)204 if mc:205 client = mc.group(1).strip() or client206 for tag in _CONTAINER_RE.findall(wp):207 attrs = dict(_ATTR_RE.findall(tag))208 project = attrs.get("project") or project209 lang = attrs.get("lang") or lang210 entity = attrs.get("entity") or entity211 return client, project, lang, entity, wp212213 def _wp_gallery(self) -> list[str]:214 """Photos d'unités types de la page /appartements/ (pleine taille)."""215 try:216 html = self.get(GALLERY_URL).text217 except Exception:218 return []219 out: list[str] = []220 for u in _WP_IMG_RE.findall(html):221 if not _WP_IMG_SKIP_RE.search(u) and u not in out:222 out.append(u)223 return out[:10]224225 # -- rendu navigateur -----------------------------------------------------------226 def get_rendered(self, url: str, wait_ms: int = 0) -> str:227 """HTML rendu Scrapfly, scroll des conteneurs internes (grille228 lazy-loadée). Surchargée (même nom que base) pour rester compatible229 avec le record/replay des fixtures — clé de rejeu = URL cible."""230 steps: list[dict] = []231 for _ in range(8):232 steps.append({"execute": {"script": _SCROLL_JS}})233 steps.append({"wait": 1200})234 html = self.get_scrapfly(url, render_js=True, asp=True,235 rendering_wait=wait_ms or 4000,236 js_scenario=steps)237 if not html:238 raise RuntimeError(f"Scrapfly : rendu vide — {url}")239 return html240241 def _render_ok(self, url: str) -> str:242 """Rendu dont la vue tableau est complète : le compteur « N résultats »243 doit être présent (sinon gabarit changé) et le nombre de lignes244 uniques du tableau doit l'atteindre — erreur franche après 3245 tentatives plutôt qu'un rendu tronqué qui dépublierait des unités."""246 last_err: Exception | None = None247 for attempt in range(3):248 html = self.get_rendered(url, wait_ms=4000)249 m = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))250 if not m:251 last_err = RuntimeError(252 "app.livya.com (somex) : compteur « N résultats » absent "253 f"du rendu — gabarit Livya changé ? ({url})")254 else:255 announced = int(m.group(1))256 uniques = len(set(_ROW_RE.findall(html)))257 if uniques >= announced:258 return html # announced == 0 : vrai zéro accepté259 last_err = RuntimeError(260 f"app.livya.com (somex) : {uniques} ligne(s) unique(s) "261 f"pour {announced} annoncées — rendu incomplet ? ({url})")262 if attempt < 2:263 time.sleep(5 * (attempt + 1))264 assert last_err is not None265 raise last_err266267 # -- vue tableau du DOM rendu -> unités ------------------------------------------268 @staticmethod269 def _collect(html: str) -> dict[str, dict]:270 """Lignes du tableau (source de vérité) + photos des cartes de grille."""271 thead = re.search(r"<thead.*?</thead>", html, re.S)272 cols: dict[str, int] = {}273 if thead:274 for i, th in enumerate(_TH_RE.findall(thead.group(0))):275 t = _cell_text(th).lower()276 for key, label in (("name", "nom"), ("floor", "étage"),277 ("beds", "chambre"), ("baths", "salle"),278 ("area", "superficie"), ("price", "prix"),279 ("status", "statut")):280 if t.startswith(label):281 cols[key] = i282 if "name" not in cols or "status" not in cols:283 raise RuntimeError(284 "app.livya.com (somex) : en-têtes du tableau introuvables "285 "(Nom/Statut) — gabarit Livya changé ?")286287 units: dict[str, dict] = {}288 rows = list(_ROW_RE.finditer(html))289 for i, m in enumerate(rows):290 end = rows[i + 1].start() if i + 1 < len(rows) else m.start() + 8000291 cells = [_cell_text(c) for c in292 _TD_RE.findall(html[m.start():min(end, m.start() + 8000)])]293294 def col(key: str) -> str:295 j = cols.get(key)296 return cells[j] if j is not None and j < len(cells) else ""297298 parsed = {299 "number": col("name").lstrip("#") or None,300 "floor": _cell_num(col("floor")),301 "beds": _cell_num(col("beds")),302 "baths": _cell_num(col("baths")),303 "area": _cell_num(col("area")),304 "price": _cell_num(col("price")),305 "status": col("status") or None,306 }307 u = units.setdefault(m.group(1), {})308 for k, v in parsed.items():309 if u.get(k) is None and v is not None:310 u[k] = v311312 # cartes de la grille (lazy-loadée, partielle) : photo du plan313 cards = [(x.start(), x.group(1)) for x in _CARD_RE.finditer(html)]314 for i, (pos, uid) in enumerate(cards):315 end = cards[i + 1][0] if i + 1 < len(cards) else pos + 9000316 im = _IMG_RE.search(html[pos:min(end, pos + 9000)])317 if im and uid in units and units[uid].get("image") is None:318 units[uid]["image"] = unquote(im.group(1))319 return units320321 # -- métadonnées de l'immeuble (flux RSC, toujours SSR) ---------------------------322 @staticmethod323 def _building(html: str) -> dict:324 """Premier immeuble du flux RSC : adresse civique, ville, code postal,325 GPS (immeuble unique « Somex » au 710 Route des Rivières)."""326 try:327 blob = "".join(328 json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))329 except Exception:330 return {}331 dec = json.JSONDecoder()332 for m in re.finditer(r'\{"buildingId"', blob):333 try:334 obj, _ = dec.raw_decode(blob[m.start():m.start() + 8000])335 except Exception:336 continue337 if obj.get("address"):338 return obj339 return {}340341 def fetch(self) -> list[Listing]:342 client, project, lang, entity, wp = self._module()343344 # contact du bureau de location (lien tel: de la page WordPress)345 contact: dict = {}346 tel = re.search(r'href="tel:(\d{10})"', wp or "")347 if tel:348 d = tel.group(1)349 contact["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"350351 gallery = self._wp_gallery()352353 url = f"{LIVYA}/{lang}/{client}/projects/{project}/plans/{entity}?noLayout=1"354 html = self._render_ok(url)355 units = self._collect(html)356 cm = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))357 if cm and int(cm.group(1)) and not units:358 raise RuntimeError(359 "app.livya.com (somex) : aucune ligne d'unité dans le rendu "360 "— gabarit changé ?")361 building = self._building(html)362363 listings: list[Listing] = []364 for uid, u in list(units.items())[: self.max_units]:365 if not (u.get("status") or "").startswith("Disponible"):366 continue367 listings.append(self._listing(uid, u, building, gallery, contact))368 return listings369370 # -- une annonce par unité disponible ----------------------------------------------371 def _listing(self, uid: str, u: dict, building: dict,372 gallery: list[str], contact: dict) -> Listing:373 num = str(u.get("number") or "").strip()374375 address = ", ".join(x for x in (376 (building.get("address") or "").strip(),377 (building.get("city") or "").strip(),378 (building.get("postalCode") or "").strip()) if x)379380 price = u.get("price")381 price = float(price) if price and price > 1 else None382383 # « Disponible » ou « Disponible - 1 décembre 2026 » (date française)384 status = (u.get("status") or "").strip()385 availability = "Disponible"386 avail_date = None387 dm = _DATE_FR_RE.search(status)388 if dm and _MOIS.get(dm.group(2).lower()):389 avail_date = (f"{int(dm.group(3)):04d}-"390 f"{_MOIS[dm.group(2).lower()]:02d}-"391 f"{int(dm.group(1)):02d}")392 availability = f"Disponible à partir du {avail_date}"393394 beds, baths, area = u.get("beds"), u.get("baths"), u.get("area")395 unit_type = _unit_type(beds)396397 desc: list[str] = []398 floor = u.get("floor")399 if floor and floor > 0:400 desc.append(f"Étage {int(floor)}")401 if beds:402 desc.append(f"{int(beds)} chambre(s)")403 if baths:404 desc.append(f"{int(baths)} salle(s) de bain")405406 details: dict = {}407 if contact:408 details["contact"] = dict(contact)409 if floor and floor > 0:410 details["floor"] = int(floor)411412 images: list[str] = []413 if u.get("image"):414 images.append(u["image"])415 images.extend(img for img in gallery if img not in images)416417 try:418 lat = (float(building["latitude"])419 if building.get("latitude") else None)420 lng = (float(building["longitude"])421 if building.get("longitude") else None)422 except (TypeError, ValueError):423 lat = lng = None424425 return Listing(426 source=self.source_id,427 external_id=uid, # UUID Livya : stable, historique428 url=PLANS_URL,429 title=f"Somex Saint-Nicolas — unité {num} ({unit_type})",430 address=address,431 sector=SECTOR,432 city=infer_city(SECTOR),433 unit_type=unit_type,434 bedrooms=beds if beds and beds > 0 else None,435 bathrooms=baths if baths and baths > 0 else None,436 price=price,437 price_label=f"{price:.0f} $ /mois" if price else "",438 availability=availability,439 availability_date=avail_date,440 area_sqft=area if area and area > 0 else None,441 description=" | ".join(desc),442 # Inclusions affichées sur la page « Appartements » du site443 # (valables pour toutes les unités) : eau chaude, électros en444 # inox, éclairage, accès internet, air climatisé.445 amenities=["Eau chaude incluse", "Électroménagers en inox",446 "Éclairage inclus", "Accès internet inclus",447 "Air climatisé"],448 details=details,449 images=images[:12],450 lat=lat,451 lng=lng,452 )453