Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/terater.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/terater.py : connecteur Les Constructions Tèratèr (terater.ca)91# Constructeur-locateur de l'Estrie : Val-Joli/Windsor, Sherbrooke (Nord,92# Fleurimont, Seyval), Orford, Cookshire-Eaton. WordPress + thème enfant93# Avada avec blocs maison (même famille de balisage que morin.py) : archive94# /a-louer/ rendue serveur — cartes div.landing_modele_block_item complètes95# (bandeau de disponibilité coloré, type « 3 ½ », adresse, secteur/ville,96# chambres/salle de bain/étage/stationnement/animaux, prix « par mois »).97# La fiche (via self.detail, cache BD) ajoute la superficie, la liste des98# inclusions et la galerie photos. Les logements loués n'apparaissent pas99# dans l'archive (bandeau « Loué » absent au moment de l'écriture) mais on100# filtre par prudence.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://terater.ca"113LIST_URL = f"{BASE}/a-louer/"114115# variantes redimensionnées WordPress (-600x397.jpg) -> pleine taille116_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)117118# villes réelles desservies (jamais devinées) + secteurs de Sherbrooke connus119_KNOWN_CITIES = [120 "Sherbrooke", "Windsor", "Val-Joli", "Orford", "Cookshire-Eaton",121 "East Angus", "Magog", "Richmond", "Ascot Corner", "Saint-Denis-de-Brompton",122]123_SHERBROOKE_SECTORS = [124 "Fleurimont", "Rock Forest", "Lennoxville", "Mont-Bellevue",125 "Jacques-Cartier", "Brompton", "Saint-Élie", "St-Élie",126]127128# espaces non résidentiels dans le champ « type » de la carte129_NON_RESIDENTIAL_RE = re.compile(130 r"commercial|bureau|local|garage|entrep[oô]t|rangement", re.I)131132133def _city_sector(raw: str) -> tuple[str, str]:134 """« Val-Joli » -> (Val-Joli, '') ; « Nord de Sherbrooke » ->135 (Sherbrooke, Nord de Sherbrooke) ; « Fleurimont » -> (Sherbrooke,136 Fleurimont). Ville vide si le secteur est inconnu (rien d'inventé)."""137 t = re.sub(r"\s+", " ", raw or "").strip()138 if not t:139 return "", ""140 for city in _KNOWN_CITIES:141 if t.lower() == city.lower():142 return city, ""143 if re.search(r"\bsherbrooke\b", t, re.I):144 return "Sherbrooke", t145 for sec in _SHERBROOKE_SECTORS:146 if t.lower() == sec.lower():147 return "Sherbrooke", t148 return "", t149150151def _clean_unit_type(raw: str) -> str:152 """normalize_unit_type seulement si le motif est net (« 3 ½ », studio…)."""153 ut = normalize_unit_type(raw or "")154 if re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison", ut or ""):155 return ut156 return ""157158159class TeraterConnector(BaseConnector):160 source_id = "terater"161 request_delay = 0.7162 max_details = 30 # garde-fou fiches détail (vraies requêtes)163164 def fetch(self) -> list[Listing]:165 html = self.get(LIST_URL).text166 soup = BeautifulSoup(html, "html.parser")167168 listings: dict[str, Listing] = {}169 for card in soup.select("div.landing_modele_block_item"):170 try:171 self._parse_card(card, listings)172 except Exception:173 continue174175 # fiches détail (cache BD) : superficie, inclusions, galerie176 self._fetched = 0177 for lst in listings.values():178 card_key = hashlib.sha1(179 f"{lst.title}|{lst.price_label}|{lst.availability}"180 .encode("utf-8")).hexdigest()181 try:182 payload = self.detail(lst.external_id, card_key,183 lambda u=lst.url: self._fetch_detail(u))184 except Exception:185 continue186 self._apply_detail(lst, payload)187 return list(listings.values())188189 # -- carte de l'archive /a-louer/ ------------------------------------------190 def _parse_card(self, card, listings: dict[str, Listing]) -> None:191 link = card.select_one("a.landing_modele_block_item_link[href]")192 if not link:193 return194 url = link["href"]195 m = re.search(r"/a-louer/([^/]+)/?", url)196 if not m:197 return198 ext_id = m.group(1)199 if ext_id in listings or "formulaire" in ext_id:200 return201202 # bandeau(x) de disponibilité : « Libre immédiatement », « Juillet203 # 2026 »… — on écarte tout logement marqué loué204 tags = [re.sub(r"\s+", " ", t.get_text(" ", strip=True)).strip()205 for t in card.select(".landing_modele_item_tag_item")]206 tags = [t for t in tags if t]207 if any(re.search(r"\blou[ée]s?\b", t, re.I) for t in tags):208 return209 availability = tags[0] if tags else ""210211 # type d'espace (« Appartement », « Maison »…) : écarter le non212 # résidentiel (locaux commerciaux, garages…)213 category = ""214 cat_el = card.select_one(".landing_modele_block_item_type")215 if cat_el:216 category = cat_el.get_text(" ", strip=True)217 if _NON_RESIDENTIAL_RE.search(category):218 return219220 piece_el = card.select_one(".landing_modele_piece")221 piece = piece_el.get_text(" ", strip=True) if piece_el else ""222223 addr_el = card.select_one(".landing_modele_block_item_adresse")224 address = re.sub(r"\s+", " ", addr_el.get_text(" ", strip=True)).strip() \225 if addr_el else ""226227 sect_el = card.select_one(".landing_modele_block_item_secteur div")228 city, sector = _city_sector(229 sect_el.get_text(" ", strip=True) if sect_el else "")230231 # prix : « 1 075$ » + « par mois »232 price_el = card.select_one(".landing_modele_price")233 after_el = card.select_one(".landing_modele_price_after")234 price_label = ""235 if price_el:236 price_label = price_el.get_text(" ", strip=True)237 if after_el:238 price_label += " " + after_el.get_text(" ", strip=True)239240 # pictos : chambres / salle de bain / étage / stationnement / animaux241 amenities: list[str] = []242 for cls, label in [("landing_modele_item_bed", "Chambres"),243 ("landing_modele_item_bath", "Salle(s) de bain"),244 ("landing_modele_etage", "Étage"),245 ("landing_modele_stationnement", "Stationnement")]:246 el = card.select_one(f".{cls} span")247 if el:248 val = re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()249 if val:250 amenities.append(f"{label} : {val}")251 animals_el = card.select_one(".landing_modele_animaux .animaux_note")252 if animals_el:253 note = animals_el.get_text(" ", strip=True)254 if note:255 amenities.append(note) # « Animaux accepter » (texte du site)256257 # visuel de la carte (background-image)258 images: list[str] = []259 img_el = card.select_one(".landing_modele_block_item_img_bg[style]")260 if img_el:261 m_img = re.search(r"url\('([^']+)'\)", img_el.get("style") or "")262 if m_img:263 images = [_SIZE_SUFFIX.sub("", m_img.group(1))]264265 title = " ".join(p for p in (piece, category, "—", address) if p) \266 if address else (piece or category)267 details = {"category": category} if category else {}268269 listings[ext_id] = Listing(270 source=self.source_id,271 external_id=ext_id,272 url=url,273 title=re.sub(r"\s+", " ", title).strip(),274 address=address,275 sector=sector,276 city=city,277 unit_type=_clean_unit_type(piece),278 price=parse_price(price_label),279 price_label=price_label,280 availability=availability,281 amenities=amenities,282 details=details,283 images=images,284 )285286 # -- fiche détail -----------------------------------------------------------287 def _fetch_detail(self, url: str) -> dict:288 """Superficie, inclusions et galerie de la fiche single_modele_*."""289 if self._fetched >= self.max_details:290 raise RuntimeError("budget de fiches détail atteint")291 self._fetched += 1292 html = self.get(url).text293 soup = BeautifulSoup(html, "html.parser")294 out: dict = {}295296 sup_el = soup.select_one(".single_modele_superficie")297 if sup_el:298 out["superficie"] = re.sub(299 r"\s+", " ", sup_el.get_text(" ", strip=True)).strip()300301 out["inclusions"] = [302 re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()303 for el in soup.select(".single_modele_inclus_item_name")304 if el.get_text(strip=True)][:30]305306 # galerie : photos du bloc .single_modele_galerie seulement — les307 # blocs slider_modele_* en pied de page sont les AUTRES logements308 images: list[str] = []309 gal = soup.select_one(".single_modele_galerie")310 if gal:311 for u in re.findall(312 r"https://terater\.ca/wp-content/uploads/[^\"'()\s]+"313 r"\.(?:jpg|jpeg|webp)", str(gal), re.I):314 u = _SIZE_SUFFIX.sub("", u)315 if u not in images:316 images.append(u)317 out["images"] = images[:30]318 return out319320 def _apply_detail(self, lst: Listing, d: dict) -> None:321 if not d:322 return323 if d.get("superficie"): # « Superficie : 1375 pi² »324 lst.amenities = list(dict.fromkeys(lst.amenities + [d["superficie"]]))325 if d.get("inclusions"):326 lst.amenities = list(dict.fromkeys(lst.amenities + d["inclusions"]))327 if d.get("images"):328 merged = list(dict.fromkeys(d["images"] + lst.images))329 lst.images = merged[:30]330