Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/kijiji.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1814#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/kijiji.py : Kijiji (kijiji.ca) — petites annonces de LOCATION91# UNIQUEMENT les catégories logement À LOUER, UNIQUEMENT le Québec (l9001) :92# c37 appartements & condos à louer · c36 chambres à louer & colocation93# Les pages listent 40+ annonces dans __NEXT_DATA__ (Apollo state) avec titre,94# prix, GPS, adresse, date de disponibilité et attributs (meublé, animaux,95# inclusions…) — aucune API privée nécessaire. Adapté du connecteur « à96# vendre » d'Immo-Ka (agent-courtage/immoka).97# Prix « Sur demande » (price.type=CONTACT, ~3 % des annonces) : le montant98# est souvent écrit dans la description (« Loyer : 1 550 $ / mois ») — on99# le récupère prudemment (montant collé à $ + mois/month plausible), sinon100# le libellé affiché devient « Sur demande » plutôt que vide.101# (Vérifié à la source : les annonces sans photo ou à photo unique le sont102# réellement sur Kijiji — imageUrls vide/à 1 sur la fiche aussi.)103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import os108import re109110from ..schema import Listing111from .base import BaseConnector112113from . import _detailutil as du114115BASE = "https://www.kijiji.ca"116# (code catégorie, segment d'URL, type d'unité par défaut)117CATEGORIES = [118 (37, "b-appartement-condo", ""), # unité déduite des attributs119 (36, "b-chambre-a-louer-colocataire", "Chambre"),120]121MAX_PAGES = int(os.environ.get("LOUKA_KIJIJI_MAX_PAGES", "100"))122DETAIL_LIMIT = int(os.environ.get("LOUKA_KIJIJI_DETAIL_LIMIT", "400"))123124# les annonces vivent sous des clés Apollo « RealEstateListing:123 » (c37)125# ou « StandardListing:123 » (c36)126_LISTING_KEY_RE = re.compile(r"^(?:RealEstate|Standard)Listing:\d+$")127_NEXT_RE = re.compile(128 r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>', re.S)129130# attributs binaires -> commodité affichable (uniquement si la valeur est vraie)131_AMENITY_LABELS = {132 "heat": "Chauffage inclus", "hydro": "Électricité incluse",133 "water": "Eau incluse", "internet": "Internet inclus",134 "cabletv": "Câble/télé inclus", "laundryinunit": "Laveuse/sécheuse dans l'unité",135 "laundryinbuilding": "Buanderie dans l'immeuble", "dishwasher": "Lave-vaisselle",136 "fridgefreezer": "Réfrigérateur/congélateur", "airconditioning": "Air climatisé",137 "balcony": "Balcon", "elevator": "Ascenseur", "gym": "Salle d'entraînement",138 "pool": "Piscine", "concierge": "Concierge",139 "twentyfourhoursecurity": "Sécurité 24 h", "storagelocker": "Espace de rangement",140 "bicycleparking": "Stationnement pour vélo", "yard": "Cour",141 "wheelchairaccessible": "Accessible en fauteuil roulant",142}143_UNIT_TYPES = {144 "apartment": "Appartement", "condo": "Condo",145 "basement-apartment": "Appartement au sous-sol", "house": "Maison",146 "townhouse": "Maison de ville", "duplex-triplex": "Duplex/Triplex",147}148_AGREEMENTS = {"one-year": "Bail de 1 an", "month-to-month": "Au mois",149 "not-available": ""}150# villes fréquentes sans accents dans les adresses Kijiji151_CITY_FIX = {152 "montreal": "Montréal", "quebec": "Québec", "levis": "Lévis",153 "trois-rivieres": "Trois-Rivières", "riviere-des-prairies": "Montréal",154 "ville de montreal": "Montréal", "ville de quebec": "Québec",155}156157158# loyer mensuel écrit dans le texte (annonces « Sur demande ») : un montant159# DOIT toucher un « $ » ET un mot mensuel (mois/month) ou un libellé loyer/prix160_NUM = r"(\d{1,2}[\s,.]?\d{3}|\d{3,4})"161_PRICE_TXT_RE = re.compile(162 r"\b(?:loyer|prix|rent|price)\s*:?\s*(?:est\s+de\s+|de\s+|à partir de\s+)?"163 + _NUM + r"(?:[.,]\d{2})?\s*\$"164 r"|" + _NUM + r"(?:[.,]\d{2})?\s*\$\s*"165 r"(?:/|par\s+|per\s+)\s*(?:mois|month)"166 r"|\$\s*" + _NUM + r"(?:\.\d{2})?\s*(?:/|per\s+|a\s+)\s*month"167 # fourchette « $1,100 to $1,300/month » : capter la borne BASSE aussi168 r"|\$\s*" + _NUM + r"(?:\.\d{2})?\s*(?:to|à|[-–])\s*\$\s*[\d ,.]+"169 r"\s*(?:/|per\s+)\s*month",170 re.I)171172173def _price_from_text(text: str) -> float | None:174 """Loyer mensuel plausible (300–12 000 $) déduit du texte de l'annonce.175176 Conservateur : montant collé à un « $ » et à un contexte mensuel177 (loyer/prix/rent ou /mois, /month). Le plus BAS des montants trouvés178 (« à partir de… ») ; None si rien de plausible — jamais inventé.179 """180 vals = []181 for m in _PRICE_TXT_RE.finditer(text or ""):182 raw = next(g for g in m.groups() if g)183 try:184 val = float(re.sub(r"[\s,.]", "", raw))185 except ValueError:186 continue187 if 300 <= val <= 12000:188 vals.append(val)189 return min(vals) if vals else None190191192def _fix_city(raw: str) -> str:193 key = (raw or "").strip().lower()194 if key in _CITY_FIX:195 return _CITY_FIX[key]196 return " ".join(w.capitalize() for w in key.replace("-", " ").split())197198199def _attr_value(a: dict) -> str:200 """Première valeur d'un attribut Apollo (canonique, sinon affichée)."""201 for k in ("canonicalValues", "values"):202 vals = a.get(k) or []203 if vals:204 return str(vals[0])205 return ""206207208def _apply_attrs(attrs: list[dict], out: dict) -> None:209 """Interprète les attributs Kijiji (mêmes clés en liste et en fiche)."""210 amenities = out.setdefault("amenities", [])211 details = out.setdefault("details", {})212 for a in attrs or []:213 cn = a.get("canonicalName") or ""214 val = _attr_value(a)215 if not val:216 continue217 if cn in _AMENITY_LABELS:218 if val == "1":219 amenities.append(_AMENITY_LABELS[cn])220 elif cn == "furnished":221 out["furnished"] = val == "1"222 elif cn == "petsallowed":223 out["pets"] = "oui" if val == "1" else "non"224 elif cn == "numberbedrooms":225 out["bedrooms"] = val # '0' = studio, sinon nb de chambres226 elif cn == "numberbathrooms":227 try: # canonique en dixièmes : '15' = 1.5228 n = int(val) / 10229 details["Salles de bain"] = f"{n:g}"230 except ValueError:231 pass232 elif cn in ("areainfeet", "sizesqft"):233 m = re.search(r"[\d.]+", val.replace(",", ""))234 if m and float(m.group(0)) > 0:235 out["area_sqft"] = float(m.group(0))236 elif cn == "dateavailable":237 m = re.match(r"(\d{4}-\d{2}-\d{2})", val)238 if m:239 out["availability_date"] = m.group(1)240 elif cn == "unittype":241 details["Type d'unité"] = _UNIT_TYPES.get(val, val)242 elif cn == "agreementtype":243 bail = _AGREEMENTS.get(val, val)244 if bail:245 details["Bail"] = bail246 elif cn == "numberparkingspots" and val.isdigit() and int(val) > 0:247 amenities.append(f"Stationnement ({val})")248249250def _parse_kijiji_detail(html: str) -> dict:251 """Fiche Kijiji : description complète, attributs, galerie haute résolution."""252 m = _NEXT_RE.search(html)253 if not m:254 return {}255 try:256 data = json.loads(m.group(1))257 except ValueError:258 return {}259 apollo = data.get("props", {}).get("pageProps", {}).get("__APOLLO_STATE__", {})260 it = next((v for k, v in apollo.items()261 if _LISTING_KEY_RE.match(k) and isinstance(v, dict)262 and v.get("description")), None)263 if not it:264 return {}265 out: dict = {}266 if it.get("description"):267 out["description"] = str(it["description"]).strip()[:6000]268 imgs = [re.sub(r"rule=kijijica-\d+-\w+", "rule=kijijica-1600-jpg", u)269 for u in it.get("imageUrls") or []]270 if imgs:271 out["images"] = imgs272 _apply_attrs((it.get("attributes") or {}).get("all") or [], out)273 out.pop("bedrooms", None) # le type d'unité est déjà fixé au niveau liste274 loc = it.get("location") or {}275 addr = (loc.get("address") or "").replace(", Canada", "")276 if re.match(r"\s*\d", addr):277 out["address"] = addr.split(",")[0]278 return out279280281class KijijiConnector(BaseConnector):282 source_id = "kijiji"283 request_delay = 1.2284285 def _page(self, seg: str, cat: int, page: int) -> list[dict]:286 """Annonces (Apollo state) d'une page de catégorie."""287 path = (f"{seg}/quebec/c{cat}l9001" if page == 1288 else f"{seg}/quebec/page-{page}/c{cat}l9001")289 html = self.get(f"{BASE}/{path}").text290 m = _NEXT_RE.search(html)291 data = json.loads(m.group(1)) if m else {}292 apollo = (data.get("props", {}).get("pageProps", {})293 .get("__APOLLO_STATE__", {}))294 return [v for k, v in apollo.items()295 if _LISTING_KEY_RE.match(k) and isinstance(v, dict)]296297 def _to_listing(self, it: dict, unit_default: str) -> Listing | None:298 lid = str(it.get("id") or "")299 url = it.get("url") or ""300 if not lid or not url:301 return None302 price = None303 pr = it.get("price") or {}304 if isinstance(pr, dict) and pr.get("amount"):305 price = round(pr["amount"] / 100.0, 0) # cents → $/mois306 loc = it.get("location") or {}307 coords = loc.get("coordinates") or {}308 address = (loc.get("address") or "").replace(", Canada", "")309 parts = [p.strip() for p in address.split(",") if p.strip()]310 # adresse à la française « 89, rue Dartois, Montréal » : le n° civique311 # arrive seul en tête — le recoller à la rue, sinon la rue devenait312 # la « ville » et polluait les filtres313 if len(parts) >= 2 and re.fullmatch(r"\d+[A-Za-z]?", parts[0]):314 parts = [f"{parts[0]} {parts[1]}"] + parts[2:]315 street = parts[0] if parts and re.match(r"\s*\d", parts[0]) else ""316 # la ville = premier élément après la rue qui n'est ni la province317 # ni un code postal (formats « rue, ville, QC H2X 1X1 »)318 rest = [p for p in (parts[1:] if street else parts)319 if not re.match(r"(?i)^(qc|qu[ée]bec)\b", p)320 and not re.match(r"(?i)^[a-z]\d[a-z]", p)]321 city = _fix_city(rest[0] if rest else (loc.get("name") or ""))322 images = [re.sub(r"rule=kijijica-\d+-", "rule=kijijica-640-", u)323 for u in it.get("imageUrls") or []]324 extra: dict = {}325 _apply_attrs((it.get("attributes") or {}).get("all") or [], extra)326 unit_type = unit_default327 beds = extra.pop("bedrooms", None)328 if not unit_type and beds:329 try: # Kijiji code parfois « 2.5 » (2 ch. + den)330 n = int(float(beds))331 except ValueError:332 n = 0333 unit_type = "Studio" if n == 0 else f"{n} chambres" # → n+2 ½334 lst = Listing(335 source=self.source_id,336 external_id=lid,337 url=url,338 title=it.get("title") or "",339 address=street,340 city=city,341 unit_type=unit_type,342 price=price,343 price_label=(f"{price:,.0f} $/mois".replace(",", " ")344 if price else ""),345 description=(it.get("description") or "")[:2000],346 amenities=extra.get("amenities") or [],347 details=extra.get("details") or {},348 images=images,349 lat=coords.get("latitude"),350 lng=coords.get("longitude"),351 )352 if extra.get("availability_date"):353 lst.availability_date = extra["availability_date"]354 lst.availability = f"Libre le {extra['availability_date']}"355 if extra.get("furnished") is not None:356 lst.furnished = extra["furnished"]357 if extra.get("pets"):358 lst.pets = extra["pets"]359 if extra.get("area_sqft"):360 lst.area_sqft = extra["area_sqft"]361 return lst362363 def fetch(self) -> list[Listing]:364 out: dict[str, Listing] = {}365 for cat, seg, unit_default in CATEGORIES:366 for page in range(1, MAX_PAGES + 1):367 try:368 items = self._page(seg, cat, page)369 except Exception:370 break371 fresh = 0372 for it in items:373 lst = self._to_listing(it, unit_default)374 if lst is not None and lst.uid not in out:375 out[lst.uid] = lst376 fresh += 1377 # plus rien de neuf (page de fin remplie de topAds répétés)378 if fresh == 0 or len(items) < 10:379 break380 listings = list(out.values())381 du.enrich(self, listings, DETAIL_LIMIT, _parse_kijiji_detail, key="v1")382 # prix « Sur demande » : tenter le montant écrit dans le texte de383 # l'annonce (APRÈS enrich : la description complète vient de la fiche)384 for lst in listings:385 if lst.price is None:386 p = _price_from_text(f"{lst.title}\n{lst.description}")387 if p is not None:388 lst.price = p389 lst.price_label = (f"{p:,.0f} $/mois (selon la description)"390 .replace(",", " "))391 elif not lst.price_label:392 lst.price_label = "Sur demande"393 return listings394