Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/siagi.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/siagi.py : connecteur SIA Gestion Immobilière (siagi.ca)91# ~240 logements en gestion — Estrie (Sherbrooke) + Grand Montréal (Laval,92# La Prairie). Site Next.js (App Router) : la page /listings est rendue93# serveur et son flux RSC (self.__next_f.push) embarque le tableau JSON94# "listings" — id (cuid stable), title « Ville · App. N », subtitle (adresse95# civique), rentLabel (« 1 200,00 $ / mois ») et mapEmbedUrl Google Maps96# (adresse complète avec code postal). Une seule requête par sync ; aucun97# rendu JavaScript nécessaire (patron louis14/somex). Les annonces n'ont pas98# de page propre ni de photo/type/disponibilité publiés — champs laissés99# vides, rien d'inventé.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import codecs104import json105import re106from urllib.parse import parse_qs, unquote, urlparse107108from ..schema import Listing, parse_price109from .base import BaseConnector110111BASE = "https://www.siagi.ca"112LIST_URL = f"{BASE}/listings"113114# fragments RSC de Next.js : self.__next_f.push([1,"...payload échappé..."])115_NEXT_F_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')116_POSTAL_RE = re.compile(r"\b([A-Z]\d[A-Z]\s?\d[A-Z]\d)\b")117118119def _flight_blob(html: str) -> str:120 """Concatène et désérialise les fragments RSC (voir somex_saintnicolas)."""121 blob = "".join(codecs.decode(c, "unicode_escape")122 for c in _NEXT_F_RE.findall(html))123 return blob.encode("latin-1", "ignore").decode("utf-8", "ignore")124125126def _clean_price_label(label: str) -> str:127 """« 1 200,00 $ / mois » -> compatible parse_price (virgule décimale)."""128 s = re.sub(r"(\d)\s(\d{3})", r"\1\2", label) # espaces de milliers129 return re.sub(r",(\d{2})\b", r".\1", s) # virgule décimale130131132class SiagiConnector(BaseConnector):133 source_id = "siagi"134 request_delay = 0.6135136 def fetch(self) -> list[Listing]:137 html = self.get(LIST_URL).text138 blob = _flight_blob(html)139140 i = blob.find('"listings":[')141 if i < 0:142 raise RuntimeError("tableau listings introuvable dans le flux RSC")143 arr, _ = json.JSONDecoder().raw_decode(blob[i + len('"listings":'):])144145 listings: list[Listing] = []146 seen: set[str] = set()147 for it in arr:148 if not isinstance(it, dict) or not it.get("id"):149 continue150 ext_id = str(it["id"])151 if ext_id in seen:152 continue153 seen.add(ext_id)154155 title = (it.get("title") or "").strip()156 street = (it.get("subtitle") or "").strip()157 rent_label = (it.get("rentLabel") or "").strip()158159 # « Sherbrooke · App. 12 » -> ville + numéro d'unité160 city = ""161 m = re.match(r"^(.*?)\s*·", title)162 if m:163 city = m.group(1).strip().title()164165 # adresse complète (avec code postal) dans l'URL Google Maps166 postal = ""167 try:168 q = parse_qs(urlparse(it.get("mapEmbedUrl") or "").query)169 full = unquote(q.get("q", [""])[0])170 pm = _POSTAL_RE.search(full.upper())171 if pm:172 postal = pm.group(1)173 except Exception:174 pass175 address = ", ".join(x for x in (street, postal) if x)176177 listings.append(Listing(178 source=self.source_id,179 external_id=ext_id,180 url=LIST_URL, # les annonces n'ont pas de page propre181 title=title,182 address=address,183 sector="", # non publié par la source184 city=city,185 unit_type="", # non publié par la source186 price=parse_price(_clean_price_label(rent_label)),187 price_label=rent_label,188 availability="", # non publié (les annonces affichées189 # sont les logements disponibles)190 ))191 return listings192