SPB Git

Repository Public

matinale.py 12.5 KB 302 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/matinale.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-1814#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/matinale.py : connecteur Gestion Matinale (gestionmatinale.com)91#   ~44 apparts + maisons à Sherbrooke, Magog et Windsor. WordPress +92#   WooCommerce : chaque logement offert est un « produit » — archives93#   /a-louer/appartements-logements/ (paginée, 16/page) et /a-louer/maison/.94#   Cartes li.product : titre « 1330 KING OUEST, SHERBROOKE, J1J 2B6 (Août) »95#   (adresse, ville, code postal + disponibilité entre parenthèses), prix96#   WooCommerce, type d'unité dans la taxonomie (classe product_cat-5-1-2) et97#   photo. external_id = ID WordPress (classe post-<id>).98#   ATTENTION robots.txt : « Crawl-Delay: 20 » -> request_delay de 20 s,99#   respecté aussi pour les fiches produit : chaque fiche (galerie complète100#   + description) n'est visitée qu'à l'apparition de l'annonce ou à un101#   changement de prix/dispo (cache BD `detail`), budget max_details par sync.102#   La première synchronisation complète prend ~15 min (43 fiches x 20 s) ;103#   les suivantes retombent à 4-5 requêtes.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, parse_price113from .base import BaseConnector114115# pictogrammes décoratifs des descriptions WooCommerce (✨🛏🛁…) -> retirés116_EMOJI_RE = re.compile("[\u2190-\u2BFF\u2600-\u27BF\uFE0F"117                       "\U0001F000-\U0001FAFF]")118119BASE = "https://gestionmatinale.com"120ARCHIVES = [121    ("/a-louer/appartements-logements/", ""),122    ("/a-louer/maison/", "Maison"),123]124125_POST_ID_RE = re.compile(r"\bpost-(\d+)\b")126_CAT_TYPE_RE = re.compile(r"\bproduct_cat-(\d)-1-2\b")127_PARENS_RE = re.compile(r"\(([^)]+)\)\s*$")128_POSTAL_RE = re.compile(r"\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b")129_CITY_RE = re.compile(r"\b(SHERBROOKE|MAGOG|WINDSOR|EAST ANGUS|ROCK FOREST|"130                      r"FLEURIMONT|LENNOXVILLE|ORFORD|STUKELY-SUD|"131                      r"SAINTE-CATHERINE-DE-HATLEY)\b", re.I)132133134class MatinaleConnector(BaseConnector):135    source_id = "matinale"136    request_delay = 20.0   # robots.txt : Crawl-Delay: 20 — respecté137    max_pages = 6          # garde-fou par archive (3 pages observées)138    max_details = 50       # fiches produit visitées par sync (cache BD)139    max_images = 16140141    # -- fiche produit : galerie complète + description WooCommerce -------------142    def _fetch_detail(self, url: str) -> dict:143        self._fetched += 1144        soup = BeautifulSoup(self.get(url).text, "html.parser")145        out: dict = {}146        images: list[str] = []147        for a in soup.select(".woocommerce-product-gallery a[href]"):148            u = str(a.get("href") or "").split("?")[0]149            if re.search(r"\.(?:jpe?g|png|webp)$", u, re.I) \150                    and u.startswith("http") and u not in images:151                images.append(u)152        if images:153            out["images"] = images[: self.max_images]154        panel = soup.select_one(".woocommerce-Tabs-panel--description, "155                                "#tab-description")156        if panel:157            txt = panel.get_text("\n", strip=True)158            txt = re.sub(r"^Description\s*\n?", "", txt)159            txt = _EMOJI_RE.sub("", txt)160            txt = re.sub(r"[ \t]{2,}", " ", txt)161            txt = "\n".join(line.strip() for line in txt.split("\n"))162            txt = re.sub(r"\n{2,}", "\n", txt).strip()163            if txt:164                out["description"] = txt[:2500]165        return out166167    def fetch(self) -> list[Listing]:168        self._fetched = 0169        listings: dict[str, Listing] = {}170        for path, forced_type in ARCHIVES:171            for page in range(1, self.max_pages + 1):172                url = (f"{BASE}{path}" if page == 1173                       else f"{BASE}{path}page/{page}/")174                try:175                    html = self.get(url).text176                except Exception:177                    break178                soup = BeautifulSoup(html, "html.parser")179                cards = soup.select("li.product")180                if not cards:181                    break182                for card in cards:183                    try:184                        lst = self._parse_card(card, forced_type)185                    except Exception:186                        continue187                    if lst and lst.external_id not in listings:188                        listings[lst.external_id] = lst189                # dernière page atteinte ?190                nums = [int(a.get_text(strip=True))191                        for a in soup.select("a.page-numbers, span.page-numbers")192                        if a.get_text(strip=True).isdigit()]193                if not nums or page >= max(nums):194                    break195        return list(listings.values())196197    # -- carte produit ----------------------------------------------------------------198    def _parse_card(self, card, forced_type: str) -> Listing | None:199        link = card.select_one("a.woocommerce-loop-product__link[href]")200        title_el = card.select_one("h2.woocommerce-loop-product__title")201        if not (link and title_el):202            return None203        url = link["href"]204        title = re.sub(r"\s+", " ", title_el.get_text(" ", strip=True)).strip()205206        # exclusions : espaces non résidentiels vendus comme produits207        if re.search(r"stationnement|garage|rangement|entrep[oô]t", title, re.I):208            return None209210        classes = " ".join(card.get("class") or [])211        m = _POST_ID_RE.search(classes)212        ext_id = m.group(1) if m else url.rstrip("/").rsplit("/", 1)[-1]213214        # type d'unité : taxonomie WooCommerce (product_cat-5-1-2) ou archive215        unit_type = forced_type216        mt = _CAT_TYPE_RE.search(classes)217        if mt:218            n = int(mt.group(1))219            unit_type = "6½+" if n >= 6 else f"{n}½"220        elif re.search(r"product_cat-mais|product_cat-chalet", classes) \221                or re.search(r"\bmaison\b|\bchalet\b", title, re.I):222            unit_type = "Maison"223224        # disponibilité entre parenthèses du titre : « (Août) », « (Vacant) »,225        # « (Janvier 2027) » — certains titres la placent au milieu226        availability = ""227        mp = re.search(r"\(([^)]{2,25})\)", title)228        if mp:229            availability = mp.group(1).strip()230231        # adresse / ville / code postal depuis le titre232        clean = re.sub(r"\s*\([^)]*\)", "", title).strip(" ,")233        city = ""234        mc = _CITY_RE.search(clean)235        if mc:236            city = mc.group(1).title()237            if city in ("Rock Forest", "Fleurimont", "Lennoxville"):238                city = "Sherbrooke"239        postal = ""240        mpost = _POSTAL_RE.search(clean.upper())241        if mpost:242            postal = mpost.group(0)243        address = clean244245        # prix WooCommerce (promo : <ins> = prix courant)246        price = None247        price_label = ""248        price_el = card.select_one("span.price")249        if price_el:250            price_label = re.sub(r"\s+", " ",251                                 price_el.get_text(" ", strip=True)).strip()252            ins = price_el.select_one("ins .woocommerce-Price-amount")253            amount = ins or price_el.select_one(".woocommerce-Price-amount")254            if amount:255                price = parse_price(re.sub(256                    r"(\d),(\d{3})", r"\1\2",257                    amount.get_text(" ", strip=True)))258259        # photo (chargée en différé : data-src)260        images = []261        img = card.select_one("img")262        if img:263            src = (img.get("data-src") or img.get("src") or "").strip()264            src = re.sub(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", "",265                         src, flags=re.I)266            if src.startswith("http"):267                images.append(src)268269        # fiche produit (cache BD) : galerie complète + description —270        # revisitée seulement si le prix ou la disponibilité change271        payload: dict = {}272        key = hashlib.sha1(f"{title}|{price_label}|{availability}"273                           .encode("utf-8")).hexdigest()[:20]274        if self._fetched < self.max_details:275            try:276                payload = self.detail(str(ext_id), key,277                                      lambda u=url: self._fetch_detail(u))278            except Exception:279                payload = {}280        gallery = [u for u in (payload.get("images") or [])281                   if isinstance(u, str) and u.startswith("http")]282        if gallery:283            images = gallery284285        details = {"postal_code": postal} if postal else {}286        return Listing(287            source=self.source_id,288            external_id=str(ext_id),289            url=url,290            title=title,291            address=address,292            sector="",293            city=city or "Sherbrooke",294            unit_type=unit_type,295            price=price,296            price_label=price_label,297            availability=availability,298            description=payload.get("description") or "",299            details=details,300            images=images,301        )302
Files main
Menu

Theme