Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logicom.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/logicom.py : connecteur Les Immeubles Logicom91# (immeubleslogicom.com — Sainte-Foy, Sillery, Lévis…). WordPress rendu92# serveur : /appartements-a-louer/ liste les immeubles (/immeuble/<slug>/),93# et chaque page immeuble expose ses unités disponibles en cartes94# `.appartement` (no d'unité dans le titre, disponibilité, type n ½,95# superficie, balcon, prix « À partir de … $ », plan PDF/PNG) + un marqueur96# carte data-lat/data-lng. Granularité : unité.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, infer_city, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "https://immeubleslogicom.com"109LIST_URL = f"{BASE}/appartements-a-louer/"110111UNIT_NO_RE = re.compile(r"(\d{1,4}[A-Z]?)\s*$")112TYPE_OK_RE = re.compile(r"studio|loft|\d\s*(?:½|1/2)", re.I)113SQFT_RE = re.compile(r"([\d\s]+)\s*pi²", re.I)114115116class LogicomConnector(BaseConnector):117 source_id = "logicom"118 request_delay = 0.6119 max_buildings = 15 # garde-fou de crawl120121 def fetch(self) -> list[Listing]:122 listings: list[Listing] = []123 try:124 html = self.get(LIST_URL).text125 except Exception:126 return listings127128 slugs = list(dict.fromkeys(129 re.findall(r"/immeuble/([a-z0-9-]+)/", html)))[:self.max_buildings]130 seen: set[str] = set()131 for slug in slugs:132 url = f"{BASE}/immeuble/{slug}/"133 try:134 page = self.get(url).text135 except Exception:136 continue137 for lst in self._parse_building(slug, url, page):138 # certaines unités apparaissent en double sur la page139 if lst.external_id in seen:140 continue141 seen.add(lst.external_id)142 listings.append(lst)143 return listings144145 def _parse_building(self, slug: str, url: str, page: str) -> list[Listing]:146 out: list[Listing] = []147 soup = BeautifulSoup(page, "html.parser")148149 h1 = soup.select_one("h1")150 building = h1.get_text(" ", strip=True) if h1 else slug151152 # secteur : bloc « Localisation » du survol (hero-info)153 sector = ""154 for blk in soup.select(".hero-info span"):155 if "localisation" in blk.get_text(strip=True).lower():156 p = blk.find_next("p")157 if p:158 sector = p.get_text(" ", strip=True)159 break160 city = infer_city(sector)161162 lat = lng = None163 marker = soup.select_one(".marker[data-lat]")164 if marker:165 try:166 lat = float(marker["data-lat"])167 lng = float(marker["data-lng"])168 except (KeyError, ValueError):169 lat = lng = None170171 # photos de l'immeuble (carrousel du projet)172 photos = [img.get("src", "") for img in173 soup.select(".slider-container img")174 if img.get("src", "").startswith("http")][:15]175176 for card in soup.select("div.appartement"):177 try:178 title_el = card.select_one("[data-title]")179 if not title_el:180 continue181 title = title_el.get_text(" ", strip=True)182 m = UNIT_NO_RE.search(title)183 unit_no = m.group(1) if m else ""184185 type_el = card.select_one(".type p")186 raw_type = type_el.get_text(" ", strip=True) if type_el else \187 card.get("data-type", "")188 # résidentiel seulement (Studio / Loft / n ½)189 if not TYPE_OK_RE.search(raw_type):190 continue191192 avail_el = title_el.find_next("p")193 availability = avail_el.get_text(" ", strip=True) \194 if avail_el else ""195196 sizes = [p.get_text(" ", strip=True)197 for p in card.select(".taille p")]198 area = None199 for s in sizes:200 sm = SQFT_RE.search(s)201 if sm and "$" not in s:202 area = float(sm.group(1).replace(" ", "")203 .replace(" ", ""))204 break205 price_label = next((re.sub(r"\s+", " ", s) for s in sizes206 if "$" in s), "")207208 plan = card.select_one('a[href$=".pdf"]')209 plan_img = card.select_one("img")210 images = list(photos)211 if plan_img and plan_img.get("src", "").startswith("http"):212 images = [plan_img["src"]] + photos213214 if not unit_no:215 unit_no = hashlib.sha1(216 f"{title}|{raw_type}|{area}".encode()).hexdigest()[:8]217 extras = [f"Balcon : {sizes[1]}"] \218 if len(sizes) >= 3 and "pi²" in sizes[1] else []219 details: dict = {}220 if plan:221 details["floor_plan"] = plan.get("href", "")222223 out.append(Listing(224 source=self.source_id,225 external_id=f"{slug}-{unit_no}",226 url=url,227 title=title,228 sector=sector,229 city=city,230 unit_type=normalize_unit_type(raw_type),231 price=parse_price(price_label),232 price_label=price_label,233 availability=availability,234 area_sqft=area,235 description=f"Unité {unit_no} — {building} "236 f"({sector}).",237 amenities=extras,238 details=details,239 images=images,240 lat=lat,241 lng=lng,242 ))243 except Exception:244 continue245 return out246