Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gimcote.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-09-1414#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/gimcote.py : connecteur GIM Côté inc. (gimcote.com)91# WordPress + thème immobilier Houzez. Archive /property-type/appartement92# paginée : chaque carte contient prix, adresse, statut, type et la galerie93# complète d'images (attribut data-images). Les fiches détail (via cache BD)94# ajoutent description, caractéristiques, bloc « Détails » structuré95# (animaux, meublé, fumeur, stationnement) et coordonnées GPS.96# 2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,97# en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient98# (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA99# (même pattern que boreal_abitibi/citiluxx/cromwell/deschenes_pepin/100# gestion_habitation, hébergeur identique).101# 2026-09-14 : l'IP résidentielle collante tirée peut elle-même être flaguée102# (challenge ou 403 SiteGround, ~1 run sur 2) ; on tourne donc l'IP103# (jusqu'à 2 nouvelles sessions collantes) avant l'erreur franche — même104# durcissement que boreal_abitibi.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import hashlib109import html as htmllib110import json111import os112import re113import time114from urllib.parse import quote115116from bs4 import BeautifulSoup117118from ..schema import (Listing, infer_city, normalize_unit_type, parse_price,119 strip_accents)120from .base import BaseConnector121122BASE = "https://gimcote.com"123LIST_URL = f"{BASE}/property-type/appartement/"124125# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)126_SG_MARKER = "/.well-known/sgcaptcha/"127128129def _sg_challenge(resp) -> bool:130 """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""131 if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():132 return True133 return _SG_MARKER in (resp.text or "")[:600]134135_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)136137138def _clean_price_label(label: str) -> str:139 """'1,450$/Par mois' -> '1450$' compatible parse_price (virgule = milliers)."""140 return re.sub(r"(\d),(\d{3})", r"\1\2", label)141142143_MAP_LATLNG_RE = re.compile(r'"lat"\s*:\s*"(-?\d+\.\d+)"\s*,\s*"lng"\s*:\s*"(-?\d+\.\d+)"')144145146def _oui_non(raw: str) -> bool | None:147 """'Oui'/'Non' (et variantes) -> bool, sinon None (inconnu)."""148 k = strip_accents((raw or "").strip().lower())149 if k in ("oui", "yes") or k.startswith("oui"):150 return True151 if k in ("non", "no") or k.startswith("non"):152 return False153 return None154155156def _pets_value(raw: str) -> str | None:157 """Valeur « Animaux » de la fiche -> oui/non/conditions (jamais deviné)."""158 k = strip_accents((raw or "").strip().lower())159 if not k:160 return None161 if k.startswith("non") or "refus" in k or "aucun" in k:162 return "non"163 if k.startswith("oui") or "accepte" in k:164 return "oui"165 # « Chat opéré », « Chat seulement », « Petit chien »… = sous conditions166 if re.search(r"chat|chien|opere|seulement|condition|approbation", k):167 return "conditions"168 return None169170171class GimCoteConnector(BaseConnector):172 source_id = "gimcote"173 request_delay = 0.6174 max_pages = 20 # garde-fou de pagination175 max_details = 150 # garde-fou fiches détail (vraies requêtes)176177 def _enable_residential_proxy(self) -> bool:178 """Route toute la session via Oxylabs résidentiel CA (session collante)."""179 endpoint = os.environ.get("OXYLABS_PROXY")180 user = os.environ.get("OXYLABS_PROXY_USER")181 pwd = os.environ.get("OXYLABS_PROXY_PASS")182 if not (endpoint and user and pwd):183 return False184 puser = f"{user}-cc-CA-sessid-gimcote{time.time_ns()}-sesstime-10"185 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"186 self.session.proxies = {"http": proxy, "https": proxy}187 self.session.verify = False # CA MITM du proxy Oxylabs (cf. _resilient)188 return True189190 def _get_html(self, url: str) -> str:191 """GET avec contournement du challenge sgcaptcha (proxy résidentiel).192193 Une IP résidentielle collante peut elle-même être flaguée : on tire194 jusqu'à 2 nouvelles sessions collantes avant l'erreur franche.195 """196 resp = self.get(url)197 if not _sg_challenge(resp):198 return resp.text199 for _ in range(2):200 if not self._enable_residential_proxy():201 break202 resp = self.get(url)203 if not _sg_challenge(resp):204 return resp.text205 raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")206207 def fetch(self) -> list[Listing]:208 listings: dict[str, Listing] = {}209 for page in range(1, self.max_pages + 1):210 url = LIST_URL if page == 1 else f"{LIST_URL}page/{page}/"211 if page == 1:212 # la 1re page échoue franchement sur challenge (fini le213 # « 0 trouvé ok » silencieux — ingest journalise ok=0)214 html = self._get_html(url)215 else:216 try:217 html = self._get_html(url)218 except Exception:219 break220 soup = BeautifulSoup(html, "html.parser")221 cards = soup.select("div.item-listing-wrap")222 if not cards:223 break224 for card in cards:225 try:226 self._parse_card(card, listings)227 except Exception:228 continue229230 # Fiches détail (cache BD) : description, caractéristiques, bloc231 # « Détails » structuré (animaux/meublé/fumeur/stationnement), GPS232 self._fetched = 0233 for lst in listings.values():234 card_key = hashlib.sha1(235 f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"236 .encode("utf-8")).hexdigest()237 try:238 payload = self.detail(lst.external_id, card_key,239 lambda u=lst.url: self._fetch_detail(u))240 except Exception:241 continue242 self._apply_detail(lst, payload)243244 return list(listings.values())245246 # -- carte Houzez -----------------------------------------------------------247 def _parse_card(self, card, listings: dict[str, Listing]) -> None:248 link = card.select_one("h2.item-title a[href]")249 if not link:250 return251 url = link["href"]252 title = link.get_text(strip=True)253 m = re.search(r"/property/([^/]+)/?", url)254 slug = m.group(1) if m else ""255 listid_el = card.select_one("[data-listid]")256 ext_id = (listid_el.get("data-listid") if listid_el else "") or slug257 if not ext_id or ext_id in listings:258 return259260 # exclusions : stationnement / commercial / rangement261 if re.search(r"stationnement|commercial|rangement|garage|entrep[oô]t",262 title, re.I):263 return264265 # adresse complète (Nominatim) : "3345, Avenue du Colisée, Lairet,266 # La Cité-Limoilou, Quebec, Urban agglomeration of Québec, ..."267 addr_el = card.select_one("address.item-address")268 full_addr = addr_el.get_text(" ", strip=True) if addr_el else ""269 parts = [p.strip() for p in full_addr.split(",") if p.strip()]270 address = ", ".join(parts[:2]) if len(parts) >= 2 else full_addr271 if "lévis" in full_addr.lower() or "levis" in full_addr.lower():272 city = "Lévis"273 elif "québec" in full_addr.lower() or "quebec" in full_addr.lower() or not full_addr:274 city = "Québec"275 else:276 return # hors Québec / Lévis277 # secteur = micro-quartier + arrondissement (avant les mentions génériques)278 sector_parts = [p for p in parts[2:]279 if not re.search(r"^(quebec|québec|urban agglomeration|"280 r"capitale-nationale|chaudière-appalaches|"281 r"canada|g\d[a-z]\s?\d[a-z]\d)", p, re.I)]282 sector = ", ".join(sector_parts[:2])283 city = infer_city(sector, default=city)284285 # statut / disponibilité — on saute les logements déjà loués286 status_el = card.select_one("a[href*='/status/']")287 availability = status_el.get_text(strip=True) if status_el else ""288 if re.search(r"lou[ée]", availability, re.I):289 return290291 # type d'unité : le titre (rédigé par l'agence) prime sur l'étiquette,292 # parfois erronée ; repli sur l'étiquette /label/ de la carte293 type_el = card.select_one("a[href*='/label/']")294 unit_type = normalize_unit_type(title)295 if not re.fullmatch(r"\d½|Studio|Loft|Chambre|Maison", unit_type or ""):296 unit_type = normalize_unit_type(type_el.get_text(strip=True) if type_el else "")297 price_el = card.select_one("li.item-price")298 price_label = price_el.get_text(strip=True) if price_el else ""299300 amenities = []301 for li in card.select("ul.item-amenities li"):302 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))303 if t and t not in amenities:304 amenities.append(t)305306 # galerie complète : attribut data-images (JSON, URLs redimensionnées)307 images: list[str] = []308 raw = card.get("data-images") or ""309 if raw:310 try:311 urls = json.loads(htmllib.unescape(raw))312 except Exception:313 urls = re.findall(r"https?:[^\"',\\]+", htmllib.unescape(raw))314 for u in urls:315 u = u.replace("\\/", "/").strip()316 if not u.startswith("http"):317 continue318 u = _SIZE_SUFFIX.sub("", u) # version pleine taille (WordPress)319 if u not in images:320 images.append(u)321 if not images:322 thumb = card.select_one("img.wp-post-image[src]")323 if thumb:324 images = [_SIZE_SUFFIX.sub("", thumb["src"])]325326 listings[str(ext_id)] = Listing(327 source=self.source_id,328 external_id=str(ext_id),329 url=url,330 title=title,331 address=address,332 sector=sector,333 city=city,334 unit_type=unit_type,335 price=parse_price(_clean_price_label(price_label)),336 price_label=price_label,337 availability=availability,338 amenities=amenities,339 images=images[:30],340 )341342 # -- fiche détail (Houzez) ----------------------------------------------------343 def _fetch_detail(self, url: str) -> dict:344 """Description complète, caractéristiques, bloc « Détails » (paires345 libellé/valeur) et coordonnées GPS (JSON de la carte Houzez)."""346 if self._fetched >= self.max_details:347 raise RuntimeError("budget de fiches détail atteint")348 self._fetched += 1349 # _get_html lève sur challenge : pas de {} vide dans detail_cache350 # (clé figée jamais invalidée)351 html = self._get_html(url)352 soup = BeautifulSoup(html, "html.parser")353 out: dict = {}354355 desc_el = soup.select_one("#property-description-wrap")356 if desc_el:357 txt = desc_el.get_text("\n", strip=True)358 txt = re.sub(r"^Description\n", "", txt)359 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1200]360361 out["amenities"] = [a.get_text(" ", strip=True)362 for a in soup.select("#property-features-wrap li")363 if a.get_text(strip=True)][:20]364365 # Paires « Stationnement: Non », « Animaux: Chat opéré », etc.366 for li in soup.select("#property-detail-wrap li"):367 st, sp = li.find("strong"), li.find("span")368 if not (st and sp):369 continue370 lab = strip_accents(st.get_text(" ", strip=True).lower())371 val = sp.get_text(" ", strip=True)372 if "animaux" in lab:373 out["pets_raw"] = val374 elif "meuble" in lab:375 out["furnished_raw"] = val376 elif "fumeur" in lab:377 out["smoking_raw"] = val378 elif "stationnement" in lab:379 out["parking_raw"] = val380381 m = _MAP_LATLNG_RE.search(html)382 if m:383 out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))384 return out385386 def _apply_detail(self, lst: Listing, d: dict) -> None:387 """Reporte le payload (frais/cache) sur l'annonce."""388 if not d:389 return390 if d.get("description"):391 lst.description = d["description"]392 if d.get("amenities"):393 lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))394 pets = _pets_value(d.get("pets_raw", ""))395 if pets:396 lst.pets = pets397 furn = _oui_non(d.get("furnished_raw", ""))398 if furn is not None:399 lst.furnished = furn400 details: dict = {}401 smoking = _oui_non(d.get("smoking_raw", ""))402 if smoking is not None:403 details["smoking"] = smoking404 parking = _oui_non(d.get("parking_raw", ""))405 if parking is not None:406 details["parking"] = {"available": parking}407 if details:408 lst.details = details409 if d.get("lat") is not None and d.get("lng") is not None:410 lst.lat, lst.lng = d["lat"], d["lng"]411