Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_1139.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/gestion_1139.py : connecteur Gestion 1139 (gestion1139.com)91# Drummondville et environs (Centre-du-Québec). WordPress + FacetWP rendu92# serveur : la page d'accueil liste les 40+ immeubles (cartes .fwpl-result :93# titre, adresse, typologies, badge .archive-tag « Disponible … » sur les94# immeubles qui louent). AUCUN prix ni inventaire par unité sur le site —95# seules les cartes portant un badge « Disponible » sont retenues.96# Granularité : une annonce par TYPOLOGIE d'un immeuble disponible97# (ex. projet-horace-3.5, projet-horace-4.5).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109BASE = "https://gestion1139.com"110111DISPO_RE = re.compile(r"disponible", re.I)112# villes plausibles du parc (détection dans le texte de la page immeuble)113CITY_RE = re.compile(114 r"(Drummondville|Saint-Nic[ée]phore|Saint-Charles-de-Drummond|"115 r"Saint-Cyrille[\w-]*|Saint-Germain[\w-]*|Notre-Dame-du-Bon-Conseil|"116 r"Wickham|L'Avenir)", re.I)117IMG_RE = re.compile(r"https://gestion1139\.com/wp-content/uploads/"118 r'[^"\'\s\\)]+\.(?:jpe?g|png|webp)', re.I)119120121class Gestion1139Connector(BaseConnector):122 source_id = "gestion_1139"123 request_delay = 0.7124125 def fetch(self) -> list[Listing]:126 listings: list[Listing] = []127 try:128 html = self.get(BASE + "/").text129 except Exception:130 return listings131 soup = BeautifulSoup(html, "html.parser")132133 seen: set[str] = set()134 for result in soup.select("div.fwpl-result"):135 try:136 tag_el = result.select_one(".archive-tag")137 tag = tag_el.get_text(" ", strip=True) if tag_el else ""138 if not tag or not DISPO_RE.search(tag):139 continue # immeuble sans badge de disponibilité140 a = result.select_one('a[href*="/immeubles/"]')141 if a is None:142 continue143 url = a.get("href", "").split("?")[0]144 slug = url.rstrip("/").split("/")[-1]145 if not slug or slug in seen:146 continue147 seen.add(slug)148149 title_el = result.select_one(".listing_title a")150 name = (title_el.get_text(" ", strip=True)151 if title_el else slug)152 addr_el = result.select_one("p.adresse")153 address = (re.sub(r"\s+", " ",154 addr_el.get_text(" ", strip=True))155 if addr_el else "")156157 card_key = hashlib.sha1(158 f"{tag}|{name}|{address}".encode("utf-8")).hexdigest()159 d = self.detail(slug, card_key,160 lambda url=url: self._fetch_detail(url))161 if d.get("address"):162 address = d["address"]163 city = d.get("city") or "Drummondville"164165 units = d.get("units") or [{"unit_type": "", "extra": []}]166 for u in units:167 ut = u.get("unit_type", "")168 suffix = ut.replace("½", ".5").replace(" ", "") or "imm"169 listings.append(Listing(170 source=self.source_id,171 external_id=f"{slug}-{suffix}",172 url=url,173 title=f"{ut + ' — ' if ut else ''}{name}",174 address=address,175 city=city,176 unit_type=ut,177 availability=tag,178 description=d.get("description", ""),179 amenities=(u.get("extra") or [])180 + (d.get("amenities") or []),181 images=d.get("images") or [],182 ))183 except Exception:184 continue185 return listings186187 def _fetch_detail(self, url: str) -> dict:188 """Page immeuble : description, adresse civique, avantages,189 typologies (« Nos unités » : n ½ / chambres / salles de bain),190 ville (détectée dans le texte) et photos."""191 out: dict = {}192 try:193 html = self.get(url).text194 except Exception:195 return out196 soup = BeautifulSoup(html, "html.parser")197198 # typologies199 units: list[dict] = []200 for bloc in soup.select("div.liste_appartement"):201 ps = [p.get_text(" ", strip=True) for p in bloc.find_all("p")202 if p.get_text(strip=True)]203 if not ps:204 continue205 units.append({"unit_type": normalize_unit_type(ps[0]),206 "extra": ps[1:3]})207 out["units"] = units208209 # description : premiers paragraphes de la section d'intro210 paras = [p.get_text(" ", strip=True)211 for p in soup.select(".uncode_text_column p")212 if len(p.get_text(strip=True)) > 40]213 if paras:214 out["description"] = re.sub(r"\s+", " ", paras[0]).strip()[:900]215216 # adresse civique (ligne « 1645 et 1655 Boulevard Lemire »)217 text = soup.get_text("\n", strip=True)218 m = re.search(r"^\d{1,5}[^\n]{3,70}(?:rue|boulevard|boul\.|avenue|"219 r"chemin|route)[^\n]{0,50}$", text, re.I | re.M)220 if m:221 out["address"] = re.sub(r"\s+", " ", m.group(0)).strip()222 m = CITY_RE.search(text)223 if m:224 out["city"] = m.group(1)225 else: # souvent seulement dans les noms de fichiers photo226 m = CITY_RE.search(html)227 if m:228 out["city"] = m.group(1).capitalize()229230 # avantages (liste « Les avantages »)231 out["amenities"] = [232 li.get_text(" ", strip=True)233 for li in soup.select(".uncode_text_column li")234 if 0 < len(li.get_text(strip=True)) <= 80][:15]235236 out["images"] = [u for u in dict.fromkeys(IMG_RE.findall(html))237 if not re.search(r"logo|icon|favicon|-\d{2,3}x\d{2,3}\.",238 u, re.I)][:20]239 return out240