SPB Git

Repository Public

sgiq.py 15.9 KB 368 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/sgiq.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/sgiq.py : connecteur SGIQ — Société de Gestion Immobilière du91#   Québec (gestionimmobilierequebec.com). Liste paginée /immeubles?page=N92#   (rendu serveur) + fiches /fiche/<id> pour images, description, commodités93#   (avec cache BD self.detail) + endpoint JSON getMarkers pour lat/lng.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import hashlib98import re99100from bs4 import BeautifulSoup101102from ..schema import Listing, infer_city, normalize_unit_type, parse_price, strip_accents103from .base import BaseConnector104105BASE = "https://gestionimmobilierequebec.com"106LIST_URL = f"{BASE}/immeubles"107# Endpoint AJAX du site (recherche/carte) : POST a=getMarkers&form=dispo=108# retourne [titre, "lat, ", "lng", popup, popup, "3-1-2", …] pour CHAQUE fiche.109MARKERS_URL = f"{BASE}/mod/act_p/ImmeubleAct.php"110111# Secteurs connus de l'agglomération de Québec (localité affichée après la112# virgule dans le titre) — tout le reste (hors Québec/Lévis) est exclu.113_QC_SECTORS = {114    "quebec", "ville de quebec", "sainte-foy", "ste-foy", "sillery", "limoilou",115    "beauport", "charlesbourg", "vanier", "loretteville", "val-belair",116    "l'ancienne-lorette", "ancienne-lorette", "saint-augustin",117    "saint-augustin-de-desmaures", "cap-rouge", "saint-roch", "st-roch",118    "saint-sauveur", "st-sauveur", "montcalm", "duberger", "les saules",119    "neufchatel", "lebourgneuf", "lac-saint-charles", "saint-emile", "st-emile",120    "wendake", "cite-limoilou", "la cite-limoilou",121}122123_IMG_RE = re.compile(124    r"//gestionimmobilierequebec\.com/mod/file/ImmeubleSliderFile/"125    r"[0-9a-f]+\.(?:jpg|jpeg|png|webp)", re.I)126127128class _FetchBudget(Exception):129    """Plafond de requêtes fiche atteint pour cette synchronisation."""130131132class SGIQConnector(BaseConnector):133    source_id = "sgiq"134    request_delay = 0.5135    max_pages = 15               # garde-fou de pagination136    max_details = 250            # garde-fou de fetch des fiches137    max_fetch_per_sync = 160     # vraies requêtes fiche par sync (cache exclu)138139    # -- helpers ---------------------------------------------------------------140    @staticmethod141    def _city_from_locality(locality: str) -> str | None:142        """Ville normalisée, ou None si hors agglomération Québec/Lévis."""143        key = strip_accents(locality.strip().lower())144        if not key:145            return "Québec"146        if infer_city(locality, default="") == "Lévis":147            return "Lévis"148        if key in _QC_SECTORS:149            return "Québec"150        return None151152    def _fetch_markers(self) -> dict[str, tuple[float, float, str]]:153        """Coordonnées + type par fiche via l'endpoint carte (1 seul POST).154155        `form=dispo=` désactive le filtre de disponibilité : les 147 fiches156        sont retournées. Format : [html, "lat, ", "lng", popup, popup, type].157        """158        markers: dict[str, tuple[float, float, str]] = {}159        try:160            resp = self.session.post(161                MARKERS_URL, data={"a": "getMarkers", "form": "dispo="},162                timeout=self.timeout)163            resp.raise_for_status()164            for row in resp.json():165                if not isinstance(row, list) or len(row) < 6:166                    continue167                m = re.search(r"/fiche/(\d+)", str(row[3]))168                if not m:169                    continue170                try:171                    lat = float(str(row[1]).strip(" ,"))172                    lng = float(str(row[2]).strip(" ,"))173                except (TypeError, ValueError):174                    continue175                typ = str(row[5] or "").replace("-1-2", " 1/2")  # "3-1-2" -> "3 1/2"176                markers[m.group(1)] = (lat, lng, typ)177        except Exception:178            pass179        return markers180181    # -- fetch -----------------------------------------------------------------182    def fetch(self) -> list[Listing]:183        listings: dict[str, Listing] = {}184185        # 1) Pagination de la liste (?page=N ; total dans input#total_page)186        total_pages = 1187        page = 1188        while page <= total_pages and page <= self.max_pages:189            try:190                html = self.get(LIST_URL if page == 1 else f"{LIST_URL}?page={page}").text191            except Exception:192                break193            soup = BeautifulSoup(html, "html.parser")194            tp = soup.select_one("input#total_page")195            if tp and (tp.get("value") or "").isdigit():196                total_pages = int(tp["value"])197198            for card in soup.select("div.preview-immeuble a[href*='/fiche/']"):199                m = re.search(r"/fiche/(\d+)", card.get("href", ""))200                if not m:201                    continue202                ext_id = m.group(1)203                if ext_id in listings:204                    continue205                title = (card.get("title") or "").strip()206                if not title:207                    img = card.select_one("img[alt]")208                    title = (img.get("alt") or "").strip() if img else ""209                # Formats observés : "925-1A rue Liénard, Québec",210                # "920-1F Av. Myrand, Québec, QC G1V 2V9", "830 avenue Turnbull"211                tokens = [t.strip() for t in title.split(",") if t.strip()]212                locality = ""213                for tok in tokens[1:]:214                    tok_clean = re.sub(r"\bQC\b|\bG\d[A-Z]\s?\d[A-Z]\d\b", "", tok).strip()215                    if tok_clean:216                        locality = tok_clean217                        break218                address = tokens[0] if tokens else title219                city = self._city_from_locality(locality)220                if city is None:          # hors Québec / Lévis221                    continue222                cat_el = card.select_one("div.text p")223                category = cat_el.get_text(strip=True) if cat_el else ""224                if re.search(r"stationnement|commercial|rangement|garage",225                             category, re.I):226                    continue227                price_el = card.select_one(".background-price strong")228                price_label = f"{price_el.get_text(strip=True)} $ /Mois" if price_el else ""229                sector = locality if strip_accents(locality.lower()) not in ("quebec",) else ""230                listings[ext_id] = Listing(231                    source=self.source_id,232                    external_id=ext_id,233                    url=f"{BASE}/fiche/{ext_id}",234                    title=title or f"Logement {ext_id}",235                    address=address,236                    sector=sector,237                    city=city,238                    price=parse_price(price_label),239                    price_label=price_label,240                    description=category,241                )242            page += 1243244        # 2) lat/lng + type structurés via l'endpoint carte (1 seul POST)245        markers = self._fetch_markers()246        for ext_id, (lat, lng, typ) in markers.items():247            lst = listings.get(ext_id)248            if lst:249                lst.lat, lst.lng = lat, lng250                if typ:251                    lst.unit_type = normalize_unit_type(typ)252253        # 3) Fiches détaillées : images, description, commodités — via le254        #    cache BD self.detail() : la fiche n'est re-téléchargée que si la255        #    carte liste (titre/prix/catégorie) a changé.256        fetched = 0257        for i, lst in enumerate(listings.values()):258            if i >= self.max_details:259                break260            key = hashlib.sha1(261                f"{lst.title}|{lst.price_label}|{lst.description}"262                .encode("utf-8")).hexdigest()263264            def _fetch(url=lst.url):265                nonlocal fetched266                if fetched >= self.max_fetch_per_sync:267                    raise _FetchBudget(url)   # ni requête, ni mise en cache vide268                fetched += 1269                return self._fetch_detail(url)270271            try:272                payload = self.detail(lst.external_id, key, _fetch)273            except Exception:274                payload = {}275            if payload:276                self._apply_detail(lst, payload)277278        return list(listings.values())279280    # -- fiche détail ----------------------------------------------------------281    def _fetch_detail(self, url: str) -> dict:282        """Télécharge une fiche et en extrait le payload brut (cacheable)."""283        detail = self.get(url).text284        dsoup = BeautifulSoup(detail, "html.parser")285286        images = ["https:" + u for u in dict.fromkeys(_IMG_RE.findall(detail))][:30]287288        # description : bloc gauche de « Description et remarques » (sans les289        # items « Chauffé : Oui » qui vont dans les commodités)290        desc_el = dsoup.select_one(291            "div.description div.block-left > div.text:not(.description-item)") \292            or dsoup.select_one("div.text.description-content")293        desc = ""294        if desc_el:295            desc = re.sub(r"\s+", " ", desc_el.get_text(" ", strip=True))296        if not desc:  # repli : tout le corps de la fiche297            body = dsoup.get_text(" ", strip=True)298            m = re.search(r"Description et remarques\s*(.+?)(?:Vous pourriez aussi aimer|Siège social)",299                          body)300            desc = re.sub(r"\s+", " ", m.group(1)) if m else ""301302        # commodités : "Chauffé : Non", "1 chambre", "Chiens permis", ...303        amenities: list[str] = []304        for el in dsoup.select("div.description-item div, div.block-right div.icon div"):305            t = el.get_text(" ", strip=True)306            if t and len(t) < 60 and t not in amenities:307                amenities.append(t)308309        # icône « animal » structurée (filtre Chiens acceptés du site)310        pets_icon = ""311        icon = dsoup.select_one("div.block-right div.icon img[src*='icon_animal']")312        if icon:313            div = icon.find_next_sibling("div")314            pets_icon = div.get_text(" ", strip=True) if div else ""315316        return {"images": images, "description": desc[:800],317                "amenities": amenities, "pets_icon": pets_icon}318319    def _apply_detail(self, lst: Listing, payload: dict) -> None:320        """Applique le payload d'une fiche (frais ou depuis le cache BD)."""321        desc = payload.get("description") or ""322        if payload.get("images"):323            lst.images = payload["images"]324        if desc:325            lst.description = desc326        if payload.get("amenities"):327            lst.amenities = payload["amenities"]328329        # animaux : icône dédiée du site ("Chiens permis")330        pi = strip_accents((payload.get("pets_icon") or "").lower())331        if pi:332            lst.pets = "non" if re.search(r"\bnon\b|refus|interdit", pi) else "oui"333334        # type d'unité depuis la description ("3 1/2 LUMINEUX ...") si les335        # marqueurs ne l'ont pas fourni336        if not lst.unit_type:337            unit = normalize_unit_type(desc)338            if unit and unit != desc.strip():339                lst.unit_type = unit340341        # secteur depuis la description ("QUARTIER SAINTE-FOY", "SECTEUR LIMOILOU")342        if not lst.sector:343            m = re.search(r"(?:QUARTIER|SECTEUR)\s+(?:DE\s+|DU\s+)?"344                          r"([A-ZÀ-Ü][A-ZÀ-Üa-zà-ü']+(?:-[A-ZÀ-Üa-zà-ü']+)*)",345                          desc)346            if m:347                lst.sector = m.group(1).strip(" -").title()348                lst.city = infer_city(lst.sector, default=lst.city)349350        # disponibilité si mentionnée ("DISPONIBLE PRÉSENTEMENT", "PRÉSENTEMENT351        # DISPONIBLE", "DISPONIBLE EN JUILLET", "LIBRE 1ER JUILLET"...)352        mois = (r"JAN[A-ZÀ-Ü]*|F[ÉE]V[A-ZÀ-Ü]*|MARS|AVR[A-ZÀ-Ü]*|MAI|JUIN|"353                r"JUIL[A-ZÀ-Ü]*|AO[ÛU]T|SEPT[A-ZÀ-Ü]*|OCT[A-ZÀ-Ü]*|"354                r"NOV[A-ZÀ-Ü]*|D[ÉE]C[A-ZÀ-Ü]*")355        m = re.search(rf"(?:LIBRE|DISPONIBLE|DISPONIBILIT[ÉE])\s*:?\s*"356                      rf"(?:D[ÈE]S\s+|LE\s+|EN\s+)?"357                      rf"(MAINTENANT|PR[ÉE]SENTEMENT|IMM[ÉE]DIATEMENT|"358                      rf"\d+\s*(?:ER|E)?\s*[A-ZÀ-Ü]{{3,10}}(?:\s+20\d\d)?|"359                      rf"(?:{mois})(?:\s+20\d\d)?)", desc, re.I)360        if not m:361            m = re.search(r"(MAINTENANT|PR[ÉE]SENTEMENT|IMM[ÉE]DIATEMENT)\s+"362                          r"DISPONIBLE", desc, re.I)363        if not m:364            m = re.search(r"PRISE DE POSSESSION\s*:?\s*(FLEXIBLE\s*)?"365                          r"(\([^)]{0,50}\)|[A-ZÀ-Ü0-9][^.<–—-]{0,40})?", desc, re.I)366        if m:367            lst.availability = re.sub(r"\s+", " ", m.group(0)).strip().capitalize()368
Files main
Menu

Theme