SPB Git

Repository Public

publimaison.py 16.8 KB 374 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/publimaison.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1313# 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/publimaison.py : Publimaison.ca (FSBO + transferts Centris)91#92#   2e plateforme « vente par le propriétaire » du Québec (~5 400 annonces),93#   qui accepte aussi les transferts Centris de courtiers (« No. MLS » affiché).94#   Recherche rendue SERVEUR pilotée par le pseudo-hash d'URL95#   (/fr/recherche/?hash=/…/nbr_item=8/page=N, page 0-indexée, 8 cartes/page,96#   total « Résultats de 1 à 8 sur NNNN »). Chaque carte porte déjà : réf MLS,97#   type, ville, prix, chambres, adresse, description et photo extralarge.98#   La fiche détail (HTML, sans JSON-LD) ajoute galerie complète, code postal,99#   pièces et dimensions, taxes et évaluation — enrichissement cache + plafond.100#101#   source_id « publimaison_ag_qc » : l'infixe _ag_ active la dédup Centris —102#   quand la réf de la carte est un n° MLS déjà porté par la bannière du103#   courtier, la fiche est masquée ; les annonces de particuliers (réf interne)104#   restent toujours visibles. Aucun double-comptage.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import html as _html109import os110import re111112from .base import BaseConnector113from . import _detailutil as du114from ..normalize import parse_price115from ..schema import PropertyListing116117SITE = "https://www.publimaison.ca"118HASH = ("/show=liste/regions=/villes=/type_propriete=/categories=/prix_min=0"119        "/prix_max=0/caracteristiques=/chambres=0/salles_bain=0/etat=1"120        "/parution=4/construction=5/trier_par=3/existante=true/nbr_item=8")121DETAIL_LIMIT = int(os.environ.get("IMMOKA_PUBLIMAISON_DETAIL_LIMIT",122                                  os.environ.get("IMMOKA_DETAIL_LIMIT", "300")))123AGENCY = "Publimaison"124125_CARD_RE = re.compile(126    r'href="/fr/annonce/(\d+)/([a-z0-9-]+?)-a-vendre-([a-z0-9-]+)"'127    r'\s+title="(\d{6,9}) - ([^"]+?) à vendre"', re.I)128_TOTAL_RE = re.compile(r"sur\s+(\d{2,6})\s*</p>")129# fiche détail : « original » = pleine résolution (extrabig/extrathumbnail =130# variantes). La galerie fotorama porte data-full="…fr_<type>_original_…" où le131# slug de type suit celui de l'annonce (maison, condo, terrain, duplex, chalet…)132# — NE PAS figer « maison » : 44 % de l'inventaire n'en est pas. L'avatar du133# courtier (fr_original_…, sans slug de type) ne matche aucun des deux motifs.134_GALLERY_RE = re.compile(r'data-full="(https://image\.publimaison\.ca/[^"]+)"', re.I)135_PHOTO_RE = re.compile(136    r"https://image\.publimaison\.ca/fr_[a-z0-9_]+?_original_[^\"'\\ ]+\.jpg", re.I)137# page /carte : seul le marqueur de la propriété a des littéraux dans LatLng(…)138# (le centre par défaut 46.8032826,-71.242796 passe par des variables)139_LATLNG_RE = re.compile(140    r"google\.maps\.LatLng\(\s*(-?\d{1,2}\.\d+)\s*,\s*(-?\d{2,3}\.\d+)\s*\)")141142143class PublimaisonConnector(BaseConnector):144    source_id = "publimaison_ag_qc"145    request_delay = 0.25146    max_pages = 900          # garde-fou (8 annonces/page)147148    def fetch(self) -> list[PropertyListing]:149        by_id: dict[str, PropertyListing] = {}150        total, dry = None, 0151        for page in range(self.max_pages):152            url = f"{SITE}/fr/recherche/?hash={HASH}/page={page}"153            try:154                html = self.get(url).text155            except Exception:156                break157            if total is None:158                m = _TOTAL_RE.search(html)159                total = int(m.group(1)) if m else 0160            before = len(by_id)161            for lst in self._cards(html):162                by_id.setdefault(lst.external_id, lst)163            # les premières pages contiennent des items promus qui se164            # chevauchent : on ne s'arrête qu'après 3 pages sans rien de neuf.165            dry = dry + 1 if len(by_id) == before else 0166            if dry >= 3:167                break168            if total and len(by_id) >= total:169                break170        listings = list(by_id.values())171        # v2 : galerie toutes catégories (v1 ne captait que fr_maison_*),172        # description fiche-description, prix d'en-tête, GPS via /carte173        du.enrich(self, listings, DETAIL_LIMIT, parse_publimaison_detail,174                  key="v2", fetch_html=self._detail_html)175        return listings176177    def _detail_html(self, url: str) -> str:178        """Fiche détail + onglet /carte (marqueur Google Maps -> lat/lng) ;179        la carte est best-effort : son échec ne coûte pas la fiche."""180        html = self.get(url).text181        try:182            html += "\n" + self.get(url.rstrip("/") + "/carte").text183        except Exception:184            pass185        return html186187    # -- cartes de résultats ----------------------------------------------------188    def _cards(self, html: str):189        for blk in html.split('maison_resultat_recherche')[1:]:190            blk = blk[:4000]191            m = _CARD_RE.search(blk)192            if not m:193                continue194            aid, type_s, region_s, ref, type_txt = m.groups()195196            def field(cls: str) -> str:197                fm = re.search(r'class="' + cls + r'">.*?>([^<]+)</a>', blk, re.S)198                return _html.unescape(fm.group(1)).strip() if fm else ""199200            ville = re.search(r'class="ville">([^<]+)<', blk)201            desc = re.search(r'class="description">([^<]+)<', blk)202            img = re.search(r'src="(https://image\.publimaison\.ca/[^"]+)"', blk)203            prix_txt = field("prix")                     # « 500 000 $ -4 Ch. »204            mb = re.search(r"-\s*(\d{1,2})\s*Ch", prix_txt)205206            # réf 7-8 chiffres = n° MLS (transfert Centris) -> clé de dédup ;207            # sinon annonce de particulier -> id d'annonce Publimaison.208            is_mls = len(ref) in (7, 8)209            yield PropertyListing(210                source=self.source_id,211                external_id=ref if is_mls else aid,212                url=f"{SITE}/fr/annonce/{aid}/{type_s}-a-vendre-{region_s}",213                title=field("adresse") or type_txt,214                address=field("adresse"),215                city=_html.unescape(ville.group(1)).strip() if ville else "",216                region=_deslug(region_s),217                property_type=type_txt,218                price=parse_price(prix_txt),219                price_label=prix_txt.split("-")[0].strip(),220                bedrooms=int(mb.group(1)) if mb else None,221                mls=ref if is_mls else "",222                description=_html.unescape(desc.group(1)).strip() if desc else "",223                images=[img.group(1).replace("_large_", "_extralarge_")] if img else [],224                agency=AGENCY,225            )226227228# ---------------------------------------------------------------------------229def parse_publimaison_detail(html: str) -> dict:230    """Fiche détail (HTML pur, + page /carte concaténée) : galerie originale231    complète (fotorama data-full, ordre de la fiche), code postal, année, prix,232    pièces et dimensions, taxes/évaluation, superficies, GPS du marqueur."""233    out: dict = {}234    details: dict = {}235236    seen, imgs = set(), []237    for u in (_GALLERY_RE.findall(html) or _PHOTO_RE.findall(html)):238        if u not in seen:239            seen.add(u)240            imgs.append(u)241    if imgs:242        out["images"] = imgs243244    # GPS : marqueur de la page /carte (littéraux), borné au Québec ;245    # on saute le centre par défaut de la carte au cas où.246    for mlat, mlng in _LATLNG_RE.findall(html):247        try:248            lat, lng = float(mlat), float(mlng)249        except ValueError:250            continue251        if (44.0 <= lat <= 63.0 and -80.5 <= lng <= -56.0252                and (round(lat, 4), round(lng, 4)) != (46.8033, -71.2428)):253            out["lat"], out["lng"] = lat, lng254            break255256    text = du.flatten(html)257258    # prix d'en-tête « … J7Y0A5 (No. MLS …) | 324 900 $ | Détails | … »259    # (les cartes « Prix sur demande » ont parfois un prix sur la fiche)260    mp = re.search(r"\|\s*([\d][\d\s]{1,11}\$)\s*\|\s*Détails\b", text)261    if mp:262        p = parse_price(mp.group(1))263        if p:264            out["price"] = p265            out["price_label"] = re.sub(r"\s+", " ", mp.group(1)).strip()266267    # « 128 Rue Léonard, Châteauguay (Montérégie) J6K1N8 (No. MLS 14082277) »268    mh = re.search(r"([A-Z]\d[A-Z]\s?\d[A-Z]\d)\s*(?:\(No\. MLS|\|)", text)269    if mh:270        details["postal_code"] = mh.group(1).strip()271272    # bloc « Données de base » (Libellé | Valeur, N/D = absent) :273    # Construction | 2007 | … | Pièces | 8 | Chambre(s) | 2 | Salle(s) de bain | 1274    my = re.search(r"(?:Année de construction|Construction)\s*\|\s*((?:1[6-9]|20)\d{2})\b", text)275    if my:276        out["year_built"] = int(my.group(1))277    mb2 = re.search(r"Chambre\(s\)\s*\|\s*(\d{1,2})\b", text)278    if mb2 and int(mb2.group(1)) > 0:279        out["bedrooms"] = int(mb2.group(1))280    ms2 = re.search(r"Salle\(s\) de bain\s*\|\s*(\d{1,2})\b", text)281    if ms2 and int(ms2.group(1)) > 0:282        out["bathrooms"] = int(ms2.group(1))283    mse = re.search(r"Salle\(s\) d[’']eau\s*\|\s*(\d{1,2})\b", text)284    if mse and int(mse.group(1)) > 0:285        out["powder_rooms"] = int(mse.group(1))286    mpc = re.search(r"Pièces\s*\|\s*(\d{1,2})\b", text)287    if mpc and int(mpc.group(1)) > 0:288        details["Nombre de pièces"] = int(mpc.group(1))289    met = re.search(r"Nombre d[’']étage\(s\)\s*\|\s*(\d{1,2})\b", text)290    if met and int(met.group(1)) > 0:291        details["Étages"] = int(met.group(1))292    for lab in ("Dimensions du bâtiment", "Dimensions du terrain"):293        mdim = re.search(re.escape(lab) + r"\s*\|\s*([\d][^|]{0,24}?)\s*\|", text)294        if mdim:295            val = mdim.group(1).strip()296            details[lab] = val297            if lab == "Dimensions du terrain" and "lot_sqft" not in out:298                mlx = re.match(r"([\d.,]+)\s*[xX]\s*([\d.,]+)\s*(pi|m)\b", val)299                if mlx:300                    try:301                        a = float(mlx.group(1).replace(",", "."))302                        b = float(mlx.group(2).replace(",", "."))303                    except ValueError:304                        a = b = 0.0305                    if a and b:306                        f = 10.7639 if mlx.group(3) == "m" else 1307                        out["lot_sqft"] = round(a * b * f, 0)308309    for label, key in [("Évaluation totale", "Évaluation municipale"),310                       ("Taxes municipales", "Taxes municipales"),311                       ("Taxes scolaires", "Taxes scolaires")]:312        mv = re.search(re.escape(label) + r"\s*\|\s*([\d\s,]+\$)", text)313        if mv:314            details[key] = mv.group(1).strip()315316    # superficies (habitable / terrain), formats « NNNN pi² » ou « N X M pi »317    ma = re.search(r"(?:Superficie habitable|Sup\. habitable)\s*\|\s*([\d\s,.]+)\s*pi", text)318    if ma:319        try:320            out["area_sqft"] = float(ma.group(1).replace(" ", "").replace(",", "."))321        except ValueError:322            pass323    ml = re.search(r"Superficie du terrain\s*\|\s*([\d\s,.]+)\s*pi", text)324    if ml:325        try:326            out["lot_sqft"] = float(ml.group(1).replace(" ", "").replace(",", "."))327        except ValueError:328            pass329330    # tableau des pièces : « Nom | Niveau | L X l pi | Revêtement » — le niveau331    # est libre (Rez-de-jardin, Mezzanine…), c'est la cellule dimensions qui ancre332    rooms = []333    for rm in re.finditer(334            r"\|\s*([A-ZÀ-Ü][^|]{1,28}?)\s*\|\s*([A-Za-zÀ-ü][A-Za-zÀ-ü0-9'’ -]{1,20}?)"335            r"\s*\|\s*([\d.,]+\s*X\s*[\d.,]+\s*(?:pi|m))\s*\|\s*([^|]{0,25}?)\s*(?=\|)", text):336        rooms.append({"nom": rm.group(1).strip(), "niveau": rm.group(2).strip(),337                      "dimensions": rm.group(3).strip(),338                      "revetement": rm.group(4).strip()})339    if rooms:340        details["pieces"] = rooms[:30]341        # comptes dérivés du tableau des pièces (appliqués seulement si le342        # champ manque encore — apply_detail n'écrase jamais une valeur)343        nb_ch = sum(1 for r in rooms if r["nom"].lower().startswith("chambre"))344        nb_sdb = sum(1 for r in rooms if r["nom"].lower().startswith("salle de bain"))345        nb_se = sum(1 for r in rooms346                    if r["nom"].lower().startswith(("salle d'eau", "salle d’eau")))347        if nb_ch and "bedrooms" not in out:348            out["bedrooms"] = nb_ch349        if nb_sdb and "bathrooms" not in out:350            out["bathrooms"] = nb_sdb351        if nb_se and "powder_rooms" not in out:352            out["powder_rooms"] = nb_se353354    # description longue de la fiche : bloc « fiche-description » (h4 + <div>355    # de <p>) — le lien statcounter « Voir … » est retiré avant l'aplatissage356    md = re.search(r'class="fiche-description[^"]*".*?<div>(.*?)</div>', html, re.S)357    if md:358        d = re.sub(r"<a\b.*?</a>", " ", md.group(1), flags=re.S)359        d = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", d))).strip()360        if len(d) > 60:361            out["description"] = d[:4000]362363    if details:364        out["details"] = details365    return out366367368def _deslug(s: str) -> str:369    r = re.sub(r"\s+", " ", s.replace("-", " ")).strip().title()370    return (r.replace("Monteregie", "Montérégie").replace("Quebec", "Québec")371             .replace("Montreal", "Montréal").replace("Abitibi Temiscamingue", "Abitibi-Témiscamingue")372             .replace("Gaspesie", "Gaspésie").replace("Cote Nord", "Côte-Nord")373             .replace("Ile", "Île").replace("Saguenay Lac St Jean", "Saguenay–Lac-Saint-Jean"))374
Files main
Menu

Theme