Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/lights.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-11-2513# Last Modified : 2026-11-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 propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# lights.py : « lumières » de la carte d'accueil — densité des propriétés à91# vendre par cellule d'environ 1 km, et principales villes. Réponse compacte,92# mise en cache : l'accueil n'a pas à charger chaque inscription.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import json97import threading98import time99from pathlib import Path100101from . import db, villes102from .public import PRICE_MAX, PRICE_MIN, PUBLIC, QC_BOUNDS103104SOURCES_PATH = Path(__file__).resolve().parent.parent / "data" / "sources.json"105106_TTL = 600107_CACHE: dict = {"ts": 0.0, "data": None}108_LOCK = threading.Lock()109110_BASE = (f"FROM listings WHERE {PUBLIC}"111 f" AND lat IS NOT NULL AND lng IS NOT NULL AND {QC_BOUNDS}")112113114def _build() -> dict:115 con = db.connect()116 try:117 cells = [[r["x"], r["y"], r["n"], round(r["p"]) if r["p"] else None]118 for r in con.execute(119 f"""SELECT ROUND(lng, 2) x, ROUND(lat, 2) y, COUNT(*) n,120 AVG(CASE WHEN price BETWEEN {PRICE_MIN} AND {PRICE_MAX}121 THEN price END) p122 {_BASE} GROUP BY x, y""")]123 # principales villes — villes normalisées (immoka/villes.py) : les124 # écritures d'une même ville sont fusionnées, les zones des petites125 # annonces et les régions publiées comme « ville » n'en sont pas126 by_label = villes.index()["by_label"]127 top = sorted(((lab, e) for lab, e in by_label.items() if e["lat"] is not None),128 key=lambda kv: -kv[1]["n"])[:24]129 raw_to_lab = {raw: lab for lab, e in top for raw in e["raws"]}130 prices: dict[str, list] = {lab: [] for lab, _ in top}131 if raw_to_lab:132 marks = ",".join("?" * len(raw_to_lab))133 for p in con.execute(134 f"SELECT city, price FROM listings WHERE {PUBLIC}"135 f" AND city IN ({marks})"136 f" AND price BETWEEN {PRICE_MIN} AND {PRICE_MAX} ORDER BY price",137 list(raw_to_lab)):138 prices[raw_to_lab[p["city"]]].append(p["price"])139 cities = [{"city": lab, "n": e["n"], "lng": e["lng"], "lat": e["lat"],140 "median": (round(prices[lab][len(prices[lab]) // 2])141 if prices[lab] else None)}142 for lab, e in top]143 total = con.execute(144 f"SELECT COUNT(*) c FROM listings WHERE {PUBLIC}").fetchone()["c"]145 positioned = con.execute(f"SELECT COUNT(*) c {_BASE}").fetchone()["c"]146 finally:147 con.close()148 return {"cells": cells, "cities": cities, "total": total,149 "positioned": positioned, "cell_deg": 0.01}150151152def compute() -> dict:153 cached = _CACHE["data"]154 if cached is not None and time.time() - _CACHE["ts"] < _TTL:155 return cached156 if not _LOCK.acquire(blocking=cached is None):157 return cached158 try:159 cached = _CACHE["data"]160 if cached is not None and time.time() - _CACHE["ts"] < _TTL:161 return cached162 data = _build()163 _CACHE.update(ts=time.time(), data=data)164 return data165 finally:166 _LOCK.release()167168169_NAMES: dict = {"mtime": 0.0, "data": {}}170171# connecteurs générés depuis d'autres registres (RE/MAX, Via Capitale,172# Century 21, Source Immo, agences web) : nom lu sur la classe du connecteur173_FAMILY = (("remax_ag_", "RE/MAX "), ("via_ag_", "Via Capitale "),174 ("c21_ag_", "Century 21 "), ("kw_", "Keller Williams "))175176177def _fallback_name(sid: str) -> str:178 for prefix, label in _FAMILY:179 if sid.startswith(prefix):180 return label + sid[len(prefix):].replace("_", " ").title()181 return sid.replace("_ag_", " ").replace("_", " ").title()182183184def source_names() -> dict[str, str]:185 """Identifiant de source → nom lisible (relu si sources.json change).186187 Couvre le registre data/sources.json ET les sources présentes en base qui188 n'y figurent pas (sous-agences générées) : aucun identifiant brut ne doit189 s'afficher sur une carte d'inscription."""190 mtime = SOURCES_PATH.stat().st_mtime191 if mtime != _NAMES["mtime"] or time.time() - _NAMES.get("ts", 0) > 3600:192 names = {s["id"]: s.get("name") or s["id"] for s in193 json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]}194 con = db.connect()195 try:196 rows = con.execute(197 f"""SELECT source, MAX(NULLIF(agency,'')) agency,198 COUNT(DISTINCT NULLIF(agency,'')) k199 FROM listings WHERE active=1 GROUP BY source""").fetchall()200 finally:201 con.close()202 for r in rows:203 if r["source"] not in names:204 names[r["source"]] = (r["agency"] if r["k"] == 1 and r["agency"]205 else _fallback_name(r["source"]))206 _NAMES.update(data=names, mtime=mtime, ts=time.time())207 return _NAMES["data"]208