Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/girs.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/girs.py : connecteur GIRS — Gestion Immobilière de la Rive Sud91# (girs.ca). Gestionnaire de Sainte-Marie (Beauce) : immeubles locatifs92# neufs à Scott, Saint-Isidore et La Guadeloupe (Chaudière-Appalaches) +93# Carleton-sur-Mer et New Richmond (Gaspésie).94# Site Duda (assets irp.cdn-website.com), rendu CÔTÉ SERVEUR :95# - le menu « À louer » du hub /location regroupe les immeubles par ville96# (« Scott, Chaudières-Appalaches » -> /location/scott/rue-amanda-gustave) ;97# - chaque page d'immeuble est une VITRINE : nom/rue (h1), description,98# pictogrammes de commodités (BALCON PRIVÉ, CLIMATISATION, « CHAT ET99# CHIEN ACCEPTÉ (sous conditions) »…), photos — mais AUCUNE liste100# d'unités, AUCUN prix, AUCUNE disponibilité (location par téléphone /101# formulaire) -> 1 annonce « catalogue » par immeuble, prix None et102# availability vide (rien d'inventé) ;103# - le type d'unités n'est cité qu'en prose (« appartements de type 4 ½ »,104# « 4 ½ et 5 ½ ») : unit_type n'est rempli que si UN seul type est105# mentionné, sinon la description fait foi.106# external_id stable : slug du chemin (/location/scott/rue-amanda-gustave ->107# scott-rue-amanda-gustave). La section « À vendre » du menu est ignorée.108# robots.txt : permissif (sitemap public).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import re113114from bs4 import BeautifulSoup115116from ..schema import Listing117from .base import BaseConnector118119BASE = "https://www.girs.ca"120HUB_URL = f"{BASE}/location"121122# « Scott, Chaudières-Appalaches » -> ville « Scott » (le site épelle la123# région « Chaudières-Appalaches », coquille conservée telle quelle côté brut)124_CITY_RE = re.compile(r"^\s*([^,]+?)\s*(?:,|$)")125_TYPE_RE = re.compile(r"\b([1-6])\s*½")126_IMG_RE = re.compile(127 r'https://irp\.cdn-website\.com/[^"\'\s\)]+'128 r'\.(?:jpg|jpeg|png|webp)', re.I)129_SKIP_IMG = re.compile(r"logo|favicon|icon|pexels|silhouette", re.I)130131132def _slug(path: str) -> str:133 """« /location/scott/rue-amanda-gustave » -> « scott-rue-amanda-gustave »."""134 return re.sub(r"[^a-z0-9]+", "-",135 path.strip("/").removeprefix("location/").lower()).strip("-")136137138def _mostly_upper(t: str) -> bool:139 letters = [c for c in t if c.isalpha()]140 if len(letters) < 5:141 return False142 return sum(c.isupper() for c in letters) / len(letters) >= 0.7143144145class GirsConnector(BaseConnector):146 source_id = "girs"147 request_delay = 0.6148 max_images = 12149150 # -- hub /location : immeubles « À louer » groupés par ville -----------------151 def _buildings(self) -> list[tuple[str, str, str]]:152 """[(path, nom d'immeuble, ville)] depuis le menu « À louer »."""153 soup = BeautifulSoup(self.get(HUB_URL).text, "html.parser")154 out: list[tuple[str, str, str]] = []155 seen: set[str] = set()156 nav = soup.select_one("ul.unav-top")157 if nav is None:158 return out159 for top_li in nav.find_all("li", recursive=False):160 top_link = top_li.find("a")161 top_txt = top_link.get_text(" ", strip=True) if top_link else ""162 if not top_txt.lower().startswith("à louer"):163 continue # « À vendre », « Nos services »… ignorés164 for city_li in top_li.select("ul li"):165 city_link = city_li.find("a")166 if not city_link:167 continue168 m = _CITY_RE.match(city_link.get_text(" ", strip=True))169 city = m.group(1).strip() if m else ""170 for a in city_li.select("ul a[href^='/location/']"):171 path = a.get("href", "").strip().rstrip("/")172 name = re.sub(r"\s+", " ", a.get_text(" ", strip=True))173 # seules les pages d'immeuble (/location/<ville>/<immeuble>)174 # sont des annonces ; les pages de ville sont ignorées175 if len(path.strip("/").split("/")) < 3:176 continue177 if path and name and path not in seen:178 seen.add(path)179 out.append((path, name, city))180 return out181182 # -- page d'immeuble ---------------------------------------------------------183 def _parse_building(self, path: str, name: str, city: str) -> Listing | None:184 url = f"{BASE}{path}"185 soup = BeautifulSoup(self.get(url).text, "html.parser")186 main = soup.select_one("#dm_content") or soup.body187 if main is None:188 return None189190 h1 = main.select_one("h1")191 street = h1.get_text(" ", strip=True) if h1 else name192193 # description et commodités : blocs de paragraphes Duda. Les légendes194 # des pictogrammes sont parfois éclatées sur plusieurs <p> du même195 # bloc (« ENVIRONNEMENT CALME » / « ET PAISIBLE ») -> on travaille au196 # niveau du bloc `div.dmNewParagraph` pour les recoller.197 paras: list[str] = []198 amenities: list[str] = []199 for div in main.select("div.dmNewParagraph"):200 if div.find(re.compile(r"^h[1-6]$")):201 continue # titres de section (ESPACE DE VIE, COMMODITÉS…)202 t = re.sub(r"\s+", " ",203 div.get_text(" ", strip=True).replace("", "")204 ).strip()205 if not t or len(t) < 4:206 continue207 # le test « majuscules » ignore les précisions entre parenthèses208 # (« CHAT ET CHIEN ACCEPTÉ (sous conditions) »)209 if _mostly_upper(re.sub(r"\([^)]*\)", "", t)):210 # pictogramme de commodité (« BALCON PRIVÉ », « INTERNET211 # ILLIMITÉ », « CHAT ET CHIEN ACCEPTÉ (sous conditions) »…)212 if 5 <= len(t) <= 70 and t not in amenities:213 amenities.append(t)214 elif len(t) >= 60 and len(paras) < 6:215 paras.append(t)216 description = "\n".join(paras)[:1400]217218 # type d'unités : seulement si UN seul type est cité en prose219 types = sorted(set(_TYPE_RE.findall(220 f"{description} {' '.join(amenities)}".replace("1/2", "½")221 .replace(" ½", "½"))))222 unit_type = f"{types[0]}½" if len(types) == 1 else ""223224 # animaux : le site publie « CHAT ET CHIEN ACCEPTÉ (sous conditions) »225 pets = None226 for t in amenities:227 if re.search(r"(?i)chat|chien|animau", t):228 pets = ("conditions" if re.search(r"(?i)condition", t)229 else "oui")230231 # photos de l'immeuble (CDN Duda), hors logos et images génériques232 images: list[str] = []233 for u in dict.fromkeys(_IMG_RE.findall(str(main))):234 if not _SKIP_IMG.search(u) and u not in images:235 images.append(u)236237 return Listing(238 source=self.source_id,239 external_id=_slug(path),240 url=url,241 title=f"{name} — {city}" if city else name,242 address=street if street.lower() != name.lower() or243 re.search(r"(?i)rue|avenue|boulevard|chemin|rang|\d", street)244 else "",245 sector="",246 city=city,247 unit_type=unit_type,248 price=None, # aucun loyer publié sur le site249 price_label="",250 availability="", # disponibilités par téléphone : rien d'inventé251 description=description,252 pets=pets,253 amenities=amenities[:30],254 images=images[: self.max_images],255 )256257 # -- fetch -----------------------------------------------------------------258 def fetch(self) -> list[Listing]:259 listings: dict[str, Listing] = {}260 for path, name, city in self._buildings():261 try:262 lst = self._parse_building(path, name, city)263 except Exception:264 continue265 if lst is not None and lst.external_id not in listings:266 listings[lst.external_id] = lst267 return list(listings.values())268