SPB Git

Repository Public

lights.py 3.2 KB 84 lines python

1# -----------------------------------------------------------------------------2# Lou-Ka — Agrégateur de logements à louer (province de Québec)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# lights.py : « lumières » de la carte d'accueil — densité des logements5# disponibles par cellule d'environ 100 m, et principales villes. Réponse6# compacte, mise en cache : l'accueil n'a pas à charger chaque annonce.7# -----------------------------------------------------------------------------8from __future__ import annotations910import json11import threading12import time13from pathlib import Path1415from . import db1617SOURCES_PATH = Path(__file__).resolve().parent.parent / "data" / "sources.json"18PRICE_MIN, PRICE_MAX = 195, 150001920_TTL = 60021_CACHE: dict = {"ts": 0.0, "data": None}22_LOCK = threading.Lock()2324# emprise du Québec habité : écarte les coordonnées aberrantes25_BOUNDS = "lat BETWEEN 44.9 AND 53.5 AND lng BETWEEN -80.0 AND -57.0"26_BASE = ("FROM listings WHERE active=1 AND published=1 AND dup_of IS NULL"27         f" AND lat IS NOT NULL AND lng IS NOT NULL AND {_BOUNDS}")282930def _build() -> dict:31    con = db.connect()32    try:33        cells = [[r["x"], r["y"], r["n"], round(r["p"]) if r["p"] else None]34                 for r in con.execute(35                     f"""SELECT ROUND(lng, 3) x, ROUND(lat, 3) y, COUNT(*) n,36                                AVG(CASE WHEN price BETWEEN {PRICE_MIN} AND {PRICE_MAX}37                                         THEN price END) p38                         {_BASE} GROUP BY x, y""")]39        cities = [{"city": r["city"], "n": r["n"], "lng": round(r["lng"], 4),40                   "lat": round(r["lat"], 4),41                   "median": round(r["p"]) if r["p"] else None}42                  for r in con.execute(43                      f"""SELECT city, COUNT(*) n, AVG(lng) lng, AVG(lat) lat,44                                 AVG(CASE WHEN price BETWEEN {PRICE_MIN} AND {PRICE_MAX}45                                          THEN price END) p46                          {_BASE} AND city<>'' GROUP BY city47                          ORDER BY n DESC LIMIT 24""")]48        total = con.execute(49            "SELECT COUNT(*) c FROM listings WHERE active=1 AND published=1"50            " AND dup_of IS NULL").fetchone()["c"]51    finally:52        con.close()53    return {"cells": cells, "cities": cities, "total": total}545556def compute() -> dict:57    cached = _CACHE["data"]58    if cached is not None and time.time() - _CACHE["ts"] < _TTL:59        return cached60    if not _LOCK.acquire(blocking=cached is None):61        return cached62    try:63        cached = _CACHE["data"]64        if cached is not None and time.time() - _CACHE["ts"] < _TTL:65            return cached66        data = _build()67        _CACHE.update(ts=time.time(), data=data)68        return data69    finally:70        _LOCK.release()717273_NAMES: dict = {"mtime": 0.0, "data": {}}747576def source_names() -> dict[str, str]:77    """Identifiant de source → nom lisible (relu si sources.json change)."""78    mtime = SOURCES_PATH.stat().st_mtime79    if mtime != _NAMES["mtime"]:80        _NAMES["data"] = {s["id"]: s.get("name") or s["id"] for s in81                          json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]}82        _NAMES["mtime"] = mtime83    return _NAMES["data"]84
Files main
Menu

Theme