SPB Git

Repository Public

gia_t.py 11.5 KB 284 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gia_t.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-2714#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/gia_t.py : connecteur GIA-T — Gestion Immobilière91#   Abitibi-Témiscamingue (gia-t.com — Rouyn-Noranda ; gère aussi pour des92#   tiers, inventaire variable). WordPress + Elementor + WP Grid Builder, tout93#   rendu serveur. Liste /location/ : cartes `article.wpgb-card` — prix94#   (« 1500$ »), adresse/titre, secteur (« Vieux Noranda », « Près du Cégep et95#   de l'Université »), catégorie (Résidentiel — le commercial est exclu),96#   « Grandeur : 5½ », extrait et photo pleine taille (lien lightbox). Fiche97#   détail /logements/<slug>/ (via cache BD) : description complète98#   (inclusions/exclusions, animaux, fumeur), chambres et salles de bain99#   (icon-box), étage (icon-list), inclusions résumées et carrousel d'images.100#   robots.txt ouvert (Disallow: vide).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://gia-t.com"113LIST_URL = f"{BASE}/location/"114115# suffixe de redimensionnement WordPress (« -768x1620.jpg » -> pleine taille)116_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)117_POST_ID_RE = re.compile(r"^wpgb-post-(\d+)$")118_PRICE_RE = re.compile(r"^\d[\d\s,]*\$")119_GRANDEUR_RE = re.compile(r"Grandeur\s*:\s*(.+)$", re.I)120121122class GiaTConnector(BaseConnector):123    source_id = "gia_t"124    request_delay = 0.6125    max_details = 30     # garde-fou fiches détail (vraies requêtes par sync)126127    def fetch(self) -> list[Listing]:128        html = self.get(LIST_URL).text129        soup = BeautifulSoup(html, "html.parser")130131        self._fetched = 0132        listings: dict[str, Listing] = {}133        for card in soup.select("article.wpgb-card"):134            try:135                self._parse_card(card, listings)136            except Exception:137                continue138        return list(listings.values())139140    # -- carte (WP Grid Builder) --------------------------------------------------------141    def _parse_card(self, card, listings: dict[str, Listing]) -> None:142        link = card.select_one('h3 a[href*="/logements/"]') \143            or card.select_one('a[href*="/logements/"]')144        if not link:145            return146        url = link["href"]147        m = re.search(r"/logements/([^/?#]+)", url)148        slug = m.group(1).strip("/") if m else ""149150        # external_id : ID du post WordPress (classe wpgb-post-<id>), sinon slug151        ext_id = slug152        for cls in card.get("class", []):153            m_id = _POST_ID_RE.match(cls)154            if m_id:155                ext_id = m_id.group(1)156                break157        if not ext_id or ext_id in listings:158            return159160        title = link.get_text(strip=True)161162        # blocs texte de la carte : prix, secteur, catégorie, « Grandeur : n½ »163        price_label = sector = category = unit_label = ""164        for blk in card.select(".wpgb-card-body div"):165            txt = re.sub(r"\s+", " ", blk.get_text(" ", strip=True))166            if not txt or blk.find("div"):167                continue168            m_g = _GRANDEUR_RE.search(txt)169            if m_g:170                unit_label = m_g.group(1).strip()171            elif _PRICE_RE.match(txt):172                price_label = txt173            elif txt in ("Résidentiel", "Commercial"):174                category = txt175            elif txt != title and len(txt) < 80:176                sector = txt177178        # exclusion : locaux commerciaux (taxonomie du site)179        if category and category != "Résidentiel":180            return181182        # extrait affiché sur la photo (sert de description de repli)183        excerpt_el = card.select_one(".wpgb-card-media-content p")184        excerpt = excerpt_el.get_text(" ", strip=True) if excerpt_el else ""185186        # photo : lien lightbox pleine taille, sinon miniature lazy-load187        images: list[str] = []188        lb = card.select_one("a.wpgb-lightbox[href]")189        if lb and lb["href"].startswith("http"):190            images.append(lb["href"])191        else:192            lazy = card.select_one("[data-wpgb-src]")193            if lazy and lazy["data-wpgb-src"].startswith("http"):194                images.append(_SIZE_SUFFIX.sub("", lazy["data-wpgb-src"]))195196        lst = Listing(197            source=self.source_id,198            external_id=ext_id,199            url=url,200            title=title,201            address=title if re.match(r"^\d+", title) else "",202            sector=sector,203            city="Rouyn-Noranda",            # tout le parc est à Rouyn-Noranda204            unit_type=normalize_unit_type(unit_label),205            price=parse_price(price_label),206            price_label=price_label,207            description=excerpt,208            images=images,209        )210211        key = hashlib.sha1(212            f"{title}|{price_label}|{unit_label}|{excerpt}"213            .encode("utf-8")).hexdigest()214        try:215            payload = self.detail(ext_id, key,216                                  lambda u=url: self._fetch_detail(u))217            self._apply_detail(lst, payload)218        except Exception:219            pass220        listings[ext_id] = lst221222    # -- fiche détail (/logements/<slug>/) ----------------------------------------------223    def _fetch_detail(self, url: str) -> dict:224        """Description complète, chambres/sdb, étage, inclusions, carrousel."""225        if self._fetched >= self.max_details:226            raise RuntimeError("budget de fiches détail atteint")227        self._fetched += 1228        html = self.get(url).text229        soup = BeautifulSoup(html, "html.parser")230        out: dict = {}231232        desc_el = soup.select_one(".elementor-widget-theme-post-content")233        if desc_el:234            txt = desc_el.get_text("\n", strip=True)235            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]236237        # icon-box : « Nombre de chambre » / « Nombre de salle de bain » / « Dimension »238        amenities: list[str] = []239        for ib in soup.select(".elementor-widget-icon-box"):240            t_el = ib.select_one(".elementor-icon-box-title")241            v_el = ib.select_one(".elementor-icon-box-description")242            t = t_el.get_text(strip=True) if t_el else ""243            v = v_el.get_text(" ", strip=True) if v_el else ""244            if not v:245                continue246            if re.search(r"chambre", t, re.I):247                amenities.append(f"{v} chambre(s)")248            elif re.search(r"salle de bain", t, re.I):249                amenities.append(f"{v} salle(s) de bain")250            elif re.search(r"dimension", t, re.I):251                amenities.append(f"Dimension : {v}")252253        # inclusions résumées : bloc texte suivant le titre « Inclusions »254        for h in soup.select(".elementor-widget-heading .elementor-heading-title"):255            if h.get_text(strip=True).lower() == "inclusions":256                widget = h.find_parent(class_="elementor-widget-heading")257                nxt = widget.find_next(class_="elementor-widget-text-editor") \258                    if widget else None259                if nxt:260                    val = nxt.get_text(" ", strip=True)261                    if val:262                        amenities.append(f"Inclus : {val}")263                break264        out["amenities"] = amenities[:15]265266        images = []267        for img in soup.select(".elementor-widget-image-carousel img[src]"):268            u = _SIZE_SUFFIX.sub("", img["src"])269            if u.startswith("http") and u not in images:270                images.append(u)271        out["images"] = images[:25]272        return out273274    def _apply_detail(self, lst: Listing, d: dict) -> None:275        """Reporte le payload (frais ou en cache) sur l'annonce."""276        if not d:277            return278        if d.get("description"):279            lst.description = d["description"]280        if d.get("amenities"):281            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))282        if d.get("images") and len(d["images"]) > len(lst.images):283            lst.images = d["images"]284
Files main
Menu

Theme