SPB Git

Repository Public

remax_agences.py 14.2 KB 346 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/remax_agences.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# 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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/remax_agences.py : BACKUP RE/MAX — un connecteur par sous-agence91#92#   Les ~54 bannières RE/MAX du Québec (RE/MAX 1er Choix, du Cartier, 3000,93#   Platine…) ont chacune leur SITE PROPRE, indépendant du portail central94#   remax-quebec.com. La majorité (42) partagent la même plateforme Centris95#   (« /fr/nos-proprietes/{ville}/{adresse}/{no-centris} », rendu serveur,96#   sitemap.xml exhaustif). C'est un plan B si la clé Meilisearch centrale97#   (voir remax_quebec.py) est rotée ou bloquée.98#99#   Une CLASSE PAR AGENCE est générée dynamiquement depuis100#   data/remax_agencies.json (source_id « remax_ag_<slug> »). L'énumération101#   se fait via le sitemap (1 requête → toutes les propriétés) ; le numéro102#   Centris (dans l'URL) sert de clé de déduplication contre le flux central103#   (voir la fusion dédupliquée dans immoka/web.py) — aucun double-comptage.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import json108import os109import re110from pathlib import Path111112from .base import BaseConnector113from ..schema import PropertyListing114115REGISTRY = Path(__file__).resolve().parent.parent.parent / "data" / "remax_agencies.json"116117# Enrichissement page détail (prix/chambres/photos) : coûteux (1 requête par118# propriété). Désactivé par défaut : le flux central est déjà enrichi et ces119# fiches sont dédoublonnées contre lui. Activable par agence si le central tombe.120DETAIL_LIMIT = int(os.environ.get("IMMOKA_AGENCE_DETAIL_LIMIT", "0"))121122_PROP_RE = re.compile(r'/fr/nos-proprietes/([a-z0-9-]+)/([^<"/]+)/(\d+)', re.I)123# 2e plateforme Centris (« centris-other ») : sitemap_inscriptions.xml, URL124#   /fr/proprietes/{type-ville-secteur}/{adresse}-{no-centris}125_PROP_RE2 = re.compile(r'/fr/proprietes/([a-z0-9-]+)/([a-z0-9-]+?)-(\d{6,})(?:/)?(?=["<]|$)', re.I)126# préfixes de type de propriété (les plus longs d'abord) pour découper le 1er segment127_TYPE_PREFIXES = [128    "batisse-commerciale-bureau", "chalet-et-maison-de-campagne",129    "maison-a-paliers-multiples", "maison-de-plain-pied", "maison-a-etages",130    "propriete-a-revenus", "local-commercial", "fond-de-commerce",131    "terre-agricole", "maison-mobile", "quadruplex", "quintuplex",132    "appartement", "condominium", "fermette", "triplex", "duplex", "chalet",133    "terrain", "maison", "condo", "commerce", "bureau", "industriel", "ferme",134    "garage", "loft", "terre",135]136_IMG_RE = re.compile(137    r'https://media\.remax-quebec\.com/img/(?:fiche|www_full|www_large|v4thumbs)/[^"\'\\ ]+\.(?:jpg|jpeg|png|webp)',138    re.I)139_IMG_SIZE_RE = re.compile(r'/img/(?:fiche|www_[a-z]+|v4thumbs)/', re.I)140141142class RemaxAgenceConnector(BaseConnector):143    """Base des connecteurs de sous-agences RE/MAX (plateforme « nos-proprietes »).144145    Les sous-classes (générées plus bas) définissent `source_id`, `domain`146    et `agency_name`.147    """148149    domain: str = ""150    agency_name: str = ""151    platform: str = "nos-proprietes"   # ou "centris-other"152    request_delay = 0.4153    use_detail_cache = True154155    def fetch(self) -> list[PropertyListing]:156        urls = self._sitemap_property_urls()157        by_id: dict[str, PropertyListing] = {}158        for url in urls:159            lst = self._to_listing(url)160            if lst is not None:161                by_id[lst.external_id] = lst162        if DETAIL_LIMIT:163            self._enrich(list(by_id.values()))164        return list(by_id.values())165166    def _sitemap_property_urls(self) -> list[str]:167        """URLs de fiches du sitemap. La plateforme déclarée est essayée168        d'abord ; si elle ne livre rien, l'autre plateforme Centris est tentée169        (5 agences ont migré de « nos-proprietes » à « centris-other » à170        l'automne 2026 : leur sitemap.xml est devenu un simple index). Lève une171        exception si aucun sitemap n'est joignable — jamais de zéro silencieux."""172        order = [self.platform] + [p for p in ("nos-proprietes", "centris-other")173                                   if p != self.platform]174        fetched, last_exc = False, None175        for platform in order:176            sm = ("sitemap_inscriptions.xml" if platform == "centris-other"177                  else "sitemap.xml")178            xml = ""179            for host in (self.domain, f"www.{self.domain}"):180                try:181                    xml = self.get(f"https://{host}/{sm}").text182                    if xml:183                        break184                except Exception as exc:  # noqa: BLE001185                    last_exc = exc186                    continue187            if not xml:188                continue189            fetched = True190            rx = _PROP_RE2 if platform == "centris-other" else _PROP_RE191            seen, out = set(), []192            for m in rx.finditer(xml):193                centris = m.groups()[-1]194                if centris not in seen:195                    seen.add(centris)196                    out.append(m.group(0))197            if out:198                self.platform = platform199                return out200        if not fetched:201            raise RuntimeError(f"sitemap injoignable sur {self.domain} : {last_exc}")202        return []203204    def _to_listing(self, path: str) -> PropertyListing | None:205        if self.platform == "centris-other":206            return self._to_listing_centris(path)207        m = _PROP_RE.search(path)208        if not m:209            return None210        city_slug, addr_slug, centris = m.group(1), m.group(2), m.group(3)211        url = f"https://{self.domain}{path if path.startswith('/') else '/' + path}"212        city, sector = _split_city(city_slug)213        return PropertyListing(214            source=self.source_id, external_id=centris, url=url,215            title=_deslug(addr_slug), address=_deslug(addr_slug),216            city=city, sector=sector, mls=centris, broker_name=self.agency_name,217        )218219    def _to_listing_centris(self, url: str) -> PropertyListing | None:220        m = _PROP_RE2.search(url)221        if not m:222            return None223        seg1, addr_slug, centris = m.group(1), m.group(2), m.group(3)224        ptype, rest = _split_type(seg1)      # type + « ville-secteur »225        city, sector = _split_city(rest)226        return PropertyListing(227            source=self.source_id, external_id=centris,228            url=url if url.startswith("http") else f"https://{self.domain}{url}",229            title=_deslug(addr_slug), address=_deslug(addr_slug),230            property_type=ptype, city=city, sector=sector,231            mls=centris, broker_name=self.agency_name,232        )233234    # -- enrichissement optionnel (prix/chambres/photos) ----------------------235    def _enrich(self, listings: list[PropertyListing]) -> None:236        from .. import db237        con = db.connect()238        budget = DETAIL_LIMIT239        for lst in listings:240            cached = db.get_cached_detail(con, self.source_id, lst.external_id, "d")241            if cached is None:242                if budget <= 0:243                    continue244                cached = self._scrape_detail(lst.url)245                db.put_cached_detail(con, self.source_id, lst.external_id, "d", cached)246                budget -= 1247            _apply(lst, cached)248        con.close()249250    def _scrape_detail(self, url: str) -> dict:251        try:252            html = self.get(url).text253        except Exception:254            return {}255        out: dict = {}256        seen, imgs = set(), []257        for u in _IMG_RE.findall(html):258            full = _IMG_SIZE_RE.sub("/img/www_full/", u)259            fn = full.rsplit("/", 1)[-1]260            if fn not in seen and "nophoto" not in full:261                seen.add(fn)262                imgs.append(full)263        if imgs:264            out["images"] = imgs265        import html as _h266        t = _h.unescape(re.sub(r"<[^>]+>", " ", html))267        t = re.sub(r"\s+", " ", t)268        mp = re.search(r"([\d  ]{4,})\s*\$", t)269        if mp:270            out["price_label"] = mp.group(0).strip()271        mb = re.search(r"(\d+)\s*chambre", t, re.I)272        if mb:273            out["bedrooms"] = int(mb.group(1))274        ms = re.search(r"(\d+)\s*salle[s]?\s*de\s*bain", t, re.I)275        if ms:276            out["bathrooms"] = int(ms.group(1))277        return out278279280def _apply(lst: PropertyListing, d: dict) -> None:281    if d.get("images"):282        lst.images = d["images"]283    if d.get("price_label") and not lst.price_label:284        lst.price_label = d["price_label"]285    for f in ("bedrooms", "bathrooms"):286        if d.get(f) is not None and getattr(lst, f, None) is None:287            setattr(lst, f, d[f])288289290def _deslug(s: str) -> str:291    return re.sub(r"\s+", " ", s.replace("-", " ")).strip().title()292293294def _split_type(seg1: str) -> tuple[str, str]:295    """« propriete-a-revenus-laval-laval-des-rapides » -> (type, « laval-... »)."""296    for pref in _TYPE_PREFIXES:297        if seg1.startswith(pref):298            return _deslug(pref), seg1[len(pref):].lstrip("-")299    # pas de type reconnu : tout est considéré comme localisation300    return "", seg1301302303# quelques villes composées fréquentes dans les slugs de la plateforme304def _split_city(slug: str) -> tuple[str, str]:305    parts = slug.split("-")306    city = parts[0].title() if parts else ""307    fixes = {"Quebec": "Québec", "Levis": "Lévis", "Montreal": "Montréal",308             "Trois": "Trois-Rivières", "St": "Saint"}309    city = fixes.get(city, city)310    sector = _deslug("-".join(parts[1:])) if len(parts) > 1 else ""311    return city, sector312313314# ---------------------------------------------------------------------------315# Génération d'une classe par sous-agence (plateforme « nos-proprietes »)316# ---------------------------------------------------------------------------317318def _slugify_id(banner: str) -> str:319    return "remax_ag_" + re.sub(r"[^a-z0-9]+", "_", banner.replace("remax-", "")).strip("_")320321322def _load_agencies() -> list[dict]:323    try:324        return json.loads(REGISTRY.read_text(encoding="utf-8"))325    except Exception:326        return []327328329# Crée dynamiquement RemaxAg<...> pour chaque agence dotée d'un site propre,330# sur l'une des deux plateformes Centris reconnues (nos-proprietes / centris-other).331# `"disabled": true` dans le registre = site mort/migré/doublon (voir "note").332for _ag in _load_agencies():333    _plat = _ag.get("platform")334    if _ag.get("disabled"):335        continue336    if _plat not in ("nos-proprietes", "centris-other") or not _ag.get("domain"):337        continue338    _dom = re.sub(r"^https?://", "", _ag["domain"]).rstrip("/")339    _sid = _slugify_id(_ag["banner"])340    _name = "RE/MAX " + _ag["banner"].replace("remax-", "").replace("-", " ").title()341    globals()[_sid.upper()] = type(342        "".join(p.title() for p in _sid.split("_")),343        (RemaxAgenceConnector,),344        {"source_id": _sid, "domain": _dom, "agency_name": _name, "platform": _plat},345    )346
Files main
Menu

Theme