SPB Git

Repository Public

recycled.py 10.7 KB 272 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/recycled.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#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# recycled.py : détection des annonces RECYCLÉES — le même logement republié91#               (souvent plus cher) après un passage antérieur sur le marché.92#93# Méthode : les candidates sont les annonces INACTIVES du même immeuble94# (building_key — même clé d'adresse que la déduplication). Chaque paire reçoit95# un score de similarité 0–100 fondé sur des signaux indépendants :96#   numéro d'unité identique, type d'unité, chambres, superficie (±3 %),97#   photos identiques (hash SHA1 du contrôle d'images), texte de description98#   (similarité de Jaccard sur les mots).99# Seules les correspondances ≥ SEUIL_AFFICHAGE sont retournées, avec les100# signaux qui les fondent (inférence explicable, jamais de fusion automatique).101# Cache : table recycled_cache (TTL 7 jours — recalcul léger, borné à102# l'immeuble).103# -----------------------------------------------------------------------------104from __future__ import annotations105106import json107import re108import time109110from . import db111112TTL = 7 * 86400113SEUIL_AFFICHAGE = 70     # score minimal pour présenter une correspondance114MAX_CANDIDATES = 200     # garde-fou (tours à très fort volume)115116_WORD = re.compile(r"[a-zà-ÿ0-9]{3,}")117118119def _tokens(text: str | None) -> set[str]:120    return set(_WORD.findall((text or "").lower()))121122123def _jaccard(a: set[str], b: set[str]) -> float:124    if not a or not b:125        return 0.0126    return len(a & b) / len(a | b)127128129def _sha1_set(con, images_json: str | None) -> set[str]:130    try:131        urls = json.loads(images_json or "[]")[:20]132    except (ValueError, TypeError):133        return set()134    if not urls:135        return set()136    marks = ",".join("?" * len(urls))137    return {r["sha1"] for r in con.execute(138        f"SELECT sha1 FROM image_checks WHERE url IN ({marks})"139        " AND sha1 IS NOT NULL", urls)}140141142def _unit_of(address: str | None, city: str | None) -> str | None:143    from .dedup import _parse_address144    return _parse_address(address or "", city or "")[1]145146147def _score(con, cur: dict, cand: dict) -> tuple[int, list[str]]:148    """Score 0–100 + signaux lisibles justifiant la correspondance."""149    score = 0150    signals: list[str] = []151    if cur["unit"] and cand["unit"]:152        if cur["unit"] == cand["unit"]:153            score += 35154            signals.append(f"même numéro d'unité ({cur['unit']})")155        else:156            return 0, []          # unités connues et différentes : pas le même157    if cur["unit_type"] and cand["unit_type"]:158        if cur["unit_type"] == cand["unit_type"]:159            score += 10160            signals.append(f"même type ({cur['unit_type']})")161        else:162            return 0, []163    if cur["bedrooms"] is not None and cand["bedrooms"] is not None:164        if cur["bedrooms"] == cand["bedrooms"]:165            score += 8166            signals.append("même nombre de chambres")167        else:168            return 0, []169    if cur["area"] and cand["area"]:170        if abs(cur["area"] - cand["area"]) <= 0.03 * max(cur["area"], cand["area"]):171            score += 15172            signals.append(f"même superficie (≈{round(cand['area'])} pi²)")173        else:174            score -= 10175    # photos identiques (hash du contenu, pas l'URL)176    sh_cur = _sha1_set(con, cur["images"])177    sh_cand = _sha1_set(con, cand["images"])178    if sh_cur and sh_cand:179        overlap = len(sh_cur & sh_cand) / min(len(sh_cur), len(sh_cand))180        if overlap >= 0.5:181            score += 30182            signals.append(f"{len(sh_cur & sh_cand)} photo(s) identique(s)")183        elif overlap > 0:184            score += 12185            signals.append("photos partiellement identiques")186    # texte de description187    jac = _jaccard(_tokens(cur["description"]), _tokens(cand["description"]))188    if jac >= 0.7:189        score += 20190        signals.append("description quasi identique")191    elif jac >= 0.45:192        score += 10193        signals.append("description très similaire")194    # même source + même identifiant externe = republication certaine195    if cur["source"] == cand["source"]:196        score += 5197    return min(100, score), signals198199200def lookup(uid: str, con=None) -> dict:201    """Correspondances probables (annonces antérieures du même logement)."""202    own = con is None203    if own:204        con = db.connect()205    try:206        cached = con.execute(207            "SELECT matches, computed_at FROM recycled_cache WHERE uid=?",208            (uid,)).fetchone()209        if cached and time.time() - cached["computed_at"] < TTL:210            return json.loads(cached["matches"])211212        cur = con.execute(213            "SELECT uid, source, address, city, unit_type, bedrooms, price,"214            " area_sqft AS area, description, images, first_seen, building_key,"215            " dup_of FROM listings WHERE uid=?", (uid,)).fetchone()216        out: dict = {"matches": [], "statut": "inferred",217                     "methode": ("similarité multi-signaux (unité, type, "218                                 "chambres, superficie, photos par hash, "219                                 "texte) parmi les annonces antérieures du "220                                 "même immeuble")}221        if cur is None or not cur["building_key"]:222            _store(con, uid, out)223            return out224        cur_d = dict(cur)225        cur_d["unit"] = _unit_of(cur["address"], cur["city"])226227        # exclure le groupe de doublons inter-sources courant (même annonce)228        dup_group = {uid, cur["dup_of"] or ""}229        for r in con.execute("SELECT uid FROM listings WHERE dup_of=?", (uid,)):230            dup_group.add(r["uid"])231232        cands = con.execute(233            "SELECT uid, source, address, city, unit_type, bedrooms, price,"234            " area_sqft AS area, description, images, first_seen, last_seen"235            " FROM listings WHERE building_key=? AND active=0 AND uid<>?"236            " ORDER BY last_seen DESC LIMIT ?",237            (cur["building_key"], uid, MAX_CANDIDATES)).fetchall()238        matches = []239        for c in cands:240            if c["uid"] in dup_group:241                continue242            # une annonce antérieure = terminée avant l'apparition de l'actuelle243            if (c["last_seen"] or 0) > (cur["first_seen"] or 0) + 7 * 86400:244                continue245            cd = dict(c)246            cd["unit"] = _unit_of(c["address"], c["city"])247            score, signals = _score(con, cur_d, cd)248            if score >= SEUIL_AFFICHAGE:249                matches.append({250                    "uid": c["uid"], "source": c["source"],251                    "prix": c["price"], "unit_type": c["unit_type"],252                    "derniere_observation": c["last_seen"],253                    "premiere_observation": c["first_seen"],254                    "confiance": score, "signaux": signals,255                })256        matches.sort(key=lambda m: -m["confiance"])257        out["matches"] = matches[:5]258        _store(con, uid, out)259        return out260    finally:261        if own:262            con.close()263264265def _store(con, uid: str, out: dict) -> None:266    con.execute(267        "INSERT INTO recycled_cache (uid, matches, computed_at) VALUES (?,?,?)"268        " ON CONFLICT(uid) DO UPDATE SET matches=excluded.matches,"269        " computed_at=excluded.computed_at",270        (uid, json.dumps(out, ensure_ascii=False), time.time()))271    con.commit()272
Files main
Menu

Theme