SPB Git

Repository Public

exp_quebec.py 20.5 KB 484 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/exp_quebec.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1613# Last Modified    : 2026-08-1914#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/exp_quebec.py : eXp Realty Québec (expquebec.com) — toute la province.91#92#   L'API cliente realestate.marketingwebsites.ca/api.php est verrouillée par93#   whitelist IP (impasse, même via proxy). MAIS le serveur WordPress (autorisé94#   sur l'API) rend l'inventaire COMPLET côté serveur sur95#   /fr/properties/?pages={N} (9 fiches/page, param « pages » uniquement).96#   Chaque carte porte data-href /fr/properties/mls/{MLS}, data-price ($US),97#   data-address (rue) et data-pic (property-images/{MLS}/). Le n° MLS = n° Centris.98#99#   FICHE DÉTAIL /fr/properties/mls/{MLS}/ : server-rendered elle aussi100#   (requêtes directes, aucun anti-bot) et TRÈS riche — galerie complète en101#   pleine résolution (~1728px, ancres data-lightbox="gallery-item"), remarque102#   du courtier + addendum, inclusions/exclusions, icônes (chambres/sdb/103#   superficie MC|PC/année), tables th/td par section (BÂTIMENT, ÉVALUATION,104#   DÉPENSES, CARACTÉRISTIQUES, DÉTAILS DE PIÈCE), GPS exact dans l'embed105#   Street View, courtier inscripteur (photo alt + tel: du bloc latéral).106#   Enrichissement via _detailutil.enrich (cache BD + plafond107#   IMMOKA_EXP_DETAIL_LIMIT, ~400/cycle).108#109#   La VILLE vient de la fiche détail (en-tête h2) ; repli sur l'endpoint SSR110#   /wp-content/themes/canvas/load/map-property.php?mls={MLS}&lang=fr pour les111#   fiches au-delà du budget détail (cache « city » déjà peuplé).112#113#   ⚠ PLAFOND : le SSR reflète le limit=1000 de l'API sous-jacente → au plus114#   ~1000 fiches (pages 1..~114, crawl vérifié). C'est l'inventaire pratique115#   complet ; si eXp QC dépasse un jour 1000 inscriptions, segmenter par région116#   (params MW_region / MW_q du formulaire), chaque segment ayant son propre cap.117#118#   source_id « exp_ag_qc » : infixe _ag_ = dédup Centris (db.refresh_dedup) —119#   les fiches co-listées avec une bannière couverte sont masquées.120# -----------------------------------------------------------------------------121from __future__ import annotations122123import html as _html124import os125import re126127from .base import BaseConnector128from . import _detailutil as du129from ..normalize import parse_price130from ..schema import PropertyListing131132SITE = "https://expquebec.com"133LISTING = SITE + "/fr/properties/"134MAP_PROP = SITE + "/wp-content/themes/canvas/load/map-property.php"135DETAIL_LIMIT = int(os.environ.get("IMMOKA_EXP_DETAIL_LIMIT", "400"))136CITY_LIMIT = int(os.environ.get("IMMOKA_EXP_CITY_LIMIT", "1200"))137AGENCY = "eXp Agence immobilière"138139_CARD_SPLIT = re.compile(r'data-href="/fr/properties/mls/(\d{6,9})"')140_PRICE_RE = re.compile(r'data-price="([^"]*)"', re.I)141_ADDR_RE = re.compile(r'data-address="([^"]*)"', re.I)142_PIC_RE = re.compile(r'data-pic="([^"]*)"', re.I)143144# ---- fiche détail -----------------------------------------------------------145_GALLERY_RE = re.compile(r'<a href="(https?://[^"]+)"[^>]*data-lightbox="gallery-item"')146_H2_RE = re.compile(r'<small>MLS\s*#\s*\d+</small><br>\s*(.*?)</h2>', re.S)147_ICON_RE = re.compile(r'<i class="icon-realestate-(bed|bathtub|plan|calendar)">'148                      r'</i>\s*([^<]+)')149_REMARK_RE = re.compile(r'<h4>Remarque du courtier</h4>\s*<p[^>]*>(.*?)</p>', re.S)150_ADDENDUM_RE = re.compile(r'<h4>Addendum</h4>\s*<p[^>]*>(.*?)</p>', re.S)151_INCL_RE = re.compile(r'<h4>INCLUSION</h4>\s*<p[^>]*>(.*?)</p>', re.S)152_EXCL_RE = re.compile(r'<h4>EXCLUSION</h4>\s*<p[^>]*>(.*?)</p>', re.S)153_TABLE_RE = re.compile(r'<table class="table">(.*?)</table>', re.S)154_SECTION_RE = re.compile(r'>\s*(BÂTIMENT|ÉVALUATION|DÉPENSES|CARACTÉRISTIQUES)\b')155_PAIR_RE = re.compile(r'<th class="prop-table"[^>]*>\s*(?:<[^>]+>\s*)*([^<]+?)\s*</th>'156                      r'\s*<td[^>]*>\s*([^<]*?)\s*</td>', re.S)157_ROOM_RE = re.compile(r'<td data-title="Chambre">([^<]*)</td>\s*'158                      r'<td data-title="Dimensions">([^<]*)</td>\s*'159                      r'<td data-title="Niveau">([^<]*)</td>\s*'160                      r'<td data-title="Planchers">([^<]*)</td>', re.S)161_SV_RE = re.compile(r'streetview\?key=[^&"\']*&location=(-?\d{1,2}\.\d+),(-?\d{2,3}\.\d+)')162_AGENT_RE = re.compile(r'agent-images/[^"]+"\s+alt="([^"]+)"')163_TEL_RE = re.compile(r'href="tel:(\d{7,15})"')164_SMS_RE = re.compile(r'data-phone="\+?1?(\d{10})"')165_OCCUP_RE = re.compile(r"Date d'occupation\s*:\s*([\d-]{8,10})")166_OPEN_RE = re.compile(r'visite libre<br>\s*(.*?)</h4>', re.S | re.I)167_TOUR_RE = re.compile(r'https?://(?:my\.)?(?:matterport\.com|youtu\.be|'168                      r'vimeo\.com)/[^"\'<> ]+', re.I)169_AREA_RE = re.compile(r'([\d,]+(?:\.\d+)?)\s*(MC|PC)\b', re.I)170_POSTAL_RE = re.compile(r'^[A-Z]\d[A-Z]\s*\d[A-Z]\d$')171172# lignes du texte-source repliées en dur à ~60 colonnes : on recolle les173# retours qui coupent une phrase (pas de ponctuation finale, suite en minuscule)174_WRAP_RE = re.compile(r'(?<![.!?:])\n(?=[a-zà-ÿœ])')175176177def _parse_us_price(label: str):178    label = (label or "").strip()179    if not label:180        return None, ""181    price = parse_price(label.replace("$", "").replace(",", "")) if label.startswith("$") \182        else parse_price(label)183    return price, label184185186def _txt(block: str) -> str:187    """Bloc HTML -> texte propre (les <br> deviennent des sauts de ligne,188    les retours en dur du flux Centris sont recollés)."""189    block = re.sub(r'<br\s*/?>', '\n@@BR@@\n', block, flags=re.I)190    block = re.sub(r'<[^>]+>', ' ', block)191    block = _html.unescape(block).replace('\r', '')192    block = re.sub(r'[ \t]+', ' ', block)193    block = re.sub(r' ?\n ?', '\n', block).strip()194    block = _WRAP_RE.sub(' ', block)             # déplie les phrases coupées195    block = block.replace('\n@@BR@@\n', '\n').replace('@@BR@@', '\n')196    return re.sub(r'\n{3,}', '\n\n', block).strip()197198199def _area_sqft(val: str) -> float | None:200    """« 91.4 MC » (m²) / « 2378.82 PC » (pi²) -> pi²."""201    m = _AREA_RE.search(val or "")202    if not m:203        return None204    try:205        v = float(m.group(1).replace(",", ""))206    except ValueError:207        return None208    if v <= 0:209        return None210    return round(v * 10.7639) if m.group(2).upper() == "MC" else round(v)211212213def _fmt_area(val: str) -> str:214    """« 91.4 MC » -> « 91.4 m² » ; « 2378.82 PC » -> « 2378.82 pi² »."""215    m = _AREA_RE.search(val or "")216    if not m:217        return (val or "").strip()218    unit = "m²" if m.group(2).upper() == "MC" else "pi²"219    return f"{m.group(1)} {unit}"220221222def _parse_exp_detail(html: str) -> dict:223    """Fiche détail expquebec.com (server-rendered) -> payload riche."""224    out: dict = {}225    details: dict = {}226    features: list[str] = []227228    # -- galerie complète, pleine résolution, ordre d'origine (dédoublonnée :229    #    le carrousel duplique les ancres pour le loop)230    images, seen = [], set()231    for u in _GALLERY_RE.findall(html):232        u = _html.unescape(u).strip()233        if u and u not in seen:234            seen.add(u)235            images.append(u)236    if images:237        out["images"] = images238239    # -- en-tête h2 : adresse <br/> Ville (secteur), Arrondissement X, CP240    m = _H2_RE.search(html)241    if m:242        head = _html.unescape(re.sub(r'<[^>]+>', '\n', m.group(1)))243        lines = [ln.strip() for ln in head.split('\n') if ln.strip()]244        if lines:245            out["address"] = lines[0]246            rest = " ".join(lines[1:])247            parts = [p.strip() for p in rest.split(",") if p.strip()]248            if parts:249                cm = re.match(r'^(.*?)\s*\((.+)\)\s*$', parts[0])250                if cm:251                    out["city"], out["sector"] = cm.group(1).strip(), cm.group(2).strip()252                else:253                    out["city"] = parts[0]254                for p in parts[1:]:255                    if _POSTAL_RE.match(p):256                        details["Code postal"] = p257                    elif p.startswith("Arrondissement ") and not out.get("sector"):258                        arr = p[len("Arrondissement "):].strip()259                        if arr and arr != "Ville" and not arr.startswith("Noms de rues"):260                            out["sector"] = arr261262    # -- icônes : chambres / salles de bains / superficie / année263    for icon, val in _ICON_RE.findall(html):264        val = val.strip()265        if not val:266            continue267        if icon == "bed" and val.isdigit():268            out["bedrooms"] = int(val)269        elif icon == "bathtub" and val.isdigit():270            out["bathrooms"] = int(val)271        elif icon == "plan":272            sqft = _area_sqft(val)273            if sqft:274                out["area_sqft"] = sqft275                details["Superficie habitable"] = _fmt_area(val)276        elif icon == "calendar" and re.fullmatch(r'(1[6-9]|20)\d{2}', val):277            out["year_built"] = int(val)278279    # -- description : l'addendum (long) bat la remarque du courtier280    remark = _REMARK_RE.search(html)281    addendum = _ADDENDUM_RE.search(html)282    texts = [_txt(x.group(1)) for x in (addendum, remark) if x]283    if texts:284        out["description"] = max(texts, key=len)285    for rx, key in ((_INCL_RE, "Inclusions"), (_EXCL_RE, "Exclusions")):286        m = rx.search(html)287        if m:288            v = _txt(m.group(1))289            if v:290                details[key] = v291292    # -- tables th/td par section (dupliquées mobile/desktop -> dict dédoublonne)293    for tbl in _TABLE_RE.findall(html):294        sec = _SECTION_RE.search(tbl)295        if not sec:296            continue297        section = sec.group(1)298        for label, val in _PAIR_RE.findall(tbl):299            label = _html.unescape(label).strip().rstrip(":")300            val = re.sub(r'\s+', ' ', _html.unescape(val)).strip()301            if not val or val in ("0", "-"):302                continue303            if section == "BÂTIMENT":304                if label == "Type":305                    out["property_type"] = val306                    details["Type de propriété"] = val307                elif label == "Style":308                    details["Style de bâtiment"] = val309                elif label == "Dimensions":310                    details["Dimensions du bâtiment"] = val311                elif label == "Dimension terrain":312                    details["Superficie du terrain"] = _fmt_area(val) \313                        if _AREA_RE.search(val) else val314                    lot = _area_sqft(val)315                    if lot:316                        out["lot_sqft"] = lot317                else:                       # Nombre d'étages, Année de construction…318                    details[label] = val319            elif section == "ÉVALUATION":320                if label == "Année":321                    details["Évaluation municipale (année)"] = val322                elif label in ("Terrain", "Bâtiment", "Total"):323                    details[f"Évaluation municipale ({label.lower()})"] = val324            elif section == "DÉPENSES":325                details[re.sub(r'\s*\(\d{4}\)\s*', '', label)] = val326            else:                           # CARACTÉRISTIQUES327                details[label] = val328                if label in ("Particularités", "Équipement disponible"):329                    features.extend(f.strip() for f in val.split(",") if f.strip())330331    # -- pièces (clé spéciale `pieces` rendue par le frontend) + salles d'eau332    rooms, powder = [], 0333    for nom, dims, niveau, sol in _ROOM_RE.findall(html):334        nom = _html.unescape(nom).strip()335        if not nom:336            continue337        room = {"nom": nom}338        for k, v in (("dimensions", dims), ("niveau", niveau), ("revetement", sol)):339            v = _html.unescape(v).strip()340            if v:341                room[k] = v342        rooms.append(room)343        if nom.lower() == "salle d'eau":344            powder += 1345    if rooms:346        details["pieces"] = rooms347    if powder:348        out["powder_rooms"] = powder349350    # -- GPS exact (embed Street View), courtier, extras351    m = _SV_RE.search(html)352    if m:353        out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))354    m = _AGENT_RE.search(html)355    if m:356        out["broker_name"] = _html.unescape(m.group(1)).strip()357        blk = html[m.end():m.end() + 3000]      # bloc latéral du courtier358        tel = _TEL_RE.search(blk) or _SMS_RE.search(blk)359        if tel:360            out["broker_phone"] = tel.group(1)361    m = _OCCUP_RE.search(html)362    if m:363        details["Date d'occupation"] = m.group(1)364    m = _OPEN_RE.search(html)365    if m:366        v = re.sub(r'\s+', ' ', _html.unescape(re.sub(r'<[^>]+>', ' ', m.group(1)))).strip(" |")367        if v:368            details["Visite libre"] = v369    m = _TOUR_RE.search(html)370    if m:371        details["Visite virtuelle"] = m.group(0)372373    if details:374        out["details"] = details375    if features:376        out["features"] = features377    return out378379380class ExpQuebecConnector(BaseConnector):381    source_id = "exp_ag_qc"382    request_delay = 0.4383    max_pages = 200          # garde-fou (9/page) ; stop après 3 pages vides384385    def fetch(self) -> list[PropertyListing]:386        by_id: dict[str, PropertyListing] = {}387        empty = 0388        for page in range(1, self.max_pages + 1):389            url = LISTING if page == 1 else f"{LISTING}?pages={page}"390            try:391                html = self.get(url).text392            except Exception:393                break394            parts = _CARD_SPLIT.split(html)395            # parts = [pre, mls1, blk1, mls2, blk2, …]396            found = 0397            for i in range(1, len(parts) - 1, 2):398                mls, blk = parts[i], parts[i + 1][:1500]399                if mls in by_id:400                    continue401                lst = self._card(mls, blk)402                if lst:403                    by_id[mls] = lst404                    found += 1405            empty = empty + 1 if found == 0 else 0406            if empty >= 3:407                break408        listings = list(by_id.values())409        # fiche détail complète : galerie pleine résolution, description,410        # tables BÂTIMENT/ÉVALUATION/DÉPENSES/CARACTÉRISTIQUES, pièces, GPS,411        # courtier + téléphone. v1 = premier parse complet.412        du.enrich(self, listings, DETAIL_LIMIT, _parse_exp_detail, key="v1")413        # repli ville (fiches au-delà du budget détail) : endpoint SSR léger,414        # cache « city » déjà peuplé pour l'inventaire existant415        self._enrich_cities([l for l in listings if not l.city])416        return listings417418    def _card(self, mls: str, blk: str) -> PropertyListing | None:419        pm = _PRICE_RE.search(blk)420        am = _ADDR_RE.search(blk)421        pic = _PIC_RE.search(blk)422        price, price_label = _parse_us_price(pm.group(1) if pm else "")423        addr = _html.unescape(am.group(1)).strip() if am else ""424        img = _html.unescape(pic.group(1)).strip() if pic else \425            f"https://realestate.marketingwebsites.ca/property-images/{mls}/{mls}-01.jpg"426        return PropertyListing(427            source=self.source_id,428            external_id=mls,429            url=f"{SITE}/fr/properties/mls/{mls}/",430            title=addr or "Propriété à vendre",431            address=addr,432            price=price,433            price_label=price_label,434            mls=mls,435            images=[img] if img else [],436            agency=AGENCY,437            broker_name=AGENCY,438        )439440    def _enrich_cities(self, listings: list[PropertyListing]) -> None:441        """Complète la ville via map-property.php, avec cache BD + plafond.442        La ville est le dernier segment texte de la carte-fiche (après le prix443        et l'adresse).444445        ⚠ detail_cache = UNE ligne par fiche : on lit le payload quelle que446        soit sa clé (« city » historique OU « v1 » du parse détail, qui inclut447        la ville) et on n'écrit une ligne « city » que s'il n'y en a AUCUNE —448        jamais par-dessus un payload détail complet."""449        if CITY_LIMIT <= 0:450            return451        from .. import db452        con = db.connect()453        budget = CITY_LIMIT454        try:455            for lst in listings:456                cached = db.get_stale_detail(con, self.source_id, lst.external_id)457                if cached is None:458                    if budget <= 0:459                        continue460                    fetched = self._fetch_city(lst.external_id)461                    db.put_cached_detail(con, self.source_id, lst.external_id,462                                         "city", fetched)463                    budget -= 1464                    cached = fetched465                if cached.get("city") and not lst.city:466                    lst.city = cached["city"]467        finally:468            con.close()469470    def _fetch_city(self, mls: str) -> dict:471        try:472            html = self.get(f"{MAP_PROP}?mls={mls}&lang=fr").text473        except Exception:474            return {}475        # segments texte : retirer prix ($), adresse (déjà connue) → dernier = ville476        segs = [s.strip() for s in re.split(r'<[^>]+>', html) if s.strip()]477        segs = [_html.unescape(s) for s in segs if "$" not in s and "-->" not in s]478        # la ville est le dernier segment alphabétique non numérique479        for s in reversed(segs):480            if re.search(r'[A-Za-zÀ-ÿ]{3,}', s) and not re.match(r'^\d', s):481                # éviter de reprendre l'adresse (commence souvent par un n° civique)482                return {"city": s}483        return {}484
Files main
Menu

Theme