SPB Git

Repository Public

immobilia.py 11.9 KB 289 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immobilia.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/immobilia.py : connecteur Immobilia Rimouski (immobiliarimouski.com)91#   Gestionnaire du centre-ville de Rimouski (ex-Immeubles MT, ~100 logements).92#   Site WordPress (Bedrock) + plugin « building-stack-sync » : l'inventaire93#   Building Stack est synchronisé dans le CPT WordPress `bss_property` et94#   rendu côté serveur — famille Building Stack (edifia, urban_services) mais95#   via le DOM WP plutôt que le portail hébergé.96#     - /logements/ : une carte par unité disponible (a.bss-property-item :97#       titre, adresse complète, type (4½/Loft…), sdb, prix, date de dispo) ;98#     - fiche /proprietes/<slug>/ : statut (« Disponible à partir du: … »),99#       bloc infos (prix « X$ par mois », type, sdb, pi², plan PDF),100#       description complète, commodités (feature-list), galerie d'images,101#       lien Google Maps (adresse seulement, pas de GPS).102#   Une annonce Lou-Ka = une unité. Fiches via self.detail() (cache BD,103#   invalidé quand la carte de la liste change), max max_details/sync.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://immobiliarimouski.com"116LIST_URL = f"{BASE}/logements/"117118119def _clean(s: str) -> str:120    return re.sub(r"\s+", " ", s or "").strip()121122123class ImmobiliaConnector(BaseConnector):124    source_id = "immobilia"125    request_delay = 0.6126    max_details = 30     # garde-fou fiches propriété (vraies requêtes par sync)127    max_images = 15128129    def fetch(self) -> list[Listing]:130        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")131        self._fetched = 0132        listings: list[Listing] = []133        for card in soup.select("a.bss-property-item[href]"):134            try:135                lst = self._parse_card(card)136                if lst:137                    listings.append(lst)138            except Exception:139                continue140        return listings141142    # -- carte de la liste /logements/ ---------------------------------------------143    def _parse_card(self, card) -> Listing | None:144        url = card["href"]145        slug = url.rstrip("/").rsplit("/", 1)[-1]146        if not slug:147            return None148149        title_el = card.select_one(".property-title")150        title = _clean(title_el.get_text(" ", strip=True)) if title_el else slug151        addr_el = card.select_one(".address")152        address = _clean(addr_el.get_text(" ", strip=True)) if addr_el else ""153        # « 201 - 149 Rue de l'Évêché Ouest, Rimouski, QC, Canada »154        parts = [p.strip() for p in address.split(",") if p.strip()]155        city = ""156        for i, p in enumerate(parts):157            if p.upper() == "QC" and i >= 1:158                city = parts[i - 1]159                break160161        # type (4½, Loft…) et sdb : icônes structurées de la carte162        unit_type_raw, bath = "", ""163        for w in card.select(".features .info-wrapper"):164            val = _clean(w.select_one(".info-value").get_text(" ", strip=True)165                         if w.select_one(".info-value") else "")166            if w.select_one(".fa-building"):167                unit_type_raw = val168            elif w.select_one(".fa-bath"):169                bath = val170171        price_el = card.select_one(".price-box .price")172        price_txt = _clean(price_el.get_text(" ", strip=True)) if price_el else ""173        avail_el = card.select_one(".availability-tag")174        card_avail = _clean(avail_el.get_text(" ", strip=True)) if avail_el else ""175176        # fiche propriété (cache BD, invalidée quand la carte change)177        card_sig = f"{address}|{unit_type_raw}|{bath}|{price_txt}|{card_avail}"178        cache_key = hashlib.sha1(card_sig.encode("utf-8")).hexdigest()179180        def fetch_fn():181            if self._fetched >= self.max_details:182                raise RuntimeError("budget de fiches propriété atteint")183            self._fetched += 1184            return self._fetch_property(url)185186        payload = self.detail(slug, cache_key, fetch_fn)187188        amenities = list(payload.get("features", []))189        if bath:190            amenities.insert(0, f"{bath} salle(s) de bain")191192        details: dict = {}193        if payload.get("floorplan"):194            details["floorplan"] = payload["floorplan"]195        if payload.get("maps_url"):196            details["maps_url"] = payload["maps_url"]197198        # prix : la carte affiche le montant nu (« 900 ») -> la fiche fait foi199        price_label = payload.get("price_label") or ""200        price = parse_price(price_label)201        if price is None and re.fullmatch(r"[\d\s  ]+", price_txt or ""):202            price = parse_price(price_txt + " $")203            price_label = price_label or f"{price_txt} $"204205        area = None206        try:207            v = float(payload.get("area") or 0)208            if 80 <= v <= 20000:209                area = v210        except (TypeError, ValueError):211            pass212213        return Listing(214            source=self.source_id,215            external_id=slug,216            url=url,217            title=title,218            address=address,219            sector="",220            city=city or "Rimouski",221            unit_type=normalize_unit_type(payload.get("unit_type")222                                          or unit_type_raw),223            price=price,224            price_label=price_label,225            availability=payload.get("status") or card_avail,226            area_sqft=area,227            description=payload.get("description", ""),228            amenities=amenities,229            details=details,230            images=payload.get("images", [])[: self.max_images],231        )232233    # -- fiche /proprietes/<slug>/ ----------------------------------------------------234    def _fetch_property(self, url: str) -> dict:235        """Payload JSON-sérialisable : infos structurées de la fiche."""236        soup = BeautifulSoup(self.get(url).text, "html.parser")237        payload: dict = {}238239        # statut (« Disponible à partir du: 15 août 2026 », « Disponible »)240        status = soup.select_one(".property-status")241        if status:242            payload["status"] = _clean(status.get_text(" ", strip=True))243244        # bloc « general-info » : prix / type / sdb / superficie / plan PDF245        for col in soup.select(".general-info .info-col"):246            val = _clean(col.get_text(" ", strip=True))247            if col.select_one(".fa-dollar-sign"):248                payload["price_label"] = val            # « 900$ par mois »249            elif col.select_one(".fa-building"):250                payload["unit_type"] = val              # « Loft », « 4 1/2 »251            elif col.select_one(".fa-ruler"):252                m = re.search(r"([\d\s  ]+)\s*pi", val)253                if m:254                    payload["area"] = re.sub(r"[\s  ]", "", m.group(1))255            if col.name == "a" and col.get("href", "").lower().endswith(".pdf"):256                payload["floorplan"] = col["href"]257258        # description complète (paragraphes et puces, ordre du DOM)259        desc = soup.select_one(".bss-property-container .description")260        if desc:261            payload["description"] = _clean(262                desc.get_text(" ", strip=True))[:2000]263264        # commodités (« Accès à internet inclus », « Réfrigérateur »…)265        features: list[str] = []266        for f in soup.select(".feature-list .feature"):267            t = _clean(f.get_text(" ", strip=True))268            if 2 <= len(t) <= 90 and t not in features:269                features.append(t)270        payload["features"] = features271272        # galerie (carrousel de la visionneuse, URLs absolues, dédupliquées)273        images: list[str] = []274        for img in soup.select(".simple-carousel-slide img[data-src]"):275            u = img["data-src"]276            if u.startswith("http") and u not in images:277                images.append(u)278        if not images:      # repli : image principale de la fiche279            m = re.search(r"data-bg-image=\"url\('([^']+)'\)", str(soup))280            if m:281                images.append(m.group(1))282        payload["images"] = images283284        # lien Google Maps (adresse complète avec code postal — pas de GPS)285        maps = soup.select_one('a.under-map-button[href^="http"]')286        if maps:287            payload["maps_url"] = maps["href"]288        return payload289
Files main
Menu

Theme