SPB Git

Repository Public

devcore.py 11.2 KB 266 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/devcore.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/devcore.py : connecteur Devcore Group (devcore.ca — 555 portes à91#   Sept-Îles + Gatineau/Maniwaki/Thurso/Val-d'Or ; siège à Gatineau).92#   WordPress + WPML. Le site n'expose pas d'unités individuelles : chaque93#   « milieu de vie » (CPT `properties`) est une page marketing par complexe.94#   L'API REST wp-json est ouverte et PRIVILÉGIÉE ici (4 requêtes par sync,95#   zéro parsing de gabarit) : /wp/v2/properties + les taxonomies96#   property_city (ville), property_type (« 1 chambre », « Studio »…) et97#   property_price (fourchettes ; « … / mois » = locatif, « $100,000… » =98#   vente). Une annonce Lou-Ka = un complexe locatif : prix seulement si la99#   page annonce « à partir de N$ » (jamais de valeur inventée), typologies100#   en commodités, fourchettes en détails. Filtres : propriétés de l'Ontario101#   (Cornwall, Ottawa, Limoges…) exclues, vente-seulement exclue, logements102#   corporatifs (moyen terme) exclus, doublons éditoriaux (pages dupliquées103#   du même complexe) dédoublonnés par ville+description. La page /location/104#   du site est périmée (fiches 404, métadonnées croisées) : non utilisée.105#   robots.txt ouvert, sitemap Yoast.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import html as htmllib110import re111112from bs4 import BeautifulSoup113114from ..schema import Listing, strip_accents115from .base import BaseConnector116117BASE = "https://devcore.ca"118API = f"{BASE}/wp-json/wp/v2"119120# villes du Québec : nom de terme property_city -> (ville Lou-Ka, secteur)121_QC_CITIES = {122    "sept-iles": ("Sept-Îles", ""),123    "gatineau": ("Gatineau", ""),124    "aylmer": ("Gatineau", "Aylmer"),125    "hull": ("Gatineau", "Hull"),126    "val d'or": ("Val-d'Or", ""),127    "val-d'or": ("Val-d'Or", ""),128    "thurso": ("Thurso", ""),129    "maniwaki": ("Maniwaki", ""),130}131132# suffixe de redimensionnement WordPress (« -1024x683.jpg » -> pleine taille)133_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)134135_FROM_PRICE_RE = re.compile(136    r"(?:à partir de|a partir de|starting at)\s*([\d\s,  ]{3,9})\s*\$"137    r"|(?:à partir de|a partir de|starting at)\s*\$\s*([\d\s,  ]{3,9})", re.I)138_AVAIL_RE = re.compile(139    r"Disponible\s+(?:pour|d[èe]s|en|le)\s+[\wà-ÿ']+(?:\s+\d{4})?", re.I)140141142def _city_key(name: str) -> str:143    return strip_accents(htmllib.unescape(name or "").strip().lower()) \144        .replace("’", "'")145146147class DevcoreConnector(BaseConnector):148    source_id = "devcore"149    request_delay = 0.6150151    # -- appels API ------------------------------------------------------------152    def _terms(self, taxonomy: str) -> dict[int, str]:153        data = self.get(f"{API}/{taxonomy}?per_page=100").json()154        return {t["id"]: htmllib.unescape(t["name"]) for t in data}155156    def fetch(self) -> list[Listing]:157        cities = self._terms("property_city")158        types = self._terms("property_type")159        prices = self._terms("property_price")160        props = self.get(f"{API}/properties?per_page=100").json()161162        candidates: list[Listing] = []163        for p in props:164            try:165                lst = self._parse_property(p, cities, types, prices)166            except Exception:167                continue168            if lst is not None:169                candidates.append(lst)170171        # dédoublonnage éditorial : le site duplique certains complexes sous172        # plusieurs slugs (« Domaine de la Baie » x3…) — clé = ville + titre173        # normalisé (suffixe « , Ville » retiré) ; on garde le plus petit id174        # WP (le plus ancien = le plus stable d'une synchro à l'autre)175        dedup: dict[str, Listing] = {}176        for lst in sorted(candidates, key=lambda l: int(l.external_id)):177            t = strip_accents(lst.title.lower())178            t = re.sub(rf",\s*{re.escape(strip_accents(lst.city.lower()))}\s*$", "", t)179            key = f"{lst.city}|{re.sub(r'[^a-z0-9]+', ' ', t).strip()}"180            if key not in dedup:181                dedup[key] = lst182        return list(dedup.values())183184    # -- une propriété (complexe locatif) ---------------------------------------185    def _parse_property(self, p: dict, cities: dict, types: dict,186                        prices: dict) -> Listing | None:187        link = p.get("link") or ""188        if "/en/" in link:                     # doublons de traduction WPML189            return None190        title = htmllib.unescape((p.get("title") or {}).get("rendered", "")).strip()191        if re.search(r"corporatif|corporate", title, re.I):192            return None                        # logement corporatif = moyen terme193194        # locatif seulement : au moins une fourchette « … / mois » ou « / month »195        price_labels = [prices[i] for i in p.get("property_price", []) if i in prices]196        monthly = [l for l in price_labels if re.search(r"/\s*(mois|month)", l, re.I)]197        if not monthly:198            return None                        # vente ou page sans données199200        # ville (taxonomie property_city) : Québec seulement201        city = sector = ""202        for i in p.get("property_city", []):203            hit = _QC_CITIES.get(_city_key(cities.get(i, "")))204            if hit:205                city, sector = hit206                break207        if not city:208            return None                        # Ontario (Cornwall, Limoges…) ou vide209210        # contenu rendu : description, images, disponibilité, « à partir de »211        content = (p.get("content") or {}).get("rendered", "")212        soup = BeautifulSoup(content, "html.parser")213214        paras = [re.sub(r"\s+", " ", el.get_text(" ", strip=True))215                 for el in soup.find_all(["p", "h2", "h3", "li"])]216        paras = [t for t in paras if len(t) > 2 and t not in ("Découvrez le projet",)]217        description = "\n".join(dict.fromkeys(paras))[:1500]218        if not description:219            return None                       # page coquille (« projet à venir »)220221        text = soup.get_text(" ", strip=True)222        price_label = ""223        m = _FROM_PRICE_RE.search(text)224        if m:225            amount = re.sub(r"[\s,  ]", "", m.group(1) or m.group(2))226            price_label = f"à partir de {amount}$"227        availability = ""228        m = _AVAIL_RE.search(text)229        if m:230            availability = re.sub(r"\s+", " ", m.group(0)).strip()231232        images: list[str] = []233        for img in soup.select("img[src]"):234            u = _SIZE_SUFFIX.sub("", img["src"].strip())235            if (u.startswith("http") and "/wp-content/uploads/" in u236                    and not u.lower().endswith(".svg") and u not in images):237                images.append(u)238239        # typologies offertes (taxonomie property_type) -> commodités affichables240        type_names = list(dict.fromkeys(241            types[i] for i in p.get("property_type", []) if i in types))242        amenities = [f"Unités : {t}" for t in type_names]243244        details: dict = {"complex": title}245        if type_names:246            details["unit_types"] = type_names247        if monthly:248            details["price_ranges"] = monthly249250        return Listing(251            source=self.source_id,252            external_id=str(p["id"]),         # id WordPress stable253            url=link,254            title=title,255            sector=sector,256            city=city,257            unit_type="",                     # complexe multi-typologies258            price=None,                       # rempli par finalize() si price_label259            price_label=price_label,260            availability=availability,261            description=description,262            amenities=amenities,263            details=details,264            images=images[:20],265        )266
Files main
Menu

Theme