SPB Git

Repository Public

agenceimage.py 13.4 KB 323 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/agenceimage.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/agenceimage.py : Image, l'agence immobilière (agenceimage.ca) —91#   Saguenay, Jonquière, Roberval, Dolbeau-Mistassini, Lac-Saint-Jean.92#   Plateforme Yoamo (ID-3 Innovations) + photos Centris. La page /mes-proprietes/93#   rend TOUT l'inventaire côté serveur : chaque carte porte n° Centris (rel/URL),94#   type + ville (dans l'URL et l'alt), coordonnées (data-geo-lat/lng), prix et95#   photo (yoamo.immo/ALSPicture.axd?propId={Centris}).96#97#   Page détail (rel="/proprietes/a-vendre/{type}/{ville}/{centris}/") rendue98#   serveur elle aussi : galerie complète (ALSPicture.axd, une URL par seq=N,99#   pleine taille sans &w=), description JSON-LD (Product), sections100#   <sup>libellé</sup><label>valeur</label> (#building/#land/#more-carac),101#   pièces (#rooms), « En complément » (taxes, évaluation, année, terrain),102#   inclusions/exclusions, courtier (#broker_list, schema.org/RealEstateAgent)103#   et lien Google Maps (adresse + GPS). ⚠ la section #related (« Aussi104#   disponibles ») liste d'AUTRES propriétés — tout est parsé AVANT elle.105#106#   source_id « image_ag_qc » : infixe _ag_ = dédup Centris (db.refresh_dedup) —107#   masque les fiches déjà portées par une bannière couverte au Saguenay–LSJ.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import os113import re114115from .base import BaseConnector116from . import _detailutil as du117from ..normalize import parse_lot_sqft118from ..schema import PropertyListing119120SITE = "https://agenceimage.ca"121LISTING = SITE + "/mes-proprietes/"122AGENCY = "Image, l'agence immobilière"123DETAIL_LIMIT = int(os.environ.get("IMMOKA_IMAGE_DETAIL_LIMIT",124                                  os.environ.get("IMMOKA_DETAIL_LIMIT", "100")))125126# chaque fiche = un <article ... lid="{Centris}"> dont les data-filter-* portent127# tout (prix, ville, genre, chambres, sdb, coords) — plus fiable que le HTML visible.128_ART_SPLIT = re.compile(r'<article\b', re.I)129_LID_RE = re.compile(r'l(?:id|s)="(\d{6,9})"', re.I)130_REL_RE = re.compile(r'rel="(/proprietes/a-vendre/[a-z0-9-]+/[a-z0-9-]+/\d{6,9}/)"', re.I)131_IMG_RE = re.compile(r'(https://yoamo\.immo/ALSPicture\.axd\?propId=\d+[^"\']*)', re.I)132133# --- page détail -------------------------------------------------------------134_DET_URL_RE = re.compile(r'https://yoamo\.immo/ALSPicture\.axd\?[^"\'\s<>]+', re.I)135_SUP_LABEL_RE = re.compile(r'<sup>([^<]+)</sup>\s*<label>\s*([^<]*?)\s*</label>', re.I)136_MAPS_RE = re.compile(r'google\.[^"\']*?[?&]q=([^@"\']+)@(-?\d{1,2}\.\d+),(-?\d{2,3}\.\d+)')137138139def _attr(blk: str, name: str) -> str:140    m = re.search(name + r'="([^"]*)"', blk, re.I)141    return _html.unescape(m.group(1)).strip() if m else ""142143144def _deslug(s: str) -> str:145    return _html.unescape(s.replace("-", " ")).strip().title()146147148def _section(html: str, sid: str) -> str:149    m = re.search(r'<section id="%s".*?</section>' % re.escape(sid), html, re.S | re.I)150    return m.group(0) if m else ""151152153def _text(fragment: str) -> str:154    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()155156157def parse_image_detail(html: str) -> dict:158    """Fiche Yoamo/agenceimage.ca : galerie complète (ordre seq=), description159    JSON-LD, caractéristiques <sup>/<label>, pièces, taxes/évaluation/année,160    inclusions, GPS + adresse (lien Google Maps), courtier + téléphone."""161    out: dict = {}162    # tout ce qui suit #related appartient à D'AUTRES propriétés163    main = re.split(r'<section id="related"', html, 1)[0]164165    # galerie : une URL ALSPicture par seq=N ; on regroupe par propId et on166    # garde le groupe majoritaire (la fiche elle-même), trié par seq d'origine167    groups: dict[str, dict[int, str]] = {}168    for m in _DET_URL_RE.finditer(main):169        u = _html.unescape(m.group(0))170        pid = re.search(r'propId=(\d+)', u)171        seq = re.search(r'[?&]seq=(\d+)', u)172        if pid and seq:173            groups.setdefault(pid.group(1), {}).setdefault(int(seq.group(1)), u)174    if groups:175        best = max(groups.values(), key=len)176        out["images"] = [best[s] for s in sorted(best)]177178    desc = du.ld_description(html)179    if desc:180        out["description"] = desc[:4000]181182    details: dict = {}183    # sections « libellé / valeur » (Bâtiment et intérieur, Terrain et184    # extérieur, Autres caractéristiques)185    for sid in ("building", "land", "more-carac"):186        for lab, val in _SUP_LABEL_RE.findall(_section(main, sid)):187            lab, val = _html.unescape(lab).strip(), _html.unescape(val).strip()188            if lab and val:189                details[lab] = val190191    # pièces (#rooms) : nom + dimensions + étage + plancher192    rooms = []193    for chunk in re.split(r'class="row-item"', _section(main, "rooms"))[1:]:194        nm = re.search(r'<label>([^<]+)</label>\s*<sub>([^<]*)</sub>', chunk)195        if not nm or not nm.group(1).strip():196            continue197        room = {"nom": _html.unescape(nm.group(1)).strip()[:40]}198        dims = _html.unescape(nm.group(2)).strip()199        if dims:200            room["dimensions"] = dims201        for lab, key in (("Étage", "niveau"), ("Plancher", "revetement")):202            mv = re.search(r'<sup>%s</sup>\s*<label>([^<]*)</label>' % lab, chunk)203            if mv and mv.group(1).strip():204                room[key] = _html.unescape(mv.group(1)).strip()205        rooms.append(room)206    if rooms:207        details["pieces"] = rooms[:25]208209    # « En complément » : taxes, évaluation municipale, année, terrain210    text = _text(main)211    for pat, key in ((r"Municipale:\s*([\d\s  ]+\$)", "Taxes municipales"),212                     (r"Scolaire:\s*([\d\s  ]+\$)", "Taxes scolaires"),213                     (r"Évaluation municipale\s*([\d\s  ]+\$)", "Évaluation municipale")):214        mm = re.search(pat, text)215        if mm:216            details[key] = re.sub(r"\s+", " ", mm.group(1)).strip()217    my = re.search(r"Construit en ((?:1[6-9]|20)\d{2})\b", text)218    if my:219        out["year_built"] = int(my.group(1))220    mt = re.search(r"Terrain de ([\d\s  .,]+?)\s*m<sup>2</sup>", main)221    if mt:222        lot = parse_lot_sqft(mt.group(1).strip() + " m²")223        if lot:224            out["lot_sqft"] = lot225226    # inclusions -> features ; exclusions -> details227    inc = _text(_section(main, "inclusive"))228    inc = re.sub(r"^Inclusions\s*", "", inc, flags=re.I)229    feats = [s.strip() for s in re.split(r"[,;]", inc) if 2 <= len(s.strip()) <= 90]230    if feats:231        out["features"] = feats[:20]232    exc = re.sub(r"^Exclusions\s*", "", _text(_section(main, "exclusive")), flags=re.I)233    if exc:234        details["Exclusions"] = exc[:300]235236    # adresse + GPS depuis le lien « Ouvrir la carte »237    mg = _MAPS_RE.search(main)238    if mg:239        addr = _html.unescape(mg.group(1)).split(",")[0].strip()240        if addr:241            out["address"] = addr242        try:243            lat, lng = float(mg.group(2)), float(mg.group(3))244            if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:245                out["lat"], out["lng"] = lat, lng246        except ValueError:247            pass248249    # courtier inscripteur (« Présenté par », 1er de la liste) + téléphone250    broker = _section(main, "broker_list")251    mb = re.search(r'itemprop="name" content="([^"]+)"', broker)252    if mb:253        out["broker_name"] = _html.unescape(mb.group(1)).strip()254    mp = re.search(r'href="tel:\+?\d+">\s*([\d\s().-]{10,20})\s*<', broker)255    if mp:256        out["broker_phone"] = mp.group(1).strip()257258    if details:259        out["details"] = details260    return out261262263class AgenceImageConnector(BaseConnector):264    source_id = "image_ag_qc"265    request_delay = 0.5266267    def fetch(self) -> list[PropertyListing]:268        try:269            html = self.get(LISTING).text270        except Exception:271            return []272        by_id: dict[str, PropertyListing] = {}273        for blk in _ART_SPLIT.split(html)[1:]:274            blk = blk[:3000]275            lst = self._card(blk)276            if lst:277                by_id.setdefault(lst.external_id, lst)278        listings = list(by_id.values())279        # fiche détail : galerie complète, description, caractéristiques,280        # pièces, adresse, courtier — plafonné/cycle, cache BD (voir _detailutil)281        du.enrich(self, [l for l in listings if l.external_id in l.url],282                  DETAIL_LIMIT, parse_image_detail, key="v1")283        return listings284285    def _card(self, blk: str) -> PropertyListing | None:286        lm = _LID_RE.search(blk)287        if not lm:288            return None289        mls = lm.group(1)290        # écarter locations / vendus / loués291        if _attr(blk, "data-filter-rental") == "true" or _attr(blk, "data-filter-sold") == "true":292            return None293294        rel = _REL_RE.search(blk)295        url = f"{SITE}{rel.group(1)}" if rel else f"{SITE}/proprietes/"296        genre = _attr(blk, "data-filter-genre")297        city = _attr(blk, "data-filter-city")298        price = _attr(blk, "data-filter-price")299        beds = _attr(blk, "data-filter-bedrooms")300        baths = _attr(blk, "data-filter-bathrooms")301        lat = _attr(blk, "data-geo-lat")302        lng = _attr(blk, "data-geo-lng")303        im = _IMG_RE.search(blk)304305        return PropertyListing(306            source=self.source_id,307            external_id=mls,308            url=url,309            title=f"{genre} à vendre, {city}".strip(" ,") or "Propriété à vendre",310            property_type=genre,311            city=city,312            price=float(price) if price.isdigit() else None,313            price_label=(f"{int(price):,} $".replace(",", " ") if price.isdigit() else ""),314            bedrooms=int(beds) if beds.isdigit() else None,315            bathrooms=int(baths) if baths.isdigit() else None,316            mls=mls,317            images=[im.group(1).replace("&w=320", "")] if im else [],318            lat=float(lat) if lat else None,319            lng=float(lng) if lng else None,320            agency=AGENCY,321            broker_name=AGENCY,322        )323
Files main
Menu

Theme