SPB Git

Repository Public

gio.py 14.6 KB 359 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gio.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/gio.py : connecteur Gestion Immobilière de l'Outaouais (gioinc.ca)91#   Gestionnaire du Plateau à Gatineau (boul. du Plateau, av. des Oliviers…).92#   WordPress/Elementor : la page /a-louer/ rend côté serveur une boucle93#   Elementor (e-loop-item-<postid>, CPT « proprietes ») avec prix, ville,94#   adresse, nombre de pièces et lien vers la fiche /proprietes/<slug>/.95#   La fiche détail (via cache BD) ajoute : titre, mention « Toutes les96#   charges comprises », type (Résidentiel/Commercial — le commercial est97#   exclu), salles de bain, description bilingue et le bloc « Aperçu »98#   structuré (stationnement, durée du bail, animaux, meublé, électroménagers,99#   taille) ainsi que la galerie de photos quand elle existe.100#   robots.txt : Crawl-delay 3 (respecté via request_delay) et Disallow /*?101#   — le connecteur ne visite que des URLs sans chaîne de requête.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price, strip_accents111from .base import BaseConnector112113BASE = "https://gioinc.ca"114LIST_URL = f"{BASE}/a-louer/"115116_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)117# image générique du site (og:image), jamais une photo du logement118_GENERIC_IMG = re.compile(r"GIO-1200x628|logo", re.I)119_BG_URL_RE = re.compile(r"url\((['\"]?)(https?://[^)'\"]+)\1\)")120121# libellés du bloc « Aperçu » : une valeur qui est elle-même un libellé122# signifie que le champ précédent est vide sur la fiche123_APERCU_LABELS = re.compile(124    r"^(Services inclus|Stationnement inclus|Durée du bail|Date d’emménagement|"125    r"Animaux acceptés|L’unité d’habitation|Taille \(pieds carrés\)|Meublé|"126    r"Électroménagers|Air conditionné|Espace extérieur privé|Fumeurs acceptés|"127    r"Immeuble|Commodités dans l’immeuble)$")128129130def _oui_non(raw: str) -> bool | None:131    k = strip_accents((raw or "").strip().lower())132    if k.startswith("oui") or k in ("yes",):133        return True134    if k.startswith("non") or k in ("no",):135        return False136    return None137138139class GioConnector(BaseConnector):140    source_id = "gio"141    request_delay = 3.0     # robots.txt : Crawl-delay 3142    max_details = 40        # garde-fou fiches détail (vraies requêtes)143144    def fetch(self) -> list[Listing]:145        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")146        listings: dict[str, Listing] = {}147        for card in soup.select('div[data-elementor-type="loop-item"]'):148            try:149                self._parse_card(card, listings)150            except Exception:151                continue152153        # fiches détail (cache BD) : description, aperçu structuré, photos154        self._fetched = 0155        for lst in listings.values():156            key = hashlib.sha1(157                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"158                .encode("utf-8")).hexdigest()159            try:160                payload = self.detail(lst.external_id, key,161                                      lambda u=lst.url: self._fetch_detail(u))162            except Exception:163                continue164            self._apply_detail(lst, payload)165166        # le commercial n'est identifiable que sur la fiche -> filtre final167        return [l for l in listings.values()168                if l.details.get("property_kind") != "Commercial"]169170    # -- carte de la boucle Elementor ------------------------------------------171    def _parse_card(self, card, listings: dict[str, Listing]) -> None:172        link = card.select_one('a.elementor-button[href*="/proprietes/"]')173        if not link:174            return175        url = link["href"]176        # id de billet WordPress stable : classe « post-2320 »177        ext_id = ""178        for cls in card.get("class", []):179            m = re.match(r"^post-(\d+)$", cls)180            if m:181                ext_id = m.group(1)182        if not ext_id or ext_id in listings:183            return184185        status = link.get_text(strip=True)          # « Disponible »186        if re.search(r"lou[ée]", status, re.I):187            return188189        # widgets texte dans l'ordre : prix, ville, adresse, « Pièces: n »190        price_label = city = address = rooms_label = ""191        for w in card.select(".elementor-widget-text-editor .elementor-widget-container"):192            txt = re.sub(r"\s+", " ", w.get_text(" ", strip=True))193            if not txt:194                continue195            if "$" in txt and not price_label:196                price_label = txt197            elif re.search(r"pi[eè]ces?\s*:", txt, re.I):198                rooms_label = txt199            elif not city:200                city = txt201            elif not address:202                address = txt203204        unit_type = ""205        m = re.search(r"pi[eè]ces?\s*:\s*(\d+)", rooms_label, re.I)206        rooms = int(m.group(1)) if m else None207        # « Pièces » du site = nombre de chambres (671-102 « 1 chambre » -> 1)208        if rooms:209            unit_type = normalize_unit_type(f"{rooms} chambres")210211        details: dict = {}212        if rooms:213            details["bedrooms"] = rooms214215        listings[ext_id] = Listing(216            source=self.source_id,217            external_id=ext_id,218            url=url,219            title=address or url.rstrip("/").rsplit("/", 1)[-1],220            address=f"{address}, {city}" if address and city else address,221            city=city or "Gatineau",222            unit_type=unit_type,223            price=parse_price(price_label),224            price_label=price_label,225            availability=status,226            details=details,227        )228229    # -- fiche détail ------------------------------------------------------------230    def _fetch_detail(self, url: str) -> dict:231        if self._fetched >= self.max_details:232            raise RuntimeError("budget de fiches détail atteint")233        self._fetched += 1234        html = self.get(url).text235        soup = BeautifulSoup(html, "html.parser")236        out: dict = {}237238        h1 = soup.find("h1")239        if h1:240            out["title"] = h1.get_text(" ", strip=True)241242        text = soup.get_text("\n", strip=True)243244        # adresse complète avec code postal : « 671 boulevard du Plateau,245        # Gatineau, QC  J9J 4K5 (Afficher sur la carte) »246        m = re.search(r"\n([^\n]+,\s*[^\n]+?,\s*QC[^\n(]*)", text)247        if m:248            out["address"] = re.sub(r"\s+", " ", m.group(1)).strip()249250        # « Résidentiel » ou « Commercial » + « Pièces: n | Salles de bain: n »251        m = re.search(r"\b(Résidentiel|Commercial)\b", text)252        if m:253            out["kind"] = m.group(1)254        m = re.search(r"Salles? de bain\s*:?\s*(\d+)", text)255        if m:256            out["bathrooms"] = int(m.group(1))257        if re.search(r"Toutes les charges comprises", text, re.I):258            out["all_inclusive"] = True259260        # description : entre « Description » et « Aperçu »261        m = re.search(r"\nDescription\n(.*?)\nAperçu\n", text, re.S)262        if m:263            desc = re.sub(r"[ \t]+", " ", m.group(1)).strip()264            out["description"] = desc[:2500]265266        # bloc « Aperçu » : paires libellé/valeur rendues en lignes successives267        m = re.search(r"\nAperçu\n(.*?)\n(?:Êtes-vous|Comment pouvons)", text, re.S)268        apercu = m.group(1) if m else ""269        for label, key in [270                (r"Animaux acceptés", "pets_raw"),271                (r"Meublé", "furnished_raw"),272                (r"Fumeurs acceptés", "smoking_raw"),273                (r"Stationnement inclus", "parking_raw"),274                (r"Durée du bail", "lease_raw"),275                (r"Électroménagers", "appliances_raw"),276                (r"Services inclus", "services_raw"),277                (r"Taille \(pieds carrés\)", "area_raw")]:278            mm = re.search(label + r"\n([^\n]+)", apercu)279            if mm and not _APERCU_LABELS.match(mm.group(1).strip()):280                out[key] = mm.group(1).strip()281282        # galerie : diaporama de la fiche (div.slide, background-image) +283        # images du contenu ; jamais l'og:image générique ni les icônes284        images: list[str] = []285286        def _add(u: str) -> None:287            if not u.startswith("http"):288                u = BASE + u289            if _GENERIC_IMG.search(u) or u.lower().endswith(".svg"):290                return291            if "/wp-content/uploads/" not in u:292                return293            u = _SIZE_SUFFIX.sub("", u)294            if u not in images:295                images.append(u)296297        for div in soup.select("div.slide div[style], [style*='background']"):298            m_bg = _BG_URL_RE.search(div.get("style", ""))299            if m_bg:300                _add(m_bg.group(2))301        for im in soup.select('img[src*="/wp-content/uploads/"]'):302            _add(im["src"])303        out["images"] = images[:30]304        return out305306    def _apply_detail(self, lst: Listing, d: dict) -> None:307        if not d:308            return309        if d.get("title"):310            lst.title = d["title"]311        if d.get("address"):312            lst.address = d["address"]313        if d.get("kind"):314            lst.details["property_kind"] = d["kind"]315        if d.get("bathrooms"):316            lst.details["bathrooms"] = d["bathrooms"]317        if d.get("description"):318            lst.description = d["description"]319        # le nombre de chambres écrit par l'agence (titre ou en-tête de la320        # description) prime sur le compteur « Pièces » de la carte, parfois321        # en décalage (ex. fiche 3 chambres avec Pièces: 2)322        head = f"{lst.title} | {(lst.description or '')[:80]}"323        m = re.search(r"(\d+)\s*chambres?\b", head, re.I)324        if m:325            lst.unit_type = normalize_unit_type(f"{m.group(1)} chambres")326            lst.details["bedrooms"] = int(m.group(1))327        if d.get("images"):328            lst.images = d["images"]329        pets = _oui_non(d.get("pets_raw", ""))330        if pets is not None:331            lst.pets = "oui" if pets else "non"332        furn = _oui_non(d.get("furnished_raw", ""))333        if furn is not None:334            lst.furnished = furn335        smoking = _oui_non(d.get("smoking_raw", ""))336        if smoking is not None:337            lst.details["smoking"] = smoking338        if d.get("parking_raw"):339            lst.details["parking"] = {"raw": d["parking_raw"]}340        if d.get("lease_raw"):341            lst.details["lease"] = d["lease_raw"]342        amen: list[str] = []343        if d.get("all_inclusive"):344            amen.append("Toutes les charges comprises")345        if d.get("services_raw"):346            amen.append(f"Services inclus : {d['services_raw']}")347        if _oui_non(d.get("appliances_raw", "")):348            amen.append("Électroménagers inclus")349        if amen:350            lst.amenities = list(dict.fromkeys(lst.amenities + amen))351        m = re.match(r"^([\d\s,.]+)$", d.get("area_raw", "") or "")352        if m:353            try:354                area = float(m.group(1).replace(" ", "").replace(",", "."))355                if 80 <= area <= 20000:356                    lst.area_sqft = area357            except ValueError:358                pass359
Files main
Menu

Theme