SPB Git

Repository Public

vraiprix_local.py 10.6 KB 259 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : vraiprix_local.py10# Repository       : https://git.spboucher.ai/immo-ka11# Created          : 2026-08-1712# Last Modified    : 2026-08-1713#14# =============================================================================15# AUTHOR & PROFESSIONAL AFFILIATION16# =============================================================================17#18# Author           : Simon-Pierre Boucher19# Position         : Professor of Finance20# Institution      : Université du Québec en Outaouais (UQO)21# Department       : Département des sciences administratives22# Organization     : SP Boucher23#24# Website          : https://spboucher.ai25# Git              : https://git.spboucher.ai26#27# =============================================================================28# OFFICIAL CONTACT DIRECTORY29# =============================================================================30#31# General          : info@spboucher.ai32# Professional     : contact@spboucher.ai33# Direct           : simon@spboucher.ai34# Research         : research@spboucher.ai35# Development      : dev@spboucher.ai36# Support          : support@spboucher.ai37# Security/Admin   : admin@spboucher.ai38# Notifications    : notifications@spboucher.ai39#40# Preferred Contact: contact@spboucher.ai41#42# =============================================================================43# COPYRIGHT & INTELLECTUAL PROPERTY44# =============================================================================45#46# Copyright (c) 202647# Simon-Pierre Boucher48#49# All rights reserved where applicable.50#51# This file is governed by the applicable project license,52# copyright notices, institutional agreements and relevant law.53#54# Unless expressly authorized by the applicable license or55# rights holder, copying, redistribution, sublicensing,56# publication and commercial exploitation are not permitted.57#58# Existing third-party rights and notices remain unaffected.59#60# =============================================================================61# CONFIDENTIALITY & SECURITY62# =============================================================================63#64# Classification   : Public65# Distribution     : Public repository; use is governed by the project license66# Security Contact : admin@spboucher.ai67#68# Access to this source does not independently grant permission69# to redistribute or disclose confidential materials.70#71# Do not embed credentials, private keys, access tokens,72# certificates or confidential personal information.73#74# =============================================================================75# LICENSE & MAINTENANCE76# =============================================================================77#78# License          : None specified (no license file in this repository)79# Maintainer       : Simon-Pierre Boucher80# Technical Contact: dev@spboucher.ai81#82# =============================================================================83# END OF SP BOUCHER SOURCE HEADER84# =============================================================================8586# -----------------------------------------------------------------------------87# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)88# Auteur : Simon-Pierre Boucher — contact@spboucher.ai89# vraiprix_local.py : appariement LOCAL contre la base Vrai-Prix (vraiprix.db,90#   3,7 M unités d'évaluation avec adresse, lat/lng, estimation, fourchette).91#   Une jointure d'adresse (FTS) par annonce → remplit d'un coup :92#     · lat/lng manquants (géocodage instantané, sans API externe)93#     · l'estimation Vrai-Prix (valeur + P10-P90 + lien /estimation/{id})94#   Bien plus rapide que l'API vrai-prix (une requête réseau par annonce).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import os100import re101import sqlite3102import time103import unicodedata104105from . import db106107# Emplacement de la base Vrai-Prix (copiée à côté de immoka.db sur le nœud).108VP_DB = os.environ.get(109    "VRAIPRIX_DB",110    str((__import__("pathlib").Path(__file__).resolve().parent.parent111         / "data" / "vraiprix.db")))112SITE = "https://www.vrai-prix.com"113_BBOX = (44.5, 63.0, -80.0, -56.0)   # Québec114115116def _norm(s: str) -> str:117    return "".join(c for c in unicodedata.normalize("NFD", (s or "").lower())118                   if unicodedata.category(c) != "Mn").strip()119120121# mots de « type de voie » ignorés dans l'appariement (variabilité rue/av/boul…)122_VOIE = {"rue", "av", "ave", "avenue", "boul", "boulevard", "ch", "chemin",123         "place", "pl", "rang", "montee", "montée", "cote", "côte", "route",124         "rte", "terrasse", "impasse", "croissant", "cours", "allee", "allée",125         "de", "du", "des", "la", "le", "les", "l", "d", "st", "ste", "saint",126         "sainte"}127128129def _street_words(norm_addr: str) -> set:130    """Mots significatifs de la rue (sans n° civique, type de voie, n° d'app.)."""131    a = re.sub(r"\b(?:app?t?|appartement|unite|suite|local|bureau|#)\s*[\w-]+", " ",132               norm_addr.split(",")[0])133    a = re.sub(r"[^a-z0-9 ]+", " ", a)134    toks = [t for t in a.split() if t]135    return {t for t in toks if not t.isdigit() and t not in _VOIE and len(t) > 1}136137138def _fts_query(address: str) -> tuple[str, str]:139    """Construit une requête FTS AND (n° civique + mots significatifs de la rue,140    sans le type de voie ni le n° d'appartement) + retourne le civique."""141    a = _norm(address).split(",")[0]142    a = re.sub(r"\b(?:app?t?|appartement|unite|suite|local|bureau|#)\s*[\w-]+", " ", a)143    a = re.sub(r"[^a-z0-9 ]+", " ", a)144    toks = [t for t in a.split() if t]145    civ = toks[0] if toks and toks[0].isdigit() else ""146    words = [t for t in toks if t != civ and t not in _VOIE and len(t) > 1]147    parts = ([civ] if civ else []) + words148    if not parts:149        return "", civ150    return " AND ".join(f'"{p}"' for p in parts), civ151152153def available() -> bool:154    return os.path.exists(VP_DB)155156157def _match(vp: sqlite3.Connection, address: str, city: str) -> dict | None:158    """Meilleure unité Vrai-Prix pour (adresse, ville)."""159    # n° civique + mots significatifs de la rue (AND), filtre municipalité160    q, civ = _fts_query(address)161    if not q:162        return None163    try:164        rows = vp.execute(165            "SELECT u.id_provinc, u.adresse, u.municipalite, u.lat, u.lng,"166            " u.est_hedo, u.est_2026, u.p10, u.p90"167            " FROM units_fts f JOIN units u ON u.rowid=f.rowid"168            " WHERE units_fts MATCH ? LIMIT 25", (q,)).fetchall()169    except sqlite3.OperationalError:170        return None171    if not rows:172        return None173    # VALIDATION STRICTE : on n'accepte QUE si même adresse — n° civique174    # identique + au moins un mot de rue en commun + même municipalité. Sinon175    # PAS de match (mieux vaut aucune estimation qu'une mauvaise).176    iwords = _street_words(_norm(address))177    nc = _norm(city).split()[0] if city else ""178179    def _accept(r) -> bool:180        ua = _norm(r["adresse"])181        m = re.match(r"\s*(\d+)", ua)182        if not civ or not m or m.group(1) != civ:      # même n° civique183            return False184        uwords = _street_words(ua)185        if iwords and not (iwords & uwords):            # mot de rue commun186            return False187        um = _norm(r["municipalite"] or "")188        if nc and um and nc not in um and um.split()[0] not in _norm(city):189            return False                                # même municipalité190        return True191192    best = next((r for r in rows if _accept(r)), None)193    if best is None:194        return None195    lat, lng = best["lat"], best["lng"]196    val = best["est_hedo"] or best["est_2026"]197    return {198        "id": best["id_provinc"], "lat": lat, "lng": lng,199        "value": val, "low": best["p10"], "high": best["p90"],200        "confidence": None, "confidence_pct": None,201        "url": f"{SITE}/estimation/{best['id_provinc']}",202    }203204205def run(limit: int | None = None, revalidate: bool = False) -> dict:206    """Apparie les annonces à la base Vrai-Prix : remplit lat/lng (si manquant)207    et l'estimation. `limit` borne le nombre d'annonces traitées.208    `revalidate=True` : re-vérifie AUSSI les annonces déjà appariées (corrige les209    mauvais merges après durcissement du matcher)."""210    if not available():211        print(f"[immo-ka] vraiprix_local: base absente ({VP_DB})")212        return {"error": "vraiprix.db absent"}213    vp = sqlite3.connect(f"file:{VP_DB}?mode=ro", uri=True)214    vp.row_factory = sqlite3.Row215    con = db.connect()216    where = ("active=1 AND dup_hidden=0 AND address<>''" if revalidate217             else "active=1 AND dup_hidden=0 AND address<>''"218                  " AND (vraiprix IS NULL OR vraiprix='{}')")219    rows = con.execute(220        f"SELECT uid, address, city, lat FROM listings WHERE {where}"221        " ORDER BY first_seen DESC").fetchall()222    if limit is not None:223        rows = rows[:limit]224225    matched = geoloc = miss = 0226    for i, r in enumerate(rows):227        m = _match(vp, r["address"], r["city"])228        try:229            if m and m["value"]:230                est = {k: m[k] for k in ("id", "value", "low", "high",231                                         "confidence", "confidence_pct", "url")}232                con.execute("UPDATE listings SET vraiprix=? WHERE uid=?",233                            (json.dumps(est, ensure_ascii=False), r["uid"]))234                # géocodage gratuit : coordonnées de l'unité si l'annonce n'en a pas235                if (r["lat"] is None and m["lat"] is not None236                        and _BBOX[0] <= m["lat"] <= _BBOX[1]237                        and _BBOX[2] <= m["lng"] <= _BBOX[3]):238                    con.execute("UPDATE listings SET lat=?, lng=? WHERE uid=?",239                                (m["lat"], m["lng"], r["uid"]))240                    geoloc += 1241                matched += 1242            else:243                con.execute("UPDATE listings SET vraiprix='{}' WHERE uid=?", (r["uid"],))244                miss += 1245            if i % 200 == 0:246                con.commit()247        except sqlite3.OperationalError:248            try:249                con.rollback()250            except sqlite3.Error:251                pass252            time.sleep(1.0)253    con.commit()254    con.close()255    vp.close()256    out = {"matched": matched, "geolocated": geoloc, "no_match": miss}257    print(f"[immo-ka] vraiprix_local {out}")258    return out259
Files main
Menu

Theme