SPB Git

Repository Public

avecuncourtier.py 16.1 KB 383 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/avecuncourtier.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/avecuncourtier.py : portail « avec un courtier » de la Chambre91#   immobilière de l'Outaouais (avecuncourtier.com). Couvre TOUT l'Outaouais92#   (Gatineau → Maniwaki/Pontiac) d'un coup — c'est le portail MLS régional de93#   la chambre, pas une agence unique. Recherche rendue SERVEUR (plateforme94#   Concrete5, Tonik Web Studio), paginée par ?page=N (12 cartes/page, ~34195#   pages). Chaque carte porte déjà : n° MLS (Centris), adresse, ville/secteur,96#   type, aire habitable, prix et photo.97#98#   ENRICHISSEMENT DÉTAIL (v2) : /fr/proprietes/details/{mls}-{slug} est rendue99#   serveur : galerie complète (/centris/photos/{mls}/{n}.jpg, ordre d'origine),100#   description + Addendas, GPS (data-lat/data-lon), accordéons « Proximité »,101#   « Dimension des pièces » (4 col.), « Taxes et dépenses » + « Bâtiment et102#   intérieur » (paires td/td : chambres, sdb, aire habitable en m², terrain,103#   année, évaluations…), visites libres, courtier(s) inscripteur(s) + agence104#   réelle (RE/MAX Vision, Exit…). Cache BD via _detailutil.enrich.105#106#   source_id « cio_ag_outaouais » : l'infixe _ag_ active la dédup Centris107#   (db.refresh_dedup, sources %_ag_%). Comme le portail agrège les inscriptions108#   des bannières déjà couvertes (RE/MAX, Royal LePage, Via Capitale, Proprio109#   Direct…), la dédup masque les fiches dont le n° Centris est déjà porté par110#   une source canonique ; seules les inscriptions d'agences NON couvertes de111#   l'Outaouais restent visibles. Aucun double-comptage.112# -----------------------------------------------------------------------------113from __future__ import annotations114115import html as _html116import os117import re118119from .base import BaseConnector120from . import _detailutil as du121from ..normalize import parse_price122from ..schema import PropertyListing123124SITE = "https://avecuncourtier.com"125LISTING = SITE + "/fr/proprietes"126MAX_PAGES = int(os.environ.get("IMMOKA_AUC_MAX_PAGES", "400"))127AGENCY = "Chambre immobilière de l'Outaouais"128# fiches détail (re)lues au plus par cycle — cache BD (key v2). ~1 400 fiches129# publiées → ~5 cycles de rattrapage, puis seules les nouvelles sont lues.130DETAIL_LIMIT = int(os.environ.get("IMMOKA_AUC_DETAIL_LIMIT",131                                  os.environ.get("IMMOKA_DETAIL_LIMIT", "300")))132133# une carte commence par <div class="photo "> et court jusqu'à la fermeture du134# bloc listing suivant ; on la borne au <div class="photo "> suivant.135_CARD_SPLIT = re.compile(r'<div class="photo\s*">')136_HREF_RE = re.compile(r'/fr/proprietes/details/(\d{6,9})-([a-z0-9-]+)', re.I)137_ALT_RE = re.compile(r'<img[^>]+alt="([^"]*)"', re.I)138_IMG_RE = re.compile(r'<img[^>]+src="([^"]+)"', re.I)139_MLS_RE = re.compile(r'MLS[^0-9]{0,3}(\d{6,9})', re.I)140_PRICE_RE = re.compile(r'class="price">\s*([\d\s ,.]+\$[^<]*)<', re.I)141_ADDR_RE = re.compile(r'<address>\s*<span>([^<]*)</span>\s*(?:<br\s*/?>)?\s*([^<]*)</address>', re.S | re.I)142_TYPE_RE = re.compile(r'header">\s*Type\s*</div>\s*<div class="column">\s*([^<]+?)\s*</div>', re.S | re.I)143144145class AvecUnCourtierConnector(BaseConnector):146    source_id = "cio_ag_outaouais"147    request_delay = 0.4148    max_pages = MAX_PAGES149150    def fetch(self) -> list[PropertyListing]:151        by_id: dict[str, PropertyListing] = {}152        dry = 0153        for page in range(1, self.max_pages + 1):154            url = f"{LISTING}?page={page}"155            try:156                html = self.get(url).text157            except Exception:158                break159            before = len(by_id)160            for blk in _CARD_SPLIT.split(html)[1:]:161                blk = blk[:3000]162                lst = self._card(blk)163                if lst:164                    by_id.setdefault(lst.external_id, lst)165            # fin de pagination : plus aucune carte neuve sur 2 pages de suite166            dry = dry + 1 if len(by_id) == before else 0167            if dry >= 2:168                break169        listings = list(by_id.values())170        # fiche détail (server-rendered) : galerie complète, description +171        # addendas, GPS, pièces, taxes/évaluations, courtier + agence réelle.172        du.enrich(self, listings, DETAIL_LIMIT, _parse_auc_detail, key="v2")173        for lst in listings:174            office = lst.details.pop("__agency", "")175            if office:176                lst.agency = office177        return listings178179    def _card(self, blk: str) -> PropertyListing | None:180        hm = _HREF_RE.search(blk)181        if not hm:182            return None183        mls = hm.group(1)184185        addr, city = "", ""186        am = _ADDR_RE.search(blk)187        if am:188            addr = _html.unescape(am.group(1)).strip()189            city = _html.unescape(re.sub(r'\s+', ' ', am.group(2))).strip()190        if not addr:191            alt = _ALT_RE.search(blk)192            addr = _html.unescape(alt.group(1)).strip() if alt else ""193194        pm = _PRICE_RE.search(blk)195        price_label = _html.unescape(pm.group(1)).replace(" ", " ").strip() if pm else ""196        tm = _TYPE_RE.search(blk)197        prop_type = _html.unescape(tm.group(1)).strip() if tm else ""198        im = _IMG_RE.search(blk)199        img = im.group(1) if im else ""200        if img and img.startswith("/"):201            img = SITE + img202203        return PropertyListing(204            source=self.source_id,205            external_id=mls,206            url=f"{SITE}/fr/proprietes/details/{mls}-{hm.group(2)}",207            title=addr or f"{prop_type} à vendre",208            address=addr,209            city=city,210            property_type=prop_type,211            price=parse_price(price_label),212            price_label=price_label,213            mls=mls,214            images=[img] if img else [],215            agency=AGENCY,216        )217218219# --- fiche détail (Concrete5 / Tonik, server-rendered) ------------------------220_GAL_RE = re.compile(r'data-lazy="(/centris/photos/\d+/[^"]+)"')221_COORD_RE = re.compile(r'data-lat="(-?\d{1,2}\.\d+)"\s+data-lon="(-?\d{2,3}\.\d+)"')222_DESC_RE = re.compile(r'class="property-description">\s*<h2>[^<]*</h2>(.*?)</div>', re.S)223_OPEN_RE = re.compile(r'class="open-houses">\s*<h2>[^<]*</h2>(.*?)</div>', re.S)224_ITEM_TITLE_RE = re.compile(r'>\s*([^<]{3,60}?)\s*<i class="fa fa-angle-down')225_PAIR_RE = re.compile(r'<tr>\s*<td>([^<]{1,70}?)</td>\s*<td>([^<]*?)</td>\s*</tr>', re.S)226_ROOM_RE = re.compile(r'<tr>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*'227                      r'<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*</tr>', re.S)228_ADD_RE = re.compile(r'<td>([^<]{40,})</td>', re.S)229_PROX_RE = re.compile(r'<p>(.*?)</p>', re.S)230_AGENT_NAME_RE = re.compile(r'class="name">([^<]+)<')231_AGENT_TEL_RE = re.compile(r'href="tel:[^"]*"[^>]*>([^<]+)<')232# <div class="agency">NOM INC.<div>RE/MAX VISION</div><div>Agence Immobilière</div>233_AGENT_BANNER_RE = re.compile(r'class="agency">[^<]*<div>([^<]+)</div>', re.S)234_TOUR_RE = re.compile(r'https?://(?:my\.matterport\.com/show/[^"\'\s<>]+'235                      r'|(?:www\.)?youtube\.com/(?:embed/|watch\?v=)[^"\'\s<>]+'236                      r'|youtu\.be/[^"\'\s<>]+'237                      r'|(?:player\.)?vimeo\.com/(?:video/)?\d+[^"\'\s<>]*)', re.I)238239# libellés « Bâtiment et intérieur » promus en colonnes du schéma240_INT_FIELDS = {"Chambres": "bedrooms", "Salles de bain": "bathrooms",241               "Salles d'eau": "powder_rooms"}242243244def _clean(s: str) -> str:245    return re.sub(r'\s+', ' ', _html.unescape(s)).strip()246247248def _to_sqft(val: str) -> float | None:249    """« 128.8 Mètres carrés » / « 1 200 Pieds carrés » / « 305.4 » (m² implicite,250    unités Centris métriques sur ce portail) -> pi²."""251    m = re.search(r'([\d][\d\s  ,.]*)', val or "")252    if not m:253        return None254    raw = m.group(1).replace(" ", "").replace(" ", "").replace(" ", "")255    if raw.count(",") == 1 and "." not in raw:256        raw = raw.replace(",", ".")257    else:258        raw = raw.replace(",", "")259    try:260        v = float(raw)261    except ValueError:262        return None263    if v <= 0:264        return None265    if re.search(r'pied|pi2|pi²|pc\b', val, re.I):266        return round(v)267    return round(v * 10.7639)                # métrique (défaut du portail)268269270def _parse_auc_detail(html: str) -> dict:271    """Fiche avecuncourtier.com : galerie, description+addendas, GPS,272    accordéons (pièces, taxes, bâtiment), courtiers + agence réelle."""273    out: dict = {}274    details: dict = {}275    feats: list[str] = []276277    # galerie : slider principal seulement (avant les vignettes dupliquées)278    main = html.split('gallery-slider__thumbnails')[0]279    imgs = list(dict.fromkeys(SITE + u for u in _GAL_RE.findall(main)))280    if len(imgs) > 1:281        out["images"] = imgs[:80]282283    mc = _COORD_RE.search(html)284    if mc:285        lat, lng = float(mc.group(1)), float(mc.group(2))286        if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:287            out["lat"], out["lng"] = lat, lng288289    desc, addendum = "", ""290    md = _DESC_RE.search(html)291    if md:292        desc = _clean(re.sub(r'<[^>]+>', ' ', md.group(1)))293    mo = _OPEN_RE.search(html)294    if mo:295        oh = _clean(re.sub(r'<[^>]+>', ' ', mo.group(1)))296        if oh:297            details["Visites libres"] = oh[:200]298299    # accordéons « Détails »300    for item in re.split(r'<div class="accordion-item">', html)[1:]:301        tm = _ITEM_TITLE_RE.search(item)302        title = _clean(tm.group(1)) if tm else ""303        if title == "Proximité":304            mp = _PROX_RE.search(item)305            if mp:306                prox = _clean(re.sub(r'<[^>]+>', ' ', mp.group(1)))307                if prox:308                    details["Proximité"] = prox[:300]309                    feats.append(f"Proximité : {prox}"[:300])310        elif title == "Dimension des pièces":311            rooms = _ROOM_RE.findall(item)312            for name, lvl, dim, floor in rooms:313                name, lvl = _clean(name), _clean(lvl)314                dim, floor = _clean(dim), _clean(floor)315                line = name + (f" — {dim}" if dim else "") + (f", {lvl}" if lvl else "")316                if floor:317                    line += f" ({floor})"318                feats.append(line)319        elif title == "Addendas":320            ma = _ADD_RE.search(item)321            if ma:322                # les sauts de ligne du texte Centris sont préservés dans le <td>323                addendum = _html.unescape(ma.group(1)).strip()324        else:                                  # Taxes et dépenses / Bâtiment…325            for label, val in _PAIR_RE.findall(item):326                label, val = _clean(label).rstrip(":"), _clean(val)327                if not label or not val or val in ("0", "-"):328                    continue329                fld = _INT_FIELDS.get(label)330                if fld:331                    mi = re.search(r'\d+', val)332                    if mi:333                        out[fld] = int(mi.group())334                elif label == "Aire habitable":335                    a = _to_sqft(val)336                    if a:337                        out["area_sqft"] = a338                elif label == "Superficie du terrain":339                    t = _to_sqft(val)340                    if t:341                        out["lot_sqft"] = t342                        val = f"{val} m²" if re.fullmatch(r'[\d\s,.]+', val) else val343                elif label == "Année de construction":344                    my = re.search(r'\b((?:1[6-9]|20)\d{2})\b', val)345                    if my:346                        out["year_built"] = int(my.group(1))347                if label in details and val not in details[label]:348                    details[label] = f"{details[label]}, {val}"[:300]349                else:350                    details[label] = val[:300]351352    if desc or addendum:353        out["description"] = "\n\n".join(filter(None, (desc, addendum)))[:6000]354    if feats:355        out["features"] = feats[:40]356357    # courtier(s) inscripteur(s) + bannière réelle (encadré agents-wrapper) :358    # premier agent = inscripteur principal359    i = html.find('class="agents-wrapper"')360    if i != -1:361        j = html.find('calculator-wrapper', i)362        seg = html[i:j if j != -1 else i + 5000]363        mn = _AGENT_NAME_RE.search(seg)364        if mn:365            out["broker_name"] = _clean(mn.group(1))366        mt = _AGENT_TEL_RE.search(seg)367        if mt:368            out["broker_phone"] = _clean(mt.group(1))369        mb = _AGENT_BANNER_RE.search(seg)370        if mb:371            banner = _clean(mb.group(1))372            if banner and banner.lower() != "agence immobilière":373                details["__agency"] = banner.title() if banner.isupper() else banner374375    # visite virtuelle / vidéo (hors liens de pied de page /channel/)376    mtou = _TOUR_RE.search(html)377    if mtou:378        details.setdefault("Visite virtuelle / vidéo", mtou.group(0))379380    if details:381        out["details"] = details382    return out383
Files main
Menu

Theme