SPB Git

Repository Public

_detailutil.py 14.0 KB 345 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/_detailutil.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/_detailutil.py : utilitaires partagés d'enrichissement « page détail »91#   Mutualise ce que les connecteurs de portails répètent pour capter TOUTES les92#   infos de la fiche source : description JSON-LD, coordonnées, application93#   au Listing avec cache BD et budget de requêtes par synchronisation.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import html as _html98import json99import re100101from ..schema import Listing102103_LD_RE = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.S | re.I)104_COORD_RE = re.compile(r'(?:google\.[^"\']*?[?&](?:q|query|ll|center)=|maps/@)'105                       r'(-?\d{1,2}\.\d+)[ ,%+A-Za-z]+?(-?\d{2,3}\.\d+)')106_LD_PROP_TYPES = {"RealEstateListing", "Residence", "SingleFamilyResidence",107                  "House", "Apartment", "Product", "Offer", "Place", "Accommodation"}108109110def ld_nodes(html: str):111    """Itère les objets JSON-LD (aplatis depuis @graph)."""112    for block in _LD_RE.findall(html):113        try:114            data = json.loads(block)115        except ValueError:116            continue117        graph = data.get("@graph", [data]) if isinstance(data, dict) else data118        for node in (graph if isinstance(graph, list) else [graph]):119            if isinstance(node, dict):120                yield node121122123def ld_description(html: str) -> str:124    """Description depuis un nœud JSON-LD de type propriété (le plus long trouvé)."""125    best = ""126    for n in ld_nodes(html):127        t = n.get("@type")128        types = t if isinstance(t, list) else [t]129        if any(x in _LD_PROP_TYPES for x in types) and n.get("description"):130            d = _html.unescape(str(n["description"])).strip()131            if len(d) > len(best):132                best = d133    return best134135136# plateformes de visite virtuelle reconnues dans le HTML d'une fiche137_VTOUR_RE = re.compile(138    r'https?://(?:my\.)?(?:matterport\.com/show/[^"\'\s<>]+'139    r'|(?:www\.)?youriguide\.com/[^"\'\s<>]+'140    r'|(?:www\.)?klapty\.com/tour/[^"\'\s<>]+'141    r'|kuula\.co/(?:share|post)/[^"\'\s<>]+'142    r'|tours?\.[a-z0-9-]+\.(?:com|ca)/[^"\'\s<>]*(?:tour|visite)[^"\'\s<>]*'143    r'|(?:www\.)?realvision\.com/[^"\'\s<>]+)', re.I)144145146def virtual_tour(html: str) -> str | None:147    """Première URL de visite virtuelle (Matterport, iGUIDE, Klapty, Kuula…)148    trouvée dans le HTML d'une fiche. None si absente — jamais inventée."""149    m = _VTOUR_RE.search(html or "")150    if not m:151        return None152    return _html.unescape(m.group(0)).replace("\\/", "/").rstrip("\\").rstrip('&')153154155def gmaps_coords(html: str) -> tuple[float, float] | None:156    m = _COORD_RE.search(html)157    if not m:158        return None159    try:160        lat, lng = float(m.group(1)), float(m.group(2))161    except ValueError:162        return None163    if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:164        return lat, lng165    return None166167168def flatten(html: str) -> str:169    """HTML -> texte « valeur | libellé » pour extraire les tableaux de fiches."""170    t = _html.unescape(re.sub(r"<[^>]+>", " | ", html))171    t = re.sub(r"[ \t\r\n]*\|[ \t\r\n|]*", " | ", t)172    return re.sub(r"[ \t]+", " ", t)173174175# libellés Centris standard (fiches de courtiers) cherchés dans un texte aplati176# « valeur | libellé » OU « libellé | valeur » — version location177_LABELS = [178    "Type de propriété", "Genre de propriété", "Style de bâtiment",179    "Année de construction", "Superficie habitable", "Superficie du terrain",180    "Nombre de pièces", "Nombre d'unités", "Stationnement (total)",181    "Stationnement", "Garage", "Système de chauffage",182    "Énergie pour le chauffage", "Piscine", "Déménagement", "Date d'emménagement",183    "Disponibilité", "Bail", "Durée du bail", "Meublé", "Animaux",184    "Inclus dans le loyer", "Cuisine",185]186187188def centris_details(text: str) -> dict:189    """Extrait les caractéristiques Centris d'un texte aplati (les deux ordres)."""190    out: dict = {}191    for label in _LABELS:192        lab = re.escape(label)193        m = (re.search(r"([^|]{1,55})\s*\|\s*" + lab + r"\b", text)194             or re.search(lab + r"\b\s*\|\s*([^|]{1,55})", text))195        if m:196            val = m.group(1).strip(" |")197            if val and 1 <= len(val) <= 55 and val.lower() != label.lower():198                out[label] = val199    return out200201202def enrich(connector, listings, limit, parse_fn, key="v1", fetch_html=None):203    """Enrichit `listings` via leur page détail, avec cache BD + plafond `limit`.204205    - `parse_fn(html) -> dict` : extrait les champs riches d'une page détail.206    - `key` : versionne le cache (changer pour forcer un rafraîchissement).207    - `fetch_html(url) -> str` : par défaut connector.get(url).text ; passer208      connector.get_rendered / get_scrapfly pour les sites derrière anti-bot.209    Le budget `limit` fait que chaque sync n'enrichit qu'un quota de fiches ;210    le parc se complète sur plusieurs cycles (le cache est permanent tant que211    la clé ne change pas).212    """213    if limit <= 0:214        return215    from .. import db216    fetch_html = fetch_html or (lambda u: connector.get(u).text)217    con = db.connect()218    budget = limit219    try:220        for lst in listings:221            cached = db.get_cached_detail(con, connector.source_id, lst.external_id, key)222            if cached is None:223                if budget <= 0:224                    continue225                try:226                    cached = parse_fn(fetch_html(lst.url))227                except Exception:228                    cached = {}229                db.put_cached_detail(con, connector.source_id, lst.external_id, key, cached)230                budget -= 1231            apply_detail(lst, cached)232    finally:233        con.close()234235236class TtlDetailCache:237    """Cache BD des pages détail AVEC durée de vie, pour les portails où la238    fiche est la seule source de données (LogisQuébec, DuProprio…).239240    Contrairement à enrich() (cache permanent tant que la clé ne change pas),241    chaque fiche est re-visitée après `ttl_days` pour capter les changements242    de prix/disponibilité — dans la limite de `budget` requêtes par243    synchronisation. Budget épuisé : le payload périmé est réutilisé tel quel244    (jamais de trou de données) ; une fiche jamais visitée retourne None et245    sera captée à une synchronisation suivante.246    """247248    def __init__(self, connector, budget: int, ttl_days: float = 7.0,249                 key: str = "v1", fetch_html=None) -> None:250        from .. import db251        self.connector = connector252        self.con = db.connect()253        self.budget = budget254        self.ttl = ttl_days * 86400255        self.key = key256        self.fetch_html = fetch_html or (lambda u: connector.get(u).text)257258    def peek(self, external_id: str) -> tuple[dict | None, bool]:259        """(payload en cache, frais ?) SANS déclencher de requête ni toucher260        au budget — permet aux connecteurs de planifier des lots parallèles."""261        import time as _time262        row = self.con.execute(263            "SELECT key, payload, fetched_at FROM detail_cache"264            " WHERE source=? AND external_id=?",265            (self.connector.source_id, str(external_id))).fetchone()266        stale = None267        if row and row["payload"]:268            try:269                stale = json.loads(row["payload"])270            except ValueError:271                stale = None272            if (stale is not None and row["key"] == self.key273                    and _time.time() - (row["fetched_at"] or 0) < self.ttl):274                return stale, True               # frais : aucun trafic requis275        return stale, False276277    def put(self, external_id: str, payload: dict) -> None:278        """Écrit un payload obtenu hors de get() (ex. téléchargement en lot)."""279        from .. import db280        db.put_cached_detail(self.con, self.connector.source_id,281                             str(external_id), self.key, payload)282283    def get(self, external_id: str, url: str, parse_fn) -> dict | None:284        from .. import db285        stale, fresh = self.peek(external_id)286        if fresh:287            return stale                         # frais : aucun trafic288        if self.budget <= 0:289            return stale                         # périmé toléré / None si jamais vu290        self.budget -= 1291        try:292            payload = parse_fn(self.fetch_html(url)) or {}293        except Exception as exc:                 # 404/410 = fiche retirée294            code = getattr(getattr(exc, "response", None), "status_code", None)295            if code in (404, 410):296                payload = {"gone": True}297            else:298                return stale                     # erreur réseau : on garde l'ancien299        db.put_cached_detail(self.con, self.connector.source_id,300                             str(external_id), self.key, payload)301        return payload302303    def close(self) -> None:304        try:305            self.con.close()306        except Exception:307            pass308309310def apply_detail(lst: Listing, d: dict) -> None:311    """Applique un payload détail au Listing sans écraser les valeurs déjà312    présentes (sauf images : on garde la plus grande galerie)."""313    if not d:314        return315    imgs = d.get("images")316    if imgs and len(imgs) > len(lst.images):317        lst.images = imgs318    if d.get("amenities"):319        seen = {a.lower() for a in lst.amenities}320        for a in d["amenities"]:321            if a.lower() not in seen:322                lst.amenities.append(a)323                seen.add(a.lower())324    if d.get("details"):325        merged = dict(d["details"])326        merged.update(lst.details)      # les valeurs du connecteur priment327        lst.details = merged328    # description : on garde la plus riche (la fiche détail bat le résumé liste)329    if d.get("description") and len(d["description"]) > len(lst.description or ""):330        lst.description = d["description"]331    for f in ("price_label", "address", "city", "sector", "unit_type",332              "availability", "title"):333        if d.get(f) and not getattr(lst, f, ""):334            setattr(lst, f, d[f])335    for f in ("price", "area_sqft", "lat", "lng", "availability_date",336              "pets", "furnished"):337        if d.get(f) is not None and getattr(lst, f, None) is None:338            setattr(lst, f, d[f])339    from ..normalize import coerce_count340    for f in ("bedrooms", "bathrooms"):341        if d.get(f) is not None and getattr(lst, f, None) is None:342            setattr(lst, f, coerce_count(d[f]))343    if d.get("virtual_tour") and not lst.details.get("virtual_tour"):344        lst.details["virtual_tour"] = d["virtual_tour"]345
Files main
Menu

Theme