SPB Git

Repository Public

gestipro.py 13.3 KB 339 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestipro.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/gestipro.py : connecteur Gestipro (gestipro.info)91#   Site WordPress (thème Houzez) : liste paginée /a-louer/ avec fiches92#   « propriete ». Une annonce par unité; pages détail pour la galerie photos.93#   Stationnements, locaux commerciaux et rangements exclus.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import hashlib98import json99import re100101from bs4 import BeautifulSoup102103from ..schema import (Listing, infer_city, normalize_unit_type,104                      parse_area_sqft, strip_accents)105from .base import BaseConnector106107BASE = "https://gestipro.info"108LIST_URL = f"{BASE}/a-louer/"109110IMG_RE = re.compile(111    r"https://gestipro\.info/wp-content/uploads/[^\"'\\\s\)]+"112    r"\.(?:jpg|jpeg|png|webp)", re.I)113IMG_NOISE_RE = re.compile(r"logo|favicon|icon|cluster|-\d+x\d+\.", re.I)114EXCLUDE_RE = re.compile(115    r"stationnement|parking|garage|rangement|entrepos|commercial|bureau|local",116    re.I)117118119def _parse_price(text: str) -> float | None:120    """Gère « 2,427$/mois » (virgule = séparateur de milliers)."""121    if not text:122        return None123    s = text.replace(" ", " ").replace(" ", " ")124    s = re.sub(r"(\d),(\d{3})", r"\1\2", s)125    m = re.search(r"(\d[\d\s]*(?:[.,]\d{2})?)\s*\$", s)126    if not m:127        return None128    try:129        val = float(m.group(1).replace(" ", "").replace(",", "."))130    except ValueError:131        return None132    return val if 100 <= val <= 20000 else None133134135def _pets_value(raw: str) -> str | None:136    """Mappe la valeur « Animaux toléré » de la fiche vers oui/non/conditions."""137    k = strip_accents((raw or "").lower())138    if not k:139        return None140    if re.search(r"refus|interdit|non admis|non accepte|aucun|pas d", k):141        return "non"142    if re.search(r"seulement|condition|petit|approbation|restriction", k):143        return "conditions"144    if re.search(r"oui|accepte|admis|autorise|tolere|bienvenu", k):145        return "oui"146    return None147148149class GestiproConnector(BaseConnector):150    source_id = "gestipro"151    request_delay = 0.5152    max_list_pages = 15          # garde-fou pagination153    max_details = 150            # garde-fou fiches détail154155    def fetch(self) -> list[Listing]:156        # 1) Pagination : /a-louer/ puis /a-louer/page/N/157        first = self.get(LIST_URL).text158        pages = [first]159        nums = [int(n) for n in re.findall(r"/a-louer/page/(\d+)/", first)]160        last = min(max(nums) if nums else 1, self.max_list_pages)161        for n in range(2, last + 1):162            try:163                pages.append(self.get(f"{LIST_URL}page/{n}/").text)164            except Exception:165                continue166167        # 2) Cartes Houzez168        listings: dict[str, Listing] = {}169        for page in pages:170            soup = BeautifulSoup(page, "html.parser")171            for card in soup.select("div.item-listing-wrap[data-hz-id]"):172                try:173                    lst = self._parse_card(card)174                except Exception:175                    continue176                if lst and lst.external_id not in listings:177                    listings[lst.external_id] = lst178179        # 3) Fiches détail (cache BD) : galerie complète, description longue,180        #    superficie, animaux, frais inclus, coordonnées GPS181        self._fetched = 0182        for lst in listings.values():183            card_key = hashlib.sha1(184                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"185                .encode("utf-8")).hexdigest()186            try:187                payload = self.detail(lst.external_id, card_key,188                                      lambda u=lst.url: self._fetch_detail(u))189            except Exception:190                continue191            self._apply_detail(lst, payload)192193        return list(listings.values())194195    def _parse_card(self, card) -> Listing | None:196        ext_id = card.get("data-hz-id", "").strip()197        title_a = card.select_one(".item-title a")198        if not ext_id or not title_a:199            return None200        url = title_a.get("href", "")201        title = title_a.get_text(" ", strip=True)202203        type_el = card.select_one(".h-type span")204        unit_raw = type_el.get_text(" ", strip=True) if type_el else ""205206        # Exclusions : stationnement, commercial, rangement...207        if EXCLUDE_RE.search(f"{title} {unit_raw} {url}"):208            return None209210        addr_el = card.select_one(".item-address span") or \211            card.select_one(".item-address")212        addr_raw = addr_el.get_text(" ", strip=True) if addr_el else ""213        # « 7170 Boulevard Cloutier, Québec, QC, Canada, Charlesbourg, Québec »214        parts = [p.strip() for p in addr_raw.split(",") if p.strip()]215        address = parts[0] if parts else ""216        sector = ""217        for p in reversed(parts[1:]):218            if p not in ("Québec", "QC", "Canada", "Quebec", "Lévis", "Levis"):219                sector = p220                break221        city = "Lévis" if re.search(r"l[ée]vis", addr_raw, re.I) else "Québec"222223        price_el = card.select_one(".item-price")224        price_label = price_el.get_text(" ", strip=True) if price_el else ""225226        avail = ", ".join(a.get_text(" ", strip=True)227                          for a in card.select(".label-status")[:2])228229        img_el = card.select_one(".listing-thumb img")230        img = ""231        if img_el:232            img = img_el.get("data-src") or img_el.get("src") or ""233            if img.startswith("data:"):234                img = img_el.get("data-src") or ""235236        return Listing(237            source=self.source_id,238            external_id=ext_id,239            url=url,240            title=title,241            address=address,242            sector=sector,243            city=infer_city(sector, default=city),244            unit_type=normalize_unit_type(unit_raw),245            price=_parse_price(price_label),246            price_label=price_label,247            availability=avail,248            images=[img] if img else [],249        )250251    def _fetch_detail(self, url: str) -> dict:252        """Fiche Houzez : description complète, caractéristiques, bloc253        « Détails » (superficie, animaux, frais, disponibilité) et géoloc254        (JSON-LD schema.org Place). Retour JSON-sérialisable (cache BD)."""255        if self._fetched >= self.max_details:256            raise RuntimeError("budget de fiches détail atteint")257        self._fetched += 1258        html = self.get(url).text259        soup = BeautifulSoup(html, "html.parser")260        out: dict = {}261262        # description complète (repli : og:description)263        desc_el = soup.select_one("#property-description-wrap")264        if desc_el:265            txt = desc_el.get_text("\n", strip=True)266            txt = re.sub(r"^Description\n", "", txt)267            txt = txt.replace("Read More", " ").replace("Read Less", " ")268            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1200]269        else:270            og = soup.find("meta", attrs={"property": "og:description"}) or \271                soup.find("meta", attrs={"name": "description"})272            if og and og.get("content"):273                out["description"] = og["content"].strip()[:600]274275        # Commodités (bloc « Caractéristiques » Houzez)276        amen = [a.get_text(" ", strip=True)277                for a in soup.select("#property-features-wrap li a")]278        out["amenities"] = [a for a in amen if a][:20]279280        # Bloc « Détails » : paires libellé/valeur structurées281        pairs: dict[str, str] = {}282        for li in soup.select("#property-detail-wrap .list-lined-item"):283            st, sp = li.find("strong"), li.find("span")284            if st and sp:285                lab = strip_accents(st.get_text(" ", strip=True).lower())286                pairs[lab] = sp.get_text(" ", strip=True)287        for lab, val in pairs.items():288            if "dimension" in lab or "superficie" in lab:289                out["area_label"] = val                 # ex. « 456 pi² »290            elif "animaux" in lab:291                out["pets_raw"] = val                   # ex. « Chat seulement »292            elif "frais" in lab:293                out["frais"] = val                      # ex. « Eau chaude et wifi inclus »294            elif "disponibilit" in lab:295                out["availability"] = val296297        # Géolocalisation : JSON-LD schema.org (Place -> geo)298        for sc in soup.find_all("script", type="application/ld+json"):299            try:300                data = json.loads(sc.string or "")301            except Exception:302                continue303            geo = data.get("geo") if isinstance(data, dict) else None304            if isinstance(geo, dict):305                try:306                    out["lat"] = float(geo.get("latitude"))307                    out["lng"] = float(geo.get("longitude"))308                except (TypeError, ValueError):309                    pass310                break311312        imgs = [u for u in dict.fromkeys(IMG_RE.findall(html))313                if not IMG_NOISE_RE.search(u)]314        out["images"] = imgs[:25]315        return out316317    def _apply_detail(self, lst: Listing, d: dict) -> None:318        """Reporte le payload (frais/cache) sur l'annonce."""319        if not d:320            return321        if d.get("description"):322            lst.description = d["description"]323        amenities = list(d.get("amenities") or [])324        if d.get("frais"):325            amenities.append(f"Frais et charge : {d['frais']}")326        if amenities:327            lst.amenities = amenities328        if d.get("availability"):329            lst.availability = d["availability"]330        if d.get("area_label"):331            lst.area_sqft = parse_area_sqft(d["area_label"])332        pets = _pets_value(d.get("pets_raw", ""))333        if pets:334            lst.pets = pets335        if d.get("lat") is not None and d.get("lng") is not None:336            lst.lat, lst.lng = d["lat"], d["lng"]337        if d.get("images"):338            lst.images = d["images"]339
Files main
Menu

Theme