SPB Git

Repository Public

immnasr.py 10.7 KB 270 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immnasr.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/immnasr.py : connecteur Les Immeubles Michel Nazair (immnasr.com)91#   Petit gestionnaire de Gatineau (Mont-Fleuri, Val-Tétreau…). Vieux site92#   « SiteBuilder » (Website.com) rendu serveur : la section À LOUER de93#   l'accueil aligne, pour chaque logement, un bloc texte structuré94#   (« Loyer: 1 325 $/mois », « Disponibilité: 1er octobre 2026 », « Nombre de95#   chambres à coucher », « Surface », « Prises laveuse et sécheuse », « Coût96#   approx. électricité/énergie », « Description: » bilingue) suivi d'un bloc97#   adresse (« 183, du Mont-Fleuri, Gatineau QC »). Les carrousels de photos98#   (CDN dotezcdn.com) précèdent les blocs : chaque galerie est rattachée à99#   son logement par le numéro civique en tête des attributs alt100#   (« 183_Facade… », « 31-2 Salon… », « 8_H-Dupuis… »).101#   external_id = adresse en slug (le site n'expose aucun identifiant).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_area_sqft, parse_price, strip_accents110from .base import BaseConnector111112BASE = "https://www.immnasr.com"113114_NBSP = " "115116117def _slug(text: str) -> str:118    s = strip_accents(text.lower())119    s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")120    return s121122123def _civic(address: str) -> str:124    m = re.match(r"\s*(\d+)", address)125    return m.group(1) if m else ""126127128class ImmnasrConnector(BaseConnector):129    source_id = "immnasr"130    request_delay = 1.0131    max_images = 20132133    def fetch(self) -> list[Listing]:134        soup = BeautifulSoup(self.get(f"{BASE}/").text, "html.parser")135136        # 1) galeries : liste ordonnée de (préfixes alt, [urls])137        galleries: list[tuple[list[str], list[str]]] = []138        for car in soup.select("div.element"):139            imgs = car.select(".carousel img[src]")140            if not imgs:141                continue142            alts, urls = [], []143            for im in imgs:144                alt = (im.get("alt") or "").strip()145                if alt:146                    alts.append(alt)147                u = (im.get("src") or "").strip()148                if u.startswith("//"):149                    u = "https:" + u150                if u.startswith("http") and u not in urls:151                    urls.append(u)152            if urls:153                galleries.append((alts, urls))154155        # 2) blocs annonces : élément texte « Loyer: … » suivi de l'adresse156        elements = soup.select("div.element")157        listings: dict[str, Listing] = {}158        for i, el in enumerate(elements):159            txt = el.get_text("\n", strip=True).replace(_NBSP, " ")160            if not re.match(r"^\s*Loyer\s*:", txt):161                continue162            # l'adresse est le prochain élément texte court « …, Gatineau QC »163            address = ""164            for nxt in elements[i + 1:i + 3]:165                t = re.sub(r"\s+", " ", nxt.get_text(" ", strip=True)166                           .replace(_NBSP, " ")).strip()167                if re.search(r",\s*(Gatineau|Hull|Aylmer)\b", t, re.I) and len(t) < 90:168                    address = t169                    break170            if not address:171                continue172            ext_id = _slug(address)173            if not ext_id or ext_id in listings:174                continue175            try:176                listings[ext_id] = self._parse_block(txt, address, ext_id, galleries)177            except Exception:178                continue179180        return list(listings.values())181182    def _parse_block(self, txt: str, address: str, ext_id: str,183                     galleries: list[tuple[list[str], list[str]]]) -> Listing:184        flat = re.sub(r"[ \t]+", " ", txt)185186        def _field(label: str) -> str:187            m = re.search(label + r"\s*:?\s*\n?(.+?)(?:\n[A-ZÀ-Ü][^\n]*:|\Z)",188                          flat, re.S)189            return re.sub(r"\s+", " ", m.group(1)).strip() if m else ""190191        m = re.search(r"Loyer\s*:\s*([\d\s]+)\s*\$", flat)192        price_label = f"{m.group(1).strip()} $ / mois" if m else ""193194        # « Disponibilité: 1 / er / octobre / 2026 » (exposant sur sa propre195        # ligne) : capturer jusqu'au libellé suivant puis aplatir196        m = re.search(r"Disponibilit[ée]\s*:\s*(.*?)\s*(?:\nNombre|\nSurface|\Z)",197                      flat, re.S | re.I)198        availability = re.sub(r"\s+", " ", m.group(1)).strip(" .") if m else ""199200        m = re.search(r"chambres? à coucher\s*:\s*\n?([^\n]+)", flat, re.I)201        bedrooms_raw = re.sub(r"\s+", " ", m.group(1)).strip() if m else ""202203        m = re.search(r"Surface\s*:\s*\n?([^\n]+)", flat, re.I)204        surface_raw = re.sub(r"\s+", " ", m.group(1)).strip() if m else ""205206        m = re.search(r"(?:Prises? laveuse[^:]*)\s*:\s*\n?([^\n]+)", flat, re.I)207        washer_raw = re.sub(r"\s+", " ", m.group(1)).strip() if m else ""208209        m = re.search(r"Co[ûu]t approx\.[^:]*:\s*\n?([^\n]+)", flat, re.I)210        energy_raw = re.sub(r"\s+", " ", m.group(1)).strip() if m else ""211212        m = re.search(r"Description\s*:\s*(.+)$", flat, re.S | re.I)213        description = ""214        if m:215            description = re.sub(r"[ \t]+", " ", m.group(1)).strip()[:2500]216217        # type d'unité : maison/bungalow écrit par l'agence, sinon n chambres218        unit_type = ""219        if re.search(r"\b(bungalow|maison)\b", description, re.I):220            unit_type = "Maison"221        else:222            mb = re.match(r"(\d+)", bedrooms_raw)223            if mb:224                unit_type = normalize_unit_type(f"{mb.group(1)} chambres")225226        details: dict = {}227        if bedrooms_raw:228            mb = re.match(r"(\d+)", bedrooms_raw)229            if mb:230                details["bedrooms"] = int(mb.group(1))231            details["bedrooms_raw"] = bedrooms_raw232        if energy_raw:233            details["energy_cost"] = energy_raw234235        amenities: list[str] = []236        if washer_raw.lower().startswith("oui"):237            amenities.append("Prises laveuse et sécheuse")238239        # galerie associée par numéro civique en tête des alt240        civic = _civic(address)241        images: list[str] = []242        if civic:243            for alts, urls in galleries:244                heads = [re.match(r"[\w]+", strip_accents(a.replace("Façade", "")).strip())245                         for a in alts]246                prefixes = {re.match(r"(\d+)", a.strip()).group(1)247                            for a in alts if re.match(r"(\d+)", a.strip())}248                _ = heads249                if civic in prefixes:250                    images = urls[: self.max_images]251                    break252253        return Listing(254            source=self.source_id,255            external_id=ext_id,256            url=f"{BASE}/#{ext_id}",257            title=address,258            address=address,259            city="Gatineau",260            unit_type=unit_type,261            price=parse_price(price_label),262            price_label=price_label,263            availability=availability,264            area_sqft=parse_area_sqft(surface_raw),265            description=description,266            amenities=amenities,267            details=details,268            images=images,269        )270
Files main
Menu

Theme