SPB Git

Repository Public

immeubles_ouellet.py 13.3 KB 310 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immeubles_ouellet.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/immeubles_ouellet.py : connecteur Les Immeubles Vianney Ouellet91#   & Fils (immeublesouellet.com — Rimouski, 300+ unités, 40+ ans). Site PHP92#   artisanal (hébergeur PQM.net). La page /location/ n'affiche RIEN en GET ;93#   le moteur de recherche (POST quartier/grandeur/prix « tous ») renvoie la94#   grille complète : un bloc par immeuble (adresse en h4, photo PQM, lien95#   detail.php?id=N) avec une rangée par unité « 4 1/2 : Complet » ou96#   « 4 1/2 : 1 x libre à partir du 2025-12-15 ». Le connecteur ne visite que97#   les immeubles ayant au moins une rangée non « Complet » et émet une98#   annonce par bloc d'unité libre de la fiche detail.php?id=N : prix propre99#   au bloc (« 995$ », « --- » quand loué), description, services inclus,100#   ameublement, date de disponibilité, galerie. Parc quasi plein en région :101#   0-2 annonces est un état normal. Les textes saisis en base par l'agence102#   sont en UTF-8 doublement encodé (« Meublé ») alors que le gabarit est103#   sain : correction chaîne par chaîne. robots.txt : 404 (= tout permis).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, parse_price, strip_accents112from .base import BaseConnector113114BASE = "https://immeublesouellet.com"115SEARCH_URL = f"{BASE}/location/index.php"116SEARCH_ALL = {"quartier": "0", "grandeur": "0", "prix": "0",117              "rechercher": "Recherche"}118119# rangée de la grille : « 4 1/2 : Complet », « 4 1/2 : 1 x libre à partir … »120_ROW_RE = re.compile(r"^\s*(.+?)\s*:\s*(.+?)\s*$")121_COMPLET_RE = re.compile(r"^complet\b", re.I)122# entête d'un bloc d'unité sur la fiche : type puis ligne prix (« 995$ »/« --- »)123_TYPE_RE = re.compile(r"^(\d\s*1/2|Studio|Loft|Maison|Commercial)$", re.I)124_PRICE_LINE_RE = re.compile(r"^(-{2,}|\d[\d\s]*\$(?:\s*/\s*mois)?)$")125126127def _fix_mojibake(s: str) -> str:128    """Textes de la base servis en UTF-8 doublement encodé : corrige si besoin."""129    if "Ã" not in s and "â€" not in s:130        return s131    for enc in ("cp1252", "latin-1"):132        try:133            return s.encode(enc).decode("utf-8")134        except (UnicodeEncodeError, UnicodeDecodeError):135            continue136    return s137138139def _slug(label: str) -> str:140    return re.sub(r"[^a-z0-9]+", "-", strip_accents(label.lower())).strip("-")141142143class ImmeublesOuelletConnector(BaseConnector):144    source_id = "immeubles_ouellet"145    request_delay = 0.6146    max_details = 15     # garde-fou fiches immeuble (vraies requêtes par sync)147148    def fetch(self) -> list[Listing]:149        # la grille complète n'est servie que par la recherche POST « tous »150        resp = self.session.post(SEARCH_URL, data=SEARCH_ALL,151                                 timeout=self.timeout)152        resp.raise_for_status()153        soup = BeautifulSoup(resp.text, "html.parser")154155        self._fetched = 0156        listings: dict[str, Listing] = {}157        for item in soup.select("li.list__item"):158            try:159                self._parse_building(item, listings)160            except Exception:161                continue162        return list(listings.values())163164    # -- bloc immeuble (résultats de recherche) ------------------------------------165    def _parse_building(self, item, listings: dict[str, Listing]) -> None:166        link = item.select_one('a[href*="detail.php?id="]')167        if not link:168            return169        m = re.search(r"detail\.php\?id=(\d+)", link["href"])170        if not m:171            return172        bid = m.group(1)173        h4 = item.select_one("h4")174        address = _fix_mojibake(h4.get_text(" ", strip=True)) if h4 else ""175        if re.search(r"commercial", address, re.I):176            return177178        # rangées « type : statut » — l'immeuble n'est visité que si au moins179        # une unité n'est pas « Complet »180        free_rows = []181        for li in item.select("ul li"):182            rm = _ROW_RE.match(_fix_mojibake(li.get_text(" ", strip=True)))183            if rm and not _COMPLET_RE.match(rm.group(2)) \184                    and not re.search(r"commercial", rm.group(1), re.I):185                free_rows.append((rm.group(1), rm.group(2)))186        if not free_rows:187            return188189        img = item.select_one("img[src]")190        thumb = img["src"] if img and img["src"].startswith("http") else ""191        detail_url = f"{BASE}/location/detail.php?id={bid}"192        try:193            payload = self._fetch_detail(detail_url)194        except Exception:195            payload = {}196197        # blocs d'unités LIBRES de la fiche (prix + date propres au bloc)198        blocks = [b for b in payload.get("units", [])199                  if not _COMPLET_RE.match(b.get("availability", "Complet"))]200        if blocks:201            per_type: dict[str, int] = {}202            for b in blocks:203                slug = _slug(b["label"])204                per_type[slug] = per_type.get(slug, 0) + 1205                ext_id = f"{bid}-{slug}-{per_type[slug]}"206                if ext_id in listings:207                    continue208                listings[ext_id] = Listing(209                    source=self.source_id,210                    external_id=ext_id,211                    url=detail_url,212                    title=f"{b['label']} — {address}".strip(" —"),213                    address=address,214                    city="Rimouski",          # tout le parc est à Rimouski215                    unit_type=normalize_unit_type(b["label"]),216                    price=parse_price(b.get("price_label", "")),217                    price_label=b.get("price_label", ""),218                    availability=b.get("availability", ""),219                    description=b.get("description", ""),220                    amenities=b.get("amenities", []),221                    furnished=b.get("furnished"),222                    images=payload.get("images") or ([thumb] if thumb else []),223                )224            return225226        # repli : fiche indisponible -> annonces depuis les rangées de la grille227        per_type: dict[str, int] = {}228        for unit_label, status in free_rows:229            slug = _slug(unit_label)230            per_type[slug] = per_type.get(slug, 0) + 1231            ext_id = f"{bid}-{slug}-{per_type[slug]}"232            if ext_id in listings:233                continue234            listings[ext_id] = Listing(235                source=self.source_id,236                external_id=ext_id,237                url=detail_url,238                title=f"{unit_label} — {address}".strip(" —"),239                address=address,240                city="Rimouski",241                unit_type=normalize_unit_type(unit_label),242                price=parse_price(status),243                price_label=status if "$" in status else "",244                availability=status,245                images=[thumb] if thumb else [],246            )247248    # -- fiche immeuble (detail.php?id=N) --------------------------------------------249    def _fetch_detail(self, url: str) -> dict:250        """Blocs d'unités (type, prix, description, services, ameublement,251        disponibilité) parsés ligne à ligne + galerie de l'immeuble."""252        if self._fetched >= self.max_details:253            raise RuntimeError("budget de fiches immeuble atteint")254        self._fetched += 1255        soup = BeautifulSoup(self.get(url).text, "html.parser")256        out: dict = {"units": [], "images": []}257258        out["images"] = [im["src"] for im in soup.select("img[src]")259                         if im["src"].startswith("http")][:20]260261        lines = [_fix_mojibake(ln) for ln in262                 soup.get_text("\n", strip=True).split("\n")]263        i, n = 0, len(lines)264        while i < n:265            # entête de bloc : ligne type suivie de la ligne prix (« --- »/« 995$ »)266            if not (_TYPE_RE.match(lines[i]) and i + 1 < n267                    and _PRICE_LINE_RE.match(lines[i + 1])):268                i += 1269                continue270            unit = {"label": lines[i]}271            if "$" in lines[i + 1]:272                unit["price_label"] = lines[i + 1]273            i += 2274            section = None275            while i < n and not (_TYPE_RE.match(lines[i]) and i + 1 < n276                                 and _PRICE_LINE_RE.match(lines[i + 1])):277                ln = lines[i]278                if ln == "Description":279                    section = "description"280                elif ln == "Services inclus":281                    section = "amenities"282                elif ln == "Ameublement":283                    section = "furnished"284                elif ln.startswith("Disponibilit"):285                    section = "availability"286                elif ln.startswith("418 724-9132"):   # pied de page : fin287                    break288                elif section == "description":289                    unit["description"] = (unit.get("description", "") +290                                           "\n" + ln).strip()[:800]291                elif section == "amenities":292                    a = re.sub(r"^-\s*", "", ln).strip()293                    if a and not re.match(r"^aucun service", a, re.I):294                        unit.setdefault("amenities", []).append(a)295                elif section == "furnished":296                    raw = strip_accents(ln.strip().lower())297                    if raw.startswith("non"):298                        unit["furnished"] = False299                    elif "meuble" in raw:300                        unit["furnished"] = True301                    section = None302                elif section == "availability":303                    unit["availability"] = ln.strip()304                    section = None305                i += 1306            if _TYPE_RE.match(unit["label"]) and "commercial" not in \307                    unit["label"].lower():308                out["units"].append(unit)309        return out310
Files main
Menu

Theme