SPB Git

Repository Public

carat_immobilier.py 12.3 KB 298 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/carat_immobilier.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/carat_immobilier.py : connecteur Carat Immobilier91#   (caratimmobilier.ca — Rouyn-Noranda, Abitibi-Témiscamingue). WordPress +92#   thème immobilier Houzez (cartes v2), tout rendu serveur — même famille que93#   gimcote.py / immeubles_bc.py. Archive /appartements/ : cartes94#   `.item-listing-wrap` (statut « Disponible… », prix « 1 ,058$ », adresse95#   complète, galerie dans data-images). Fiche détail /property/<slug>/ (via96#   cache BD) : description, commodités (#property-features-wrap), bloc97#   « Détails » structuré (type 4 1/2, chambres, salle de bain, superficie) et98#   bloc adresse (ville, quartier, immeuble). Pas de GPS réel (carte Houzez99#   sur coordonnées par défaut). robots.txt Yoast ouvert, sitemap XML.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import html as htmllib105import json106import re107108from bs4 import BeautifulSoup109110from ..schema import (Listing, normalize_unit_type, parse_area_sqft,111                      parse_price, strip_accents)112from .base import BaseConnector113114BASE = "https://caratimmobilier.ca"115LIST_URL = f"{BASE}/appartements/"116117# suffixe de redimensionnement WordPress (« -584x438.jpg » -> pleine taille)118_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)119120121def _clean_price_label(label: str) -> str:122    """'1 ,058$' (Houzez) -> '1058$' compatible parse_price (virgule = milliers)."""123    label = re.sub(r"(\d)\s*,\s*(\d{3})", r"\1\2", label)124    return re.sub(r"\s+", " ", label).strip()125126127class CaratImmobilierConnector(BaseConnector):128    source_id = "carat_immobilier"129    request_delay = 0.6130    max_details = 30     # garde-fou fiches détail (vraies requêtes par sync)131132    def fetch(self) -> list[Listing]:133        html = self.get(LIST_URL).text134        soup = BeautifulSoup(html, "html.parser")135136        listings: dict[str, Listing] = {}137        for card in soup.select("div.item-listing-wrap"):138            try:139                self._parse_card(card, listings)140            except Exception:141                continue142143        # fiches détail (cache BD) : description, commodités, type, superficie144        self._fetched = 0145        for lst in listings.values():146            key = hashlib.sha1(147                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"148                .encode("utf-8")).hexdigest()149            try:150                payload = self.detail(lst.external_id, key,151                                      lambda u=lst.url: self._fetch_detail(u))152            except Exception:153                continue154            self._apply_detail(lst, payload)155        return list(listings.values())156157    # -- carte Houzez v2 ---------------------------------------------------------------158    def _parse_card(self, card, listings: dict[str, Listing]) -> None:159        link = card.select_one("h2.item-title a[href]") \160            or card.select_one('a[href*="/property/"]')161        if not link:162            return163        url = link["href"]164        m = re.search(r"/property/([^/?#]+)", url)165        slug = m.group(1) if m else ""166        ext_id = card.get("data-hz-id") or slug167        if not ext_id or str(ext_id) in listings:168            return169        title = link.get_text(strip=True)170171        # exclusions : commercial / stationnement / rangement172        if re.search(r"commercial|bureau|local|stationnement|garage|entrep[oô]t",173                     title, re.I):174            return175176        # statut (« Disponible 1er septembre », « Loué ») — on saute les loués177        status_el = card.select_one(".label-status")178        availability = status_el.get_text(strip=True) if status_el else ""179        if re.search(r"lou[ée]", availability, re.I):180            return181182        # adresse complète : « 769 Av. Murdoch, Rouyn-Noranda, QC J9X 1H9, Canada »183        addr_el = card.select_one("address.item-address")184        address = addr_el.get_text(" ", strip=True) if addr_el else ""185        city = "Rouyn-Noranda"               # tout le parc est à Rouyn-Noranda186        parts = [p.strip() for p in address.split(",") if p.strip()]187        for p in parts[1:]:188            if not re.match(r"^(QC|Québec|Quebec|Canada|[A-Z]\d[A-Z])", p, re.I):189                city = re.sub(r"\s+(QC|Québec|Quebec).*$", "", p, flags=re.I).strip() or city190                break191192        price_el = card.select_one("li.item-price")193        price_label = _clean_price_label(194            price_el.get_text(strip=True)) if price_el else ""195196        # galerie complète : attribut data-images (JSON, URLs redimensionnées)197        images: list[str] = []198        raw = card.get("data-images") or ""199        if raw:200            try:201                entries = json.loads(htmllib.unescape(raw))202                urls = [e.get("image", "") for e in entries if isinstance(e, dict)]203            except Exception:204                urls = re.findall(r"https?:[^\"',\\]+", htmllib.unescape(raw))205            for u in urls:206                u = u.replace("\\/", "/").strip()207                if not u.startswith("http"):208                    continue209                u = _SIZE_SUFFIX.sub("", u)   # version pleine taille (WordPress)210                if u not in images:211                    images.append(u)212        if not images:213            thumb = card.select_one("img.wp-post-image[src]")214            if thumb:215                images = [_SIZE_SUFFIX.sub("", thumb["src"])]216217        # type d'unité : « 4 ½ » présent dans le titre de l'annonce218        unit_type = ""219        m_type = re.search(r"\b(\d)\s*(?:1/2|½)", title)220        if m_type:221            unit_type = normalize_unit_type(f"{m_type.group(1)} 1/2")222223        listings[str(ext_id)] = Listing(224            source=self.source_id,225            external_id=str(ext_id),226            url=url,227            title=title,228            address=address,229            city=city,230            unit_type=unit_type,231            price=parse_price(price_label),232            price_label=price_label,233            availability=availability,234            images=images[:30],235        )236237    # -- fiche détail (Houzez) -----------------------------------------------------238    def _fetch_detail(self, url: str) -> dict:239        """Description, commodités, bloc « Détails » et bloc adresse."""240        if self._fetched >= self.max_details:241            raise RuntimeError("budget de fiches détail atteint")242        self._fetched += 1243        html = self.get(url).text244        soup = BeautifulSoup(html, "html.parser")245        out: dict = {}246247        desc_el = soup.select_one("#property-description-wrap")248        if desc_el:249            txt = desc_el.get_text("\n", strip=True)250            txt = re.sub(r"^Description\n", "", txt)251            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]252253        out["amenities"] = [a.get_text(" ", strip=True)254                            for a in soup.select("#property-features-wrap li")255                            if a.get_text(strip=True)][:20]256257        # bloc « Détails » : paires <strong>label</strong><span>valeur</span>258        fields: dict[str, str] = {}259        for li in soup.select("#property-detail-wrap li"):260            strong = li.select_one("strong")261            span = li.select_one("span")262            if strong and span:263                key = strip_accents(strong.get_text(strip=True).lower())264                fields[key] = span.get_text(" ", strip=True)265        out["fields"] = fields266267        # bloc adresse : « Ville: Rouyn Noranda », « Quartier: Rouyn »…268        for li in soup.select("#property-address-wrap li"):269            txt = li.get_text(" ", strip=True)270            m = re.match(r"(Ville|Quartier)\s*:\s*(.+)$", txt, re.I)271            if m:272                out[strip_accents(m.group(1).lower())] = m.group(2).strip()273        return out274275    def _apply_detail(self, lst: Listing, d: dict) -> None:276        """Reporte le payload (frais ou en cache) sur l'annonce."""277        if not d:278            return279        desc = d.get("description") or ""280        if desc and desc.strip() != lst.address.strip():281            lst.description = desc282283        fields = d.get("fields") or {}284        extra: list[str] = []285        if fields.get("chambres"):286            extra.append(f"{fields['chambres']} chambre(s)")287        if fields.get("salle de bain"):288            extra.append(f"{fields['salle de bain']} salle(s) de bain")289        if d.get("amenities") or extra:290            lst.amenities = list(dict.fromkeys(291                lst.amenities + extra + (d.get("amenities") or [])))292        if not lst.unit_type and fields.get("type de propriete"):293            lst.unit_type = normalize_unit_type(fields["type de propriete"])294        if lst.area_sqft is None and fields.get("superficie"):295            lst.area_sqft = parse_area_sqft(fields["superficie"])296        if d.get("quartier"):297            lst.sector = d["quartier"]298
Files main
Menu

Theme