Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/location_di.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/location_di.py : connecteur Location DI / Groupe Sphère DI91# (locationdi.com) — +750 logements : Trois-Rivières, Bécancour, MRC de92# Joliette (Saint-Charles-Borromée, Saint-Félix-de-Valois…), Berthierville,93# Lachute, Montréal.94# Site SSR (Astro) très propre : la page /logements affiche toutes les95# unités disponibles sous forme de cartes avec ATTRIBUTS DE DONNÉES96# structurés (data-slug, data-ville, data-region, data-type, data-etage,97# data-prix, data-date). Chaque fiche embarque un JSON-LD schema.org98# « Apartment » (adresse, superficie, chambres, photos, description).99# Les pages régionales /logements/region/<r> sont aussi balayées (filet).100# robots.txt : pas de bloc User-agent générique ni de crawl-delay ; les101# bots IA « live fetch » sont explicitement autorisés, seuls les bots102# d'ENTRAÎNEMENT sont bloqués — notre usage (indexation d'annonces avec103# lien vers la source, UA transparent LouKaBot) est conforme.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import json109import re110111from bs4 import BeautifulSoup112113from ..schema import Listing, parse_availability_date114from .base import BaseConnector115116BASE = "https://locationdi.com"117118# JSON-LD des fiches : <script type="application/ld+json">{...}</script>119_LD_RE = re.compile(120 r'<script type="application/ld\+json">(.*?)</script>', re.S)121122123class _CapAtteint(Exception):124 """Plafond de requêtes détail atteint pour cette synchronisation."""125126127class LocationDIConnector(BaseConnector):128 source_id = "location_di"129 request_delay = 0.7 # politesse (petit site régional)130 max_region_pages = 12 # garde-fou : pages régionales balayées131 max_real_details = 60 # vraies requêtes fiches par sync (cache exclu)132133 # -- liste ------------------------------------------------------------------134 def _cards(self, html: str, found: dict[str, dict]) -> list[str]:135 """Cartes .logement-card (attributs data-*) ; retourne les pages136 régionales découvertes (/logements/region/…)."""137 soup = BeautifulSoup(html, "html.parser")138 for card in soup.select("div.logement-card[data-slug]"):139 slug = card.get("data-slug", "").strip()140 if not slug or slug in found:141 continue142 text = card.get_text(" ", strip=True)143 # badge de disponibilité affiché sur la carte (texte source)144 avail = ""145 m = re.search(r"(Disponible dès maintenant|Libre le [^·|]+)", text)146 if m:147 avail = m.group(1).strip()148 found[slug] = {149 "ville": card.get("data-ville", "").strip(),150 "region": card.get("data-region", "").strip(),151 "type": card.get("data-type", "").strip(),152 "etage": card.get("data-etage", "").strip(),153 "prix": card.get("data-prix", "").strip(),154 "date": card.get("data-date", "").strip(),155 "avail": avail,156 "from": "À partir de" in text,157 }158 regions = []159 for a in soup.select('a[href^="/logements/region/"]'):160 href = (a.get("href") or "").split("?")[0].split("#")[0]161 if href:162 regions.append(BASE + href)163 return regions164165 # -- fiche (JSON-LD + commodités) --------------------------------------------166 def _unit_detail(self, slug: str, key: str) -> dict:167 def _fetch() -> dict:168 if self._real_details >= self.max_real_details:169 raise _CapAtteint()170 self._real_details += 1171 resp = self.get(f"{BASE}/logements/{slug}")172 resp.encoding = "utf-8" # pages servies sans charset explicite173 html = resp.text174 out: dict = {}175 for m in _LD_RE.finditer(html):176 try:177 ld = json.loads(m.group(1))178 except ValueError:179 continue180 if ld.get("@type") != "Apartment":181 continue182 out["description"] = str(ld.get("description") or "")183 adr = ld.get("address") or {}184 out["street"] = str(adr.get("streetAddress") or "")185 out["locality"] = str(adr.get("addressLocality") or "")186 fs = ld.get("floorSize") or {}187 try:188 v = float(fs.get("value"))189 if 80 <= v <= 20000:190 out["area"] = v191 except (TypeError, ValueError):192 pass193 beds = ld.get("numberOfRooms")194 if isinstance(beds, int):195 out["bedrooms"] = beds196 out["images"] = [u for u in (ld.get("image") or [])197 if isinstance(u, str) and u.startswith("http")]198 break199 # commodités : noms des items sous « Commodités et inclusions »200 soup = BeautifulSoup(html, "html.parser")201 amenities: list[str] = []202 for h2 in soup.find_all("h2"):203 if "Commodités" not in h2.get_text():204 continue205 cont = h2.find_next_sibling("div") or h2.parent206 for p in cont.find_all("p"):207 cls = " ".join(p.get("class") or [])208 if "font-semibold" not in cls:209 continue210 t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))211 if 3 <= len(t) <= 60 and t not in amenities:212 amenities.append(t)213 break214 out["amenities"] = amenities[:20]215 return out216217 try:218 return self.detail(slug, key, _fetch)219 except Exception:220 return {}221222 # -- fetch --------------------------------------------------------------------223 def fetch(self) -> list[Listing]:224 self._real_details = 0225 found: dict[str, dict] = {}226227 resp = self.get(f"{BASE}/logements")228 resp.encoding = "utf-8" # pages servies sans charset explicite229 regions = self._cards(resp.text, found)230 # filet : pages régionales (au cas où une unité manque à la liste globale)231 for url in list(dict.fromkeys(regions))[: self.max_region_pages]:232 try:233 r = self.get(url)234 r.encoding = "utf-8"235 self._cards(r.text, found)236 except Exception:237 continue238239 listings: list[Listing] = []240 for slug, c in found.items():241 m = re.search(r"(\d+)$", slug)242 ext_id = m.group(1) if m else slug # id numérique stable du slug243 key = hashlib.sha1(json.dumps(c, sort_keys=True, ensure_ascii=False)244 .encode("utf-8")).hexdigest()[:16]245 det = self._unit_detail(slug, key)246247 try:248 price = float(c["prix"]) if c["prix"] else None249 except ValueError:250 price = None251 availability = c["avail"] or (f"Libre le {c['date']}" if c["date"]252 else "")253 # data-date ISO de la carte (une date passée = libre maintenant)254 avail_date = parse_availability_date(c["date"]) if c["date"] else None255256 address = det.get("street") or ""257 title_addr = ""258 if address:259 title_addr = address + (f", {det['locality']}"260 if det.get("locality") else "")261 details: dict = {}262 if c["etage"]:263 details["floor_label"] = c["etage"] # ex. « 3e Étage »264 if isinstance(det.get("bedrooms"), int):265 details["bedrooms"] = det["bedrooms"]266 if c["from"]:267 details["price_from"] = True268269 listings.append(Listing(270 source=self.source_id,271 external_id=ext_id,272 url=f"{BASE}/logements/{slug}",273 title=(f"{c['type']} — {title_addr}" if title_addr274 else f"{c['type']} — {slug}"),275 address=address,276 sector=c["region"], # ex. « Mauricie »277 city=det.get("locality") or c["ville"], # vraie ville278 unit_type=c["type"],279 price=price,280 price_label=(f"À partir de {c['prix']}$ / mois"281 if c["from"] and c["prix"] else ""),282 availability=availability,283 availability_date=avail_date,284 area_sqft=det.get("area"),285 description=str(det.get("description") or "")[:600],286 amenities=det.get("amenities") or [],287 details=details,288 images=(det.get("images") or [])[:20],289 ))290 return listings291