Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/vraiprix.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1214#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 propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# vraiprix.py : estimation de valeur marchande via Vrai-Prix (www.vrai-prix.com)91# Pour chaque annonce : /api/search?q=<adresse> → id de l'unité d'évaluation,92# puis /api/estimate?id → valeur estimée, fourchette P10-P90, indice de93# confiance. Repli : POST /api/estimate (municipalité + type + superficie).94# Résultat stocké dans listings.vraiprix (JSON) + lien vers /estimation/{id}.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import time100import unicodedata101102import requests103104from . import db105106BASE = "https://www.vrai-prix.com"107UA = "ImmoKaBot/1.0 (+https://www.immo-ka.com; contact@spboucher.ai)"108DELAY = 0.25 # politesse109110# type Immo-Ka -> typeProp Vrai-Prix (repli manuel)111_TYPE_MAP = {112 "Maison": "unifamilial", "Condo": "condo", "Duplex": "plex",113 "Triplex": "plex", "Multiplex": "plex", "Jumelé": "unifamilial",114 "Maison de ville": "unifamilial", "Chalet": "unifamilial",115 "Fermette/Agricole": "unifamilial", "Maison mobile": "unifamilial",116}117118119def _norm(s: str) -> str:120 return "".join(c for c in unicodedata.normalize("NFD", (s or "").lower())121 if unicodedata.category(c) != "Mn").strip()122123124def _session() -> requests.Session:125 s = requests.Session()126 s.headers["User-Agent"] = UA127 return s128129130def _search_id(s: requests.Session, address: str, city: str) -> str | None:131 """Retourne l'id de l'unité Vrai-Prix la mieux appariée à l'adresse."""132 q = f"{address}, {city}".strip(", ")133 if len(q) < 4:134 return None135 try:136 r = s.get(f"{BASE}/api/search", params={"q": q}, timeout=20)137 results = r.json().get("results", [])138 except Exception:139 return None140 if not results:141 return None142 ncity = _norm(city)143 # préférer une correspondance de municipalité, sinon le 1er144 for res in results:145 if ncity and _norm(res.get("municipalite", "")) == ncity:146 return res.get("id")147 return results[0].get("id")148149150def _estimate_by_id(s: requests.Session, uid: str) -> dict | None:151 try:152 r = s.get(f"{BASE}/api/estimate", params={"id": uid}, timeout=25)153 return r.json()154 except Exception:155 return None156157158def _pack(unit_id: str, result: dict) -> dict:159 """Champs conservés pour l'affichage sur la fiche Immo-Ka."""160 return {161 "id": unit_id,162 "value": result.get("estimate"),163 "low": result.get("low"),164 "high": result.get("high"),165 "confidence_pct": result.get("confidencePct"),166 "confidence": result.get("confidenceLevel"),167 "url": f"{BASE}/estimation/{unit_id}",168 }169170171def estimate_for(s: requests.Session, address: str, city: str) -> dict | None:172 uid = _search_id(s, address, city)173 if not uid:174 return None175 data = _estimate_by_id(s, uid)176 if not data or not isinstance(data.get("result"), dict):177 return None178 return _pack(uid, data["result"])179180181def run(limit: int | None = None) -> dict:182 """Enrichit les annonces sans estimation Vrai-Prix (adresse requise)."""183 con = db.connect()184 s = _session()185 rows = con.execute(186 "SELECT uid, address, city FROM listings"187 " WHERE active=1 AND vraiprix IS NULL AND address<>''"188 " ORDER BY first_seen DESC").fetchall()189 done = miss = 0190 for r in rows:191 if limit is not None and done + miss >= limit:192 break193 est = estimate_for(s, r["address"], r["city"])194 # on marque toujours (même un échec) pour ne pas re-sonder sans cesse ;195 # « {} » = tenté sans correspondance.196 con.execute("UPDATE listings SET vraiprix=? WHERE uid=?",197 (json.dumps(est or {}, ensure_ascii=False), r["uid"]))198 con.commit()199 if est:200 done += 1201 else:202 miss += 1203 time.sleep(DELAY)204 con.close()205 out = {"estimated": done, "no_match": miss}206 print(f"[immo-ka] vraiprix: {out}")207 return out208