SPB Git

Repository Public

mkar.py 11.3 KB 281 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/mkar.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/mkar.py : connecteur Gestion Immobilière MKAR91#   (gestionimmobilieremkar.ca — Saguenay : Jonquière/Chicoutimi/La Baie, Alma,92#   Chambord ; gère aussi pour des tiers). WordPress + thème maison blitzWP93#   (CPT property), tout rendu serveur. Archive /proprietes-gestion-immobiliere-94#   mkar/ : cartes `article.archive__item--property` — badge de disponibilité95#   (« Disponible »/« Complet »), type (« 4½ », « Chambre », « Loft »),96#   catégorie (Duplex, Colocation…), adresse + municipalité, photos. Fiche97#   /propriete/<slug>/ (via cache BD) : inclusions (chambres, salles de bain,98#   chauffage, wifi…), conditions de location (animaux, fumeur) et galerie.99#   Aucun prix publié nulle part -> price = None (rien d'inventé).100#   robots.txt Yoast standard (admin seulement), sitemap.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, strip_accents110from .base import BaseConnector111112BASE = "https://gestionimmobilieremkar.ca"113LIST_URL = f"{BASE}/proprietes-gestion-immobiliere-mkar/"114115# municipalités du filtre du site ; celles de gauche = secteurs de Saguenay116_SAGUENAY = {"jonquiere", "chicoutimi", "la baie", "lac kenogami"}117_MUNICIPALITIES = _SAGUENAY | {"alma", "chambord"}118119120def _split_locality(raw: str) -> tuple[str, str]:121    """« 1745 Rue Haziel - 1745 Chicoutimi » -> (adresse, municipalité)."""122    txt = re.sub(r"\s+", " ", raw).strip()123    for name in sorted(_MUNICIPALITIES, key=len, reverse=True):124        m = re.search(rf"\s({name})\s*$", strip_accents(txt.lower()))125        if m:126            return txt[: m.start()].strip(" -,"), txt[m.start():].strip()127    return txt, ""128129130class MkarConnector(BaseConnector):131    source_id = "mkar"132    request_delay = 0.6133    max_details = 25     # garde-fou fiches détail (vraies requêtes par sync)134135    def fetch(self) -> list[Listing]:136        html = self.get(LIST_URL).text137        soup = BeautifulSoup(html, "html.parser")138139        self._fetched = 0140        listings: dict[str, Listing] = {}141        for card in soup.select("article.archive__item--property"):142            try:143                self._parse_card(card, listings)144            except Exception:145                continue146        return list(listings.values())147148    # -- carte (article.archive__item--property) --------------------------------------149    def _parse_card(self, card, listings: dict[str, Listing]) -> None:150        link = card.select_one('a.item__link[href*="/propriete/"]') \151            or card.select_one('a[href*="/propriete/"]')152        if not link:153            return154        url = link["href"]155        m = re.search(r"/propriete/([^/?#]+)", url)156        if not m:157            return158        ext_id = m.group(1)159        if not ext_id or ext_id in listings:160            return161162        # badge de disponibilité : on ne garde que les unités « Disponible »163        avail_el = card.select_one(".item__availability")164        availability = avail_el.get_text(strip=True) if avail_el else ""165        if availability and not re.search(r"disponible", availability, re.I):166            return167168        type_el = card.select_one(".item__room")169        unit_label = type_el.get_text(strip=True) if type_el else ""170        cat_el = card.select_one(".item__category")171        category = cat_el.get_text(strip=True) if cat_el else ""172173        # garages et espaces non résidentiels : exclus174        if re.search(r"garage|entrep[oô]t|commercial|bureau|local",175                     f"{unit_label} {category}", re.I):176            return177178        addr_el = card.select_one(".item__addresse")179        address, locality = _split_locality(180            addr_el.get_text(" ", strip=True) if addr_el else "")181182        loc_key = strip_accents(locality.lower())183        if loc_key in _SAGUENAY:184            city, sector = "Saguenay", locality185        else:186            city, sector = locality, ""187188        images: list[str] = []189        for img in card.select(".item__image img[src]"):190            u = img["src"]191            if u.startswith("http") and u not in images:192                images.append(u)193194        title = " — ".join(p for p in (category, address) if p) or unit_label195196        lst = Listing(197            source=self.source_id,198            external_id=ext_id,199            url=url,200            title=title,201            address=address,202            sector=sector,203            city=city,204            unit_type=normalize_unit_type(unit_label),205            price=None,                       # aucun prix publié par MKAR206            price_label="",207            availability=availability,208            amenities=[category] if category else [],209            images=images[:15],210        )211212        key = hashlib.sha1(213            f"{unit_label}|{category}|{address}|{availability}"214            .encode("utf-8")).hexdigest()215        try:216            payload = self.detail(ext_id, key,217                                  lambda u=url: self._fetch_detail(u))218            self._apply_detail(lst, payload)219        except Exception:220            pass221        listings[ext_id] = lst222223    # -- fiche détail (/propriete/<slug>/) ---------------------------------------------224    def _fetch_detail(self, url: str) -> dict:225        """Inclusions, conditions de location (animaux) et galerie complète."""226        if self._fetched >= self.max_details:227            raise RuntimeError("budget de fiches détail atteint")228        self._fetched += 1229        html = self.get(url).text230        soup = BeautifulSoup(html, "html.parser")231        out: dict = {}232233        # « Inclusions » : items structurés (1 Chambre, 1 Salle de bain, Wifi…)234        inclusions = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))235                      for li in soup.select(".property__inclusions .inclusions__item h3")]236        out["amenities"] = [t for t in inclusions if t][:20]237238        # « Conditions de location » : <strong> successifs (bail, animaux, fumeur)239        conditions = [re.sub(r"\s+", " ", s.get_text(" ", strip=True))240                      for s in soup.select(".property__conditions strong")]241        conditions = [t for t in conditions if t]242        if conditions:243            out["description"] = ("Conditions de location : "244                                  + " ; ".join(conditions))[:1200]245            joined = " ".join(conditions).lower()246            if re.search(r"animaux ne sont pas permis", joined):247                out["pets"] = "non"248249        # GPS : carte du thème (attributs data-lat / data-lng)250        map_el = soup.select_one(".property__map .map[data-lat][data-lng]")251        if map_el:252            try:253                out["lat"] = float(map_el["data-lat"])254                out["lng"] = float(map_el["data-lng"])255            except (TypeError, ValueError):256                pass257258        # galerie (swiper) : photos pleine taille, icônes SVG exclues259        images: list[str] = []260        for img in soup.select(".property img[src*='/wp-content/uploads/']"):261            u = img["src"]262            if u.startswith("http") and not u.endswith(".svg") and u not in images:263                images.append(u)264        out["images"] = images[:25]265        return out266267    def _apply_detail(self, lst: Listing, d: dict) -> None:268        """Reporte le payload (frais ou en cache) sur l'annonce."""269        if not d:270            return271        if d.get("description"):272            lst.description = d["description"]273        if d.get("amenities"):274            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))275        if d.get("pets"):276            lst.pets = d["pets"]277        if d.get("lat") is not None and d.get("lng") is not None:278            lst.lat, lst.lng = d["lat"], d["lng"]279        if d.get("images") and len(d["images"]) > len(lst.images):280            lst.images = d["images"]281
Files main
Menu

Theme