SPB Git

Repository Public

sourceimmo.py 20.8 KB 490 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/sourceimmo.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-2514#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/sourceimmo.py : base réutilisable pour les agences bâties sur la91#   plateforme « source.immo » (plugin WordPress source-immo). L'app AngularJS92#   appelle une API ASP.NET publique :93#     GET https://api-v1.source.immo/api/listing/view/{view}/{locale}/items94#   avec les en-têtes x-si-account / x-si-api / x-si-appId (exposés dans la95#   config publique {_configs.json} du site). Pagination par `next_token`.96#   Une sous-classe fournit account_id / api_key / app_id / view_id.97#98#   ENRICHISSEMENT DÉTAIL (fiche complète) : l'endpoint99#     GET .../listing/view/{view}/{locale}/items/ref_number/{ref}100#   retourne TOUT : galerie complète (blob.source.immo, variante -lg) avec101#   étiquettes de pièces, description longue + addendum, ville/secteur résolus102#   (dictionary), taxes et frais (expenses), pièces avec dimensions (rooms),103#   attributs traduits (attribute_value), courtier + téléphone, inclusions/104#   exclusions, lien Centris original. Mise en cache BD (detail_cache) — seules105#   les fiches nouvelles ou modifiées (prix/photo de couverture) sont re-lues.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import os110import re111112from .base import BaseConnector113from ._detailutil import apply_detail114from ..schema import PropertyListing115116API_ROOT = "https://api-v1.source.immo/api"117118# Codes de catégorie source.immo -> vocabulaire brut (finalize() normalise)119_CATEGORY = {120    "RESIDENTIAL": "Maison", "SINGLE-FAMILY": "Maison",121    "MULTI-FAMILY": "Multiplex", "CONDO": "Condo", "APARTMENT": "Condo",122    "LOT": "Terrain", "LAND": "Terrain", "FARM": "Fermette/Agricole",123    "COMMERCIAL": "Commercial", "INDUSTRIAL": "Commercial",124    # codes courts (vus chez groupevalor) : COM/IND, RES, CON…125    "COM": "Commercial", "IND": "Commercial", "RES": "Maison",126    "CON": "Condo", "MF": "Multiplex",127}128_SUBCATEGORY = {129    "2X": "Duplex", "3X": "Triplex", "4X": "Quadruplex", "5X": "Quintuplex",130}131132# « Montréal (Verdun/Île-des-Sœurs) » -> ville + secteur133_CITY_SECTOR_RE = re.compile(r"^(.*?)\s*\((.*)\)\s*$")134135136def _fmt_money(amount) -> str:137    try:138        return f"{float(amount):,.0f} $".replace(",", " ")139    except (TypeError, ValueError):140        return ""141142143def _big(url: str) -> str:144    """Variante grande taille d'une photo blob.source.immo (-sm/-md -> -lg)."""145    return re.sub(r"-(?:sm|md)\.(jpg|jpeg|png|webp)$", r"-lg.\1", url or "")146147148class SourceImmoConnector(BaseConnector):149    """Base : définir source_id, account_id, api_key, app_id, view_id, site_url."""150151    account_id = ""152    api_key = ""153    app_id = ""154    view_id = ""155    site_url = ""156    locale = "fr"157    request_delay = 0.25158    use_detail_cache = True159    max_pages = 400          # garde-fou (100 items/page)160    # fiches détail (re)lues au plus par synchronisation — le cache BD rend les161    # cycles suivants quasi gratuits. IMMOKA_DETAIL_LIMIT pour un rattrapage.162    detail_limit = 400163164    def _headers(self) -> dict:165        return {166            "x-si-account": self.account_id,167            "x-si-api": self.api_key,168            "x-si-appId": self.app_id,169            "Accept": "application/json",170        }171172    def fetch(self) -> list[PropertyListing]:173        url = f"{API_ROOT}/listing/view/{self.view_id}/{self.locale}/items"174        out: list[PropertyListing] = []175        params: dict = {}176        seen: set[str] = set()177        prev_token = None178        for _ in range(self.max_pages):179            try:180                data = self.get(url, headers=self._headers(), params=params).json()181            except Exception:182                break183            items = data.get("items", []) if isinstance(data, dict) else []184            if not items:185                break186            before = len(out)187            for it in items:188                lst = self._to_listing(it)189                if lst and lst.uid not in seen:190                    seen.add(lst.uid)191                    out.append(lst)192            # Pagination source.immo : l'API attend `st` (search_token) + `nt`193            # (next_token) — c'est ce que fait l'app AngularJS. Avec le mauvais194            # nom de paramètre, l'API renvoie toujours la 1re page (faux plafond195            # de 100 items). Avec st+nt, on parcourt tout l'inventaire.196            meta = data.get("metadata") or {}197            token = meta.get("next_token")198            if not token or token == prev_token or len(out) == before:199                break200            prev_token = token201            params = {"st": meta.get("search_token") or "", "nt": token}202        self._enrich_details(out)203        return out204205    # -- fiche détail (galerie complète, taxes, pièces, ville…) ----------------206    def _enrich_details(self, listings: list[PropertyListing]) -> None:207        budget = int(os.environ.get("IMMOKA_DETAIL_LIMIT", self.detail_limit))208        if budget <= 0 or not self.view_id:209            return210        from .. import db211        con = db.connect()212        try:213            for lst in listings:214                # clé de changement : prix + photo de couverture (les fiches215                # modifiées à la source sont re-lues, les autres viennent du cache)216                key = f"v1:{lst.price or ''}:{lst.details.get('cover_thumb', '')}"217                cached = db.get_cached_detail(con, self.source_id,218                                              lst.external_id, key)219                if cached is None:220                    stale = db.get_stale_detail(con, self.source_id, lst.external_id)221                    if budget <= 0:222                        if stale:223                            self._apply(lst, stale)224                        continue225                    try:226                        raw = self.get(227                            f"{API_ROOT}/listing/view/{self.view_id}/"228                            f"{self.locale}/items/ref_number/{lst.external_id}",229                            headers=self._headers()).json()230                        cached = self._detail_payload(raw)231                    except Exception:232                        cached = {}233                    if not cached and stale:234                        # échec transitoire : on garde l'ancien payload235                        self._apply(lst, stale)236                        budget -= 1237                        continue238                    db.put_cached_detail(con, self.source_id, lst.external_id,239                                         key, cached)240                    budget -= 1241                self._apply(lst, cached)242        finally:243            con.close()244245    def _apply(self, lst: PropertyListing, payload: dict) -> None:246        if not payload:247            return248        # ville/secteur résolus par le détail : plus fiables que la liste249        for f in ("city", "sector"):250            if payload.get(f):251                setattr(lst, f, payload[f])252        apply_detail(lst, payload)253254    def _detail_payload(self, d: dict) -> dict:255        """Payload compact (JSON-sérialisable, mis en cache) depuis la fiche API."""256        if not isinstance(d, dict) or not d.get("ref_number"):257            return {}258        dic = d.get("dictionary") or {}259260        def cap(group: str, code) -> str:261            return ((dic.get(group) or {}).get(str(code)) or {}).get("caption", "") \262                if code is not None else ""263264        out: dict = {}265        # -- galerie complète, meilleure résolution, ordre source + étiquettes --266        photos = d.get("photos") or []267        images, captions = [], []268        for p in photos:269            u = _big(p.get("url") or "")270            if u:271                images.append(u)272                captions.append(cap("photo_category", p.get("category_code")))273        if images:274            out["images"] = images275        details: dict = {}276        if any(captions):277            details["photo_captions"] = captions278279        # -- description longue (+ addendum) ------------------------------------280        desc = (d.get("description") or "").strip()281        addendum = (d.get("addendum") or "").strip()282        if addendum and addendum not in desc:283            desc = (desc + "\n\n" + addendum).strip()284        if desc:285            out["description"] = desc286287        # -- localisation précise ------------------------------------------------288        loc = d.get("location") or {}289        addr = loc.get("address") or {}290        street = " ".join(filter(None, [addr.get("street_number"),291                                        addr.get("street_name")])).strip()292        if addr.get("door") and street:293            street = f"{addr['door']}-{street}"294        if street:295            out["address"] = street296        if addr.get("postal_code"):297            details["postal_code"] = addr["postal_code"]298        city_caption = cap("city", loc.get("city_code"))299        if city_caption:300            m = _CITY_SECTOR_RE.match(city_caption)301            if m:302                out["city"], out["sector"] = m.group(1), m.group(2)303            else:304                out["city"] = city_caption305        region = cap("region", loc.get("region_code"))306        if region:307            details["region"] = region308        if loc.get("latitude") and loc.get("longitude"):309            out["lat"], out["lng"] = loc["latitude"], loc["longitude"]310311        # -- pièces/chambres/année/superficies (unité principale) ---------------312        units = d.get("units") or []313        main = next((u for u in units if u.get("category_code") == "MAIN"),314                    units[0] if units else {})315        for src_k, dst_k in (("bedroom_count", "bedrooms"),316                             ("bathroom_count", "bathrooms"),317                             ("waterroom_count", "powder_rooms")):318            if main.get(src_k) is not None:319                out[dst_k] = main[src_k]320        if main.get("room_count"):321            details["Nombre de pièces"] = main["room_count"]322        b = d.get("building") or {}323        if b.get("construction_year"):324            out["year_built"] = b["construction_year"]325        if b.get("total_levels"):326            details["Nombre d'étages"] = b["total_levels"]327        if (b.get("dimension") or {}).get("area_sf"):328            out["area_sqft"] = b["dimension"]["area_sf"]329        land = d.get("land") or {}330        if (land.get("dimension") or {}).get("area_sf"):331            out["lot_sqft"] = land["dimension"]["area_sf"]332333        # -- coûts : taxes, frais, évaluation municipale -------------------------334        _period = {"Y": "an", "M": "mois", "W": "sem."}335        for e in d.get("expenses") or []:336            label = cap("expense_type", e.get("type_code")) or e.get("type_code")337            money = _fmt_money(e.get("amount"))338            if not (label and money):339                continue340            per = _period.get(e.get("period_code") or "", "")341            year = f" ({e['year']})" if e.get("year") else ""342            details[label] = f"{money}/{per}{year}" if per else f"{money}{year}"343        assess = (d.get("assessment") or {}).get("amount") or (344            ((b.get("assessment") or {}).get("amount") or 0)345            + ((land.get("assessment") or {}).get("amount") or 0)) or None346        if assess:347            year = (d.get("assessment") or {}).get("year") or \348                   (b.get("assessment") or {}).get("year")349            details["Évaluation municipale"] = _fmt_money(assess) + (350                f" ({year})" if year else "")351352        # -- inclusions / exclusions / lien original / visites -------------------353        if d.get("inclusions"):354            details["Inclusions"] = str(d["inclusions"])[:600]355        if d.get("exclusions"):356            details["Exclusions"] = str(d["exclusions"])[:600]357        links = d.get("links") or {}358        if links.get("website"):359            details["listing_origin_url"] = links["website"]360        for k, lab in (("virtual_tour", "Visite virtuelle"), ("video", "Vidéo")):361            if links.get(k):362                details[lab] = links[k]363364        # -- caractéristiques traduites (attributs) + pièces ---------------------365        features: list[str] = []366        for a in d.get("attributes") or []:367            group = cap("attribute", a.get("code")) or (a.get("code") or "").title()368            vals = [cap("attribute_value", (v or {}).get("code"))369                    or str((v or {}).get("code") or "")370                    for v in a.get("values") or []]371            vals = [v for v in vals if v]372            if group and vals:373                features.append(f"{group} : {', '.join(vals)}")374        _unit = {"I": "po", "F": "pi", "M": "m"}375        for r in d.get("rooms") or []:376            name = cap("room_category", r.get("category_code"))377            if not name:378                continue379            dim = r.get("dimension") or {}380            w, l = dim.get("width"), dim.get("length")381            u = _unit.get(dim.get("unit_code") or "", "pi")382            size = ""383            if w and l:384                if u == "po":   # dimensions en pouces -> pieds,pouces lisibles385                    size = f" — {int(l // 12)},{int(l % 12)} × {int(w // 12)},{int(w % 12)} pi"386                else:387                    size = f" — {l:g} × {w:g} {u}"388            floor = cap("flooring", r.get("flooring_code"))389            features.append(f"{name}{size}" + (f" ({floor})" if floor else ""))390        if features:391            out["features"] = features392393        # -- courtier inscripteur (nom + téléphone) -------------------------------394        brokers = d.get("brokers") or []395        if brokers:396            bk = brokers[0]397            name = bk.get("name") or " ".join(398                filter(None, [bk.get("first_name"), bk.get("last_name")]))399            phone = next(iter((bk.get("phones") or {}).values()), "")400            if name:401                details["Courtier inscripteur"] = name + (f" — {phone}" if phone else "")402            if phone:403                out["broker_phone"] = phone404        if details:405            out["details"] = details406        return out407408    # -- mapping (item de liste) ------------------------------------------------409    def _to_listing(self, it: dict) -> PropertyListing | None:410        ref = it.get("ref_number") or it.get("id")411        if not ref or not it.get("for_sale_flag", True):412            return None413        if (it.get("status_code") or "").upper() not in ("", "AVAILABLE"):414            return None415416        loc = it.get("location") or {}417        addr = loc.get("address") or {}418        street = " ".join(filter(None, [addr.get("street_number"),419                                        addr.get("street_name")])).strip()420        if addr.get("door") and street:421            street = f"{addr['door']}-{street}"422        price = ((it.get("price") or {}).get("sell") or {}).get("amount")423424        cat = (it.get("category_code") or "").upper()425        sub = (it.get("subcategory_code") or "").upper()426        prop_type = _SUBCATEGORY.get(sub) or _CATEGORY.get(cat, "")427428        unit = it.get("main_unit") or {}429        building = it.get("building") or {}430        dim = building.get("dimension") or {}431        area = dim.get("area_sf")432        land = it.get("land") or {}433        lot = (land.get("dimension") or {}).get("area_sf")434435        photo = it.get("photo_url") or ""436        images = [_big(photo)] if photo else []437438        # caractéristiques disponibles dans l'item (la fiche détail enrichit)439        details = {"postal_code": addr.get("postal_code", "")}440        if photo:441            # miniature légère pour les cartes de liste (mobile) — la galerie442            # pleine taille vient de la fiche détail443            details["cover_thumb"] = photo444        b_ass = (building.get("assessment") or {}).get("amount")445        l_ass = (land.get("assessment") or {}).get("amount")446        if b_ass or l_ass:447            details["Évaluation municipale"] = (448                f"{(b_ass or 0) + (l_ass or 0):,.0f} $".replace(",", " "))449        if unit.get("room_count"):450            details["Nombre de pièces"] = unit["room_count"]451        features = []452        attrs = it.get("attributes") or {}453        if attrs.get("PARKING"):454            features.append("Stationnement")455        if it.get("virtual_tour_flag"):456            features.append("Visite virtuelle")457        if it.get("video_flag"):458            features.append("Vidéo")459460        return PropertyListing(461            source=self.source_id,462            external_id=str(ref),463            url=self._listing_url(it),464            title=street,465            address=street,466            city="",                       # résolu par la fiche détail (dictionary)467            sector="",468            region=str(loc.get("region_code") or ""),469            property_type=prop_type,470            price=float(price) if price is not None else None,471            price_label=(f"{float(price):,.0f} $".replace(",", " ") if price else ""),472            bedrooms=unit.get("bedroom_count"),473            bathrooms=unit.get("bathroom_count"),474            powder_rooms=unit.get("waterroom_count"),475            area_sqft=float(area) if area else None,476            lot_sqft=float(lot) if lot else None,477            year_built=building.get("construction_year"),478            mls=str(ref),479            lat=loc.get("latitude"),480            lng=loc.get("longitude"),481            description=(it.get("description") or "").strip(),482            images=images,483            features=features,484            details=details,485        )486487    def _listing_url(self, it: dict) -> str:488        # URL lisible non essentielle ; on pointe la recherche du site par défaut.489        return self.site_url490
Files main
Menu

Theme