SPB Git

Repository Public

garic.py 13.8 KB 327 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/garic.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-09-2214#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/garic.py : connecteur Garic Gestion Immobilière (garic.ca)91#   Gestionnaire de Gatineau (Hull, Vieux-Gatineau, secteur est). WordPress92#   (Oxygen) : la grille filtrable de /a-louer/ se nourrit d'un endpoint93#   admin-ajax MAISON `garic_get_properties` qui renvoie TOUT l'inventaire94#   en JSON structuré : ID, adresse (post_title), prix/mois, type (« 4 ½ »),95#   chambres, salles de bain, superficie, disponibilité, image, URL de la96#   fiche et géocodage complet (lat/lng + quartier OpenStreetMap). Le nonce97#   de sécurité est lu sur la page /a-louer/ à chaque sync.98#   L'unique propriété d'OTTAWA est exclue (périmètre Québec). La fiche99#   /a-louer/<slug> (cache BD) ajoute description, inclusions, « À100#   proximité », scores de mobilité ET la galerie complète (liens lightbox101#   pleine grandeur — le JSON admin-ajax n'expose qu'une seule image).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price111from .base import BaseConnector112113BASE = "https://garic.ca"114LIST_URL = f"{BASE}/a-louer/"115AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"116117_NONCE_RE = re.compile(r'nonce"\s*:\s*"([0-9a-f]+)"')118# « 74, Rue Saint-Paul, Vieux-Gatineau, Gatineau, Outaouais, … » -> secteur119_GENERIC_SEG = re.compile(120    r"(?i)^(gatineau|outaouais|quebec|québec|canada|j\d[a-z]\s?\d[a-z]\d|"121    r"\(secteur\).*|urban agglomeration.*|papineau|les collines-de-l'outaouais)$"122    r"|^(rue|avenue|av\.?|boul\.?|boulevard|chemin|mont[ée]e|impasse|place)\b")123# municipalités distinctes de la couronne parfois présentes dans le géocodage124_MUNICIPALITIES = {"thurso": "Thurso", "chelsea": "Chelsea",125                   "cantley": "Cantley", "val-des-monts": "Val-des-Monts"}126127128class GaricConnector(BaseConnector):129    source_id = "garic"130    request_delay = 1.0131    max_details = 60     # tout l'inventaire (~45) tient dans un sync132    max_images = 12133134    def __init__(self) -> None:135        super().__init__()136        # Depuis le retour du vhost (panne 2026-09-04 → 2026-09-22), garic.ca137        # sert le certificat du VPS de l'agence (CN=vps1010.mediaconnection.ca)138        # au lieu du sien : hostname mismatch. Contenu public — on tolère.139        self.session.verify = False  # noqa: S501140141    # -- fiche détail ------------------------------------------------------------142    def _fetch_detail(self, url: str) -> dict:143        self._fetched += 1144        soup = BeautifulSoup(self.get(url).text, "html.parser")145        out: dict = {"amenities": [], "nearby": [], "scores": {}}146147        def _section(title: str) -> list[str]:148            """Bloc `div.meta-info` : « <h3>Inclusions</h3> 🍳 Cuisinière<br/>… »149            — une entrée par segment séparé par <br/>."""150            h = soup.find("h3", string=re.compile(rf"^\s*{title}\s*$"))151            if not (h and h.parent):152                return []153            items = [re.sub(r"\s+", " ", t).strip()154                     for t in h.parent.get_text("\n", strip=True).split("\n")]155            return [t for t in items156                    if t and t != title and 2 < len(t) < 90][:15]157158        out["amenities"] = _section("Inclusions")159        out["nearby"] = _section("À proximité")160161        h = soup.find("h3", string=re.compile(r"^\s*Description\s*$"))162        if h and h.parent:163            txt = h.parent.get_text("\n", strip=True)164            txt = re.sub(r"^Description\s*\n?", "", txt)165            txt = re.sub(r"\n{2,}", "\n", txt)166            out["description"] = txt.strip()[:2000]167168        text = soup.get_text(" ", strip=True)169        for label, key in (("Walk Score", "walk"), ("Transit Score", "transit"),170                           ("Bike Score", "bike")):171            m = re.search(rf"{label}\s*®?\s*(\d{{1,3}})", text)172            if m:173                out["scores"][key] = int(m.group(1))174175        # galerie complète : liens lightbox pleine grandeur vers les uploads176        images: list[str] = []177        for a in soup.select('a[href*="/wp-content/uploads/"]'):178            u = (a.get("href") or "").split("?")[0]179            if not re.search(r"\.(?:jpe?g|png|webp)$", u, re.I):180                continue181            if re.search(r"logo|cropped-|favicon|icon", u, re.I):182                continue183            u = re.sub(r"-\d{2,4}x\d{2,4}(?=\.\w+$)", "", u)184            if u.startswith("http") and u not in images:185                images.append(u)186        out["images"] = images[: self.max_images]187        return out188189    # -- fetch -----------------------------------------------------------------190    def fetch(self) -> list[Listing]:191        # 1) nonce de la grille (rafraîchi à chaque sync)192        page = self.get(LIST_URL).text193        m = _NONCE_RE.search(page)194        if not m:195            # page parquée / gabarit remanié : erreur FRANCHE plutôt qu'un196            # « found=0 ok » silencieux (la panne vhost 09-04→09-22 a dépublié197            # l'inventaire pendant 18 jours sans alerter la supervision)198            raise RuntimeError("garic : nonce admin-ajax introuvable sur "199                               f"{LIST_URL} — page parquée ou gabarit remanié")200        # 2) inventaire JSON complet (POST via la session -> rejouable en test)201        r = self.session.post(202            AJAX_URL,203            data={"action": "garic_get_properties", "security": m.group(1)},204            timeout=self.timeout)205        r.raise_for_status()206        data = (r.json() or {}).get("data") or []207208        self._fetched = 0209        listings: dict[str, Listing] = {}210        for rec in data:211            try:212                self._parse_record(rec, listings)213            except Exception:214                continue215        return list(listings.values())216217    def _parse_record(self, rec: dict, listings: dict[str, Listing]) -> None:218        ville = (rec.get("ville") or "").strip()219        if ville.lower() != "gatineau":220            return   # Ottawa (Ontario) : hors périmètre221        ext = str(rec.get("ID") or "")222        url = (rec.get("url") or "").split("?")[0]223        if not ext or not url or ext in listings:224            return225226        title = re.sub(r"\s+", " ", rec.get("post_title") or "").strip()227        price_amt = (rec.get("prix_montant") or "").strip()228        per = (rec.get("prix_par") or "mois").strip()229        price_label = f"{price_amt}$ par {per}" if price_amt else ""230231        # superficie déclarée (souvent vide) — champ « superficie » brut232        area = None233        sup = (rec.get("superficie") or "").strip()234        if sup:235            try:236                v = float(re.sub(r"[^\d.]", "", sup))237                if 80 <= v <= 20000:238                    area = v239            except ValueError:240                area = None241242        # géocodage publié : lat/lng + quartier OSM (« Vieux-Gatineau »)243        lat = lng = None244        sector = ""245        emp = rec.get("emplacement") or {}246        markers = emp.get("markers") or []247        if markers:248            lat, lng = markers[0].get("lat"), markers[0].get("lng")249            geos = markers[0].get("geocode") or []250            disp = ""251            if geos:252                disp = (geos[0].get("display_name")253                        or (geos[0].get("properties") or {})254                        .get("display_name") or "")255            segs = [s.strip() for s in disp.split(",")]256            for seg in segs[2:5]:257                if seg and not _GENERIC_SEG.match(seg) \258                        and not re.match(r"^\d", seg):259                    sector = seg260                    break261        # le géocodage révèle parfois une municipalité distincte (Thurso…) :262        # elle devient la ville, sans secteur263        city = "Gatineau"264        if sector.lower() in _MUNICIPALITIES:265            city, sector = _MUNICIPALITIES[sector.lower()], ""266        if lat is None:267            lat, lng = emp.get("lat"), emp.get("lng")268269        images: list[str] = []270        img = rec.get("image") or {}271        for k in ("full", "large", "thumbnail"):272            u = img.get(k) or ""273            if u.startswith("http"):274                images.append(re.sub(r"-\d{2,4}x\d{2,4}(?=\.\w+$)", "", u))275                break276277        details: dict = {}278        sdb = (rec.get("pieces_salles_de_bain") or "").strip()279        if sdb.isdigit():280            details["bathrooms"] = int(sdb)281282        # fiche détail (description, inclusions, proximité, scores, galerie)283        # clé versionnée « v2 » : force une revisite unique des fiches mises284        # en cache avant l'ajout de la galerie285        payload: dict = {}286        key = hashlib.sha1(f"v2|{title}|{price_label}|{rec.get('availability')}"287                           .encode("utf-8")).hexdigest()[:20]288        if self._fetched < self.max_details:289            try:290                payload = self.detail(ext, key,291                                      lambda u=url: self._fetch_detail(u))292            except Exception:293                payload = {}294        desc_bits = []295        if payload.get("description"):296            desc_bits.append(payload["description"])297        if payload.get("nearby"):298            desc_bits.append("À proximité : " + ", ".join(payload["nearby"]))299        for k, v in (payload.get("scores") or {}).items():300            details[f"{k}_score"] = v301        # galerie complète de la fiche (sinon l'image unique du JSON)302        gallery = [u for u in (payload.get("images") or [])303                   if isinstance(u, str) and u.startswith("http")]304        if gallery:305            images = gallery306307        listings[ext] = Listing(308            source=self.source_id,309            external_id=ext,310            url=url,311            title=title,312            address=title,          # le titre EST l'adresse civique313            sector=sector,314            city=city,315            unit_type=normalize_unit_type(rec.get("type") or ""),316            price=parse_price(price_label),317            price_label=price_label,318            availability=(rec.get("availability") or "").strip(),319            area_sqft=area,320            description="\n".join(desc_bits)[:2200],321            amenities=list(payload.get("amenities") or []),322            details=details,323            lat=float(lat) if lat is not None else None,324            lng=float(lng) if lng is not None else None,325            images=images[: self.max_images],326        )327
Files main
Menu

Theme