Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/wandji.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/wandji.py : connecteur Gestion Immobilière Wandji91# (wandji-immobilier.com — Gatineau : Hull, Aylmer, Plateau, Buckingham,92# Masson-Angers + Papineauville). Le site est une SPA Angular 2 (2016) vide93# sans JavaScript, mais son backend expose une API JSON publique :94# GET /api/buildings -> liste des logements NON LOUÉS (rented=false) avec95# prix, adresse, secteur, ville, lat/lng, chambres, salles de bain,96# disponibilité (ISO), descriptions FR/EN, inclusions/exclusions,97# proximité et galerie (/api/buildings/<id>/picture/<fichier>).98# Une annonce = un document Mongo (_id stable = external_id). Les locaux99# commerciaux (type COMMERCIAL / subType LOCAL) et les adresses hors Québec100# (secteur Ottawa) sont exclus. Le suffixe « /mois » n'est affiché par le101# site que si monthly=true : le price_label reproduit ce comportement.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110BASE = "https://wandji-immobilier.com"111API_URL = f"{BASE}/api/buildings"112113MAX_IMAGES = 20114115# « Buckingham-gatineau », « Plateau-hull », « Masson-angers - gatineau »,116# « Gatineau gatineau » -> secteur sans le suffixe ville accolé par le site117_SECTOR_SUFFIX = re.compile(r"[\s-]+(gatineau|hull|aylmer|montreal|ottawa)\s*$", re.I)118119# libellés français des booléens structurés de l'API (affichés par la SPA)120_FLAGS = [121 ("airConditioning", "Climatisation"),122 ("garage", "Garage"),123 ("outdoorParking", "Stationnement extérieur"),124 ("interiorStorage", "Rangement intérieur"),125 ("exteriorStorage", "Rangement extérieur"),126 ("basement", "Sous-sol"),127]128129_TYPE_FR = {"APARTMENT": "Appartement", "CONDO": "Condo",130 "HOUSE": "Maison", "COMMERCIAL": "Commercial"}131132133def _fmt_price(value: float) -> str:134 """1725 -> « 1 725 $ » (format d'affichage québécois usuel)."""135 s = f"{value:,.0f}".replace(",", " ")136 return f"{s} $"137138139class WandjiConnector(BaseConnector):140 source_id = "wandji"141 request_delay = 0.6142143 def fetch(self) -> list[Listing]:144 buildings = self.get(API_URL).json()145 listings: dict[str, Listing] = {}146 for b in buildings:147 try:148 lst = self._parse(b)149 except Exception:150 continue151 if lst and lst.external_id not in listings:152 listings[lst.external_id] = lst153 return list(listings.values())154155 def _parse(self, b: dict) -> Listing | None:156 ext_id = str(b.get("_id") or "").strip()157 if not ext_id:158 return None159 # locaux commerciaux exclus (non résidentiel)160 if (b.get("type") or "").upper() == "COMMERCIAL" or \161 (b.get("subType") or "").upper() == "LOCAL":162 return None163 if b.get("rented"):164 return None # déjà loué (défensif)165166 city = (b.get("city") or "").strip()167 province = (b.get("province") or "").strip()168 if province and "qu" not in province.lower():169 return None # hors Québec (parc Ottawa exclu)170 # « Hull (Gatineau) » -> ville Gatineau ; Hull passe en secteur171 sector_from_city = ""172 m = re.match(r"^(.*?)\s*\((.+)\)$", city)173 if m:174 sector_from_city, city = m.group(1).strip(), m.group(2).strip()175 if re.search(r"ottawa", city, re.I):176 return None177178 sector_raw = (b.get("sector") or "").strip()179 sector = _SECTOR_SUFFIX.sub("", sector_raw).strip(" -")180 if sector.lower() == city.lower():181 sector = "" # « Gatineau-gatineau » etc.182 if not sector:183 sector = sector_from_city184 sector = sector[:1].upper() + sector[1:] if sector else ""185186 address = (b.get("address") or "").strip()187 price = b.get("price") if isinstance(b.get("price"), (int, float)) else None188 price_label = ""189 if price:190 price_label = _fmt_price(price) + (" / mois" if b.get("monthly") else "")191192 # type d'unité : Maison explicite, sinon n chambres -> (n+2)½ ;193 # jamais deviné quand l'API ne donne rien194 btype = (b.get("type") or "").upper()195 rooms = b.get("rooms")196 if btype == "HOUSE":197 unit_type = "Maison"198 elif isinstance(rooms, int) and rooms > 0:199 unit_type = normalize_unit_type(f"{rooms} chambres")200 else:201 unit_type = ""202203 # disponibilité ISO de l'API (« 2026-07-01T04:00:00.000Z »)204 avail_iso = (b.get("availability") or "")[:10]205206 # description française d'abord, complétée des inclusions/proximité207 # rédigées par l'agence (exploitées par textmine)208 parts = []209 desc = (b.get("descriptionFR") or b.get("description") or "").strip()210 if desc:211 parts.append(desc)212 if (b.get("inclusionFR") or "").strip():213 parts.append(f"Inclus : {b['inclusionFR'].strip()}")214 if (b.get("exclusionFR") or "").strip():215 parts.append(f"Non inclus : {b['exclusionFR'].strip()}")216 if (b.get("proximityFR") or "").strip():217 parts.append(f"À proximité : {b['proximityFR'].strip()}")218 description = "\n".join(parts)[:2500]219220 amenities = [label for key, label in _FLAGS if b.get(key)]221222 details: dict = {}223 if isinstance(rooms, int) and rooms > 0:224 details["bedrooms"] = rooms225 baths = b.get("bathrooms")226 if isinstance(baths, (int, float)) and baths > 0:227 details["bathrooms"] = baths228 if b.get("subType"):229 details["subtype"] = b["subType"]230 if b.get("levels"):231 details["levels"] = b["levels"]232 if b.get("postalCode"):233 details["postal_code"] = str(b["postalCode"]).strip()234235 # superficie : l'API contient surtout des valeurs sentinelles (0/1) —236 # ne garder que les valeurs plausibles237 area = b.get("area")238 area_sqft = float(area) if isinstance(area, (int, float)) and area >= 80 else None239240 images = [f"{BASE}/api/buildings/{ext_id}/picture/{img}"241 for img in (b.get("images") or [])[:MAX_IMAGES] if img]242243 lat = lng = None244 try:245 lat, lng = float(b.get("latitude")), float(b.get("longitude"))246 except (TypeError, ValueError):247 pass248249 return Listing(250 source=self.source_id,251 external_id=ext_id,252 url=f"{BASE}/proprietes#{ext_id}",253 title=address,254 address=address,255 sector=sector,256 city=city,257 unit_type=unit_type,258 price=float(price) if price else None,259 price_label=price_label,260 availability=avail_iso,261 availability_date=avail_iso or None,262 area_sqft=area_sqft,263 description=description,264 amenities=amenities,265 details=details,266 images=images,267 lat=lat,268 lng=lng,269 )270