SPB Git

Repository Public

rdl.py 13.1 KB 325 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/rdl.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2313# Last Modified    : 2026-08-2314#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# rdl.py : Registre des loyers (registre-des-loyers.ca) — extraction + requêtes91#92#   Le Registre des loyers est une initiative citoyenne (Vivre en ville) où93#   les locataires déclarent volontairement leur loyer. La carte publique94#   expose une API JSON ouverte :95#       GET /api/v1/housings/{NElat},{NElng},{SWlat},{SWlng}96#   On balaie la province par grandes boîtes (aucune pagination côté serveur ;97#   la boîte « tout le Québec » dépasse ses capacités -> découpage, avec98#   subdivision récursive en cas d'erreur 500), puis on stocke le tout dans99#   data/rdl.db (base séparée : jamais de verrou sur louka.db).100#101#   Usage :  python run.py rdl            # rafraîchît la base locale102#   Lecture : nearby(lat, lng, radius_m)  # loyers déclarés autour d'un point103#             (bloc « Registre des loyers » de la fiche, /api/rdl)104# -----------------------------------------------------------------------------105from __future__ import annotations106107import json108import math109import sqlite3110import time111import urllib.request112from pathlib import Path113from statistics import median114115DB_PATH = Path(__file__).resolve().parent.parent / "data" / "rdl.db"116API = "https://registre-des-loyers.ca/api/v1/housings/{},{},{},{}"117UA = "LouKaBot/1.0 (+https://www.lou-ka.com; contact@spboucher.ai)"118DELAY = 2.0                      # politesse entre deux boîtes119120# Boîtes (NE_lat, NE_lng, SW_lat, SW_lng) couvrant le pays entier (le registre121# est pancanadien ; Lou-Ka n'affiche que ce qui tombe près d'une annonce).122# Elles se recoupent légèrement, la déduplication se fait par id.123BOXES: list[tuple[float, float, float, float]] = [124    (46.0, -70.0, 45.0, -75.0),      # Grand Montréal + Montérégie + Estrie125    (47.2, -70.0, 46.0, -76.0),      # Québec, Mauricie, Centre-du-Québec126    (46.2, -74.8, 45.2, -77.5),      # Outaouais127    (49.5, -63.5, 47.2, -80.0),      # Abitibi, Saguenay, Gaspésie128    (47.2, -63.5, 45.0, -70.0),      # Bas-Saint-Laurent, Beauce est129    (63.0, -55.0, 49.5, -80.0),      # Côte-Nord, Nord-du-Québec130    (45.05, -70.0, 44.5, -80.0),     # frange frontalière sud131    (57.0, -74.5, 41.6, -96.0),      # Ontario132    (60.0, -96.0, 48.9, -110.0),     # Prairies (MB, SK)133    (60.0, -110.0, 48.0, -140.0),    # Alberta, Colombie-Britannique134    (70.0, -60.0, 60.0, -142.0),     # territoires + Nunavik135    (49.0, -52.0, 43.0, -70.0),      # Atlantique (NB, NÉ, ÎPÉ, TNL sud)136    (61.0, -52.0, 49.0, -57.0),      # Terre-Neuve nord + Labrador est137]138139# au-delà de ce volume on subdivise par prudence (plafond serveur inconnu)140SUSPECT = 40000141142_SCHEMA = """143CREATE TABLE IF NOT EXISTS rdl_housings (144    id INTEGER PRIMARY KEY,145    full_address TEXT, street_number TEXT, apartment_number TEXT,146    street_name TEXT, city TEXT, zip TEXT,147    lat REAL, lng REAL,148    price REAL, rooms INTEGER, year INTEGER, start_date TEXT,149    type_of_accomodation TEXT,150    heating_included INTEGER, electricity_included INTEGER,151    furnishing_included INTEGER, parking_included INTEGER,152    animal_allowed INTEGER,153    address_slug TEXT, updated_at TEXT, fetched_at TEXT154);155CREATE INDEX IF NOT EXISTS idx_rdl_latlng ON rdl_housings (lat, lng);156"""157158159def _connect(ro: bool = False) -> sqlite3.Connection:160    if ro:161        con = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)162    else:163        DB_PATH.parent.mkdir(parents=True, exist_ok=True)164        con = sqlite3.connect(DB_PATH)165    con.row_factory = sqlite3.Row166    return con167168169def _fetch_box(ne_lat: float, ne_lng: float, sw_lat: float, sw_lng: float,170               depth: int = 0) -> list[dict]:171    """Une boîte ; en cas d'erreur serveur (boîte trop lourde), découpe en 4."""172    url = API.format(ne_lat, ne_lng, sw_lat, sw_lng)173    req = urllib.request.Request(url, headers={"User-Agent": UA})174    try:175        with urllib.request.urlopen(req, timeout=120) as resp:176            data = json.load(resp)177        rows = data.get("data", {}).get("housings") or []178        if len(rows) < SUSPECT or depth >= 3:179            return rows180        raise RuntimeError(f"{len(rows)} résultats — subdivision de prudence")181    except Exception as exc:182        if depth >= 3:183            print(f"  ! abandon boîte {url}: {exc}")184            return []185        mid_lat = (ne_lat + sw_lat) / 2186        mid_lng = (ne_lng + sw_lng) / 2187        out: list[dict] = []188        for quad in ((ne_lat, ne_lng, mid_lat, mid_lng),189                     (ne_lat, mid_lng, mid_lat, sw_lng),190                     (mid_lat, ne_lng, sw_lat, mid_lng),191                     (mid_lat, mid_lng, sw_lat, sw_lng)):192            time.sleep(DELAY)193            out.extend(_fetch_box(*quad, depth=depth + 1))194        return out195196197def _num(v, cast=float):198    try:199        return cast(v)200    except (TypeError, ValueError):201        return None202203204def refresh() -> None:205    """Balaie la province et remplace le contenu de data/rdl.db."""206    now = time.strftime("%Y-%m-%d %H:%M:%S")207    seen: dict[int, dict] = {}208    for i, box in enumerate(BOXES, 1):209        rows = _fetch_box(*box)210        fresh = 0211        for h in rows:212            hid = _num(h.get("id"), int)213            if hid is None or hid in seen:214                continue215            seen[hid] = h216            fresh += 1217        print(f"[rdl] boîte {i}/{len(BOXES)} : {len(rows)} reçus, "218              f"{fresh} nouveaux ({len(seen)} au total)")219        time.sleep(DELAY)220221    con = _connect()222    con.executescript(_SCHEMA)223    with con:224        con.execute("DELETE FROM rdl_housings")225        con.executemany(226            "INSERT OR REPLACE INTO rdl_housings VALUES "227            "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",228            [(hid,229              h.get("full_address"), h.get("street_number"),230              h.get("apartment_number"), h.get("street_name"),231              h.get("city"), h.get("zip"),232              _num(h.get("latitude")), _num(h.get("longitude")),233              _num(h.get("price")), _num(h.get("number_of_closed_room"), int),234              _num(h.get("year"), int),235              (h.get("start_date") or "")[:10] or None,236              h.get("type_of_accomodation"),237              1 if h.get("heating_included") else 0,238              1 if h.get("electricity_included") else 0,239              1 if h.get("furnishing_included") else 0,240              1 if h.get("parking_included") else 0,241              1 if h.get("animal_allowed") else 0,242              h.get("address_slug"), h.get("updated_at"), now)243             for hid, h in seen.items()])244    n, cities = con.execute(245        "SELECT COUNT(*), COUNT(DISTINCT city) FROM rdl_housings").fetchone()246    print(f"[rdl] terminé : {n} loyers déclarés, {cities} villes -> {DB_PATH}")247    con.close()248249250def _dist_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float:251    dlat = math.radians(lat2 - lat1)252    dlng = math.radians(lng2 - lng1)253    a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1))254         * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2)255    return 6371000 * 2 * math.asin(math.sqrt(a))256257258def nearby(lat: float, lng: float, radius_m: int = 600,259           limit: int = 12) -> dict | None:260    """Loyers déclarés autour d'un point + agrégats (bloc fiche / API)."""261    if not DB_PATH.exists():262        return None263    dlat = radius_m / 111320.0264    dlng = radius_m / (111320.0 * max(0.2, math.cos(math.radians(lat))))265    con = _connect(ro=True)266    rows = con.execute(267        "SELECT * FROM rdl_housings WHERE lat BETWEEN ? AND ? "268        "AND lng BETWEEN ? AND ? AND price > 100 AND price < 20000",269        (lat - dlat, lat + dlat, lng - dlng, lng + dlng)).fetchall()270    con.close()271    hits = []272    for r in rows:273        if r["lat"] is None or r["lng"] is None:274            continue275        d = _dist_m(lat, lng, r["lat"], r["lng"])276        if d <= radius_m:277            hits.append((d, r))278    if not hits:279        return {"n": 0, "radius_m": radius_m, "items": []}280    hits.sort(key=lambda t: t[0])281282    def _q(vals: list[float], q: float) -> int:283        s = sorted(vals)284        i = q * (len(s) - 1)285        lo = int(i)286        hi = min(lo + 1, len(s) - 1)287        return round(s[lo] + (s[hi] - s[lo]) * (i - lo))288289    prices = [r["price"] for _, r in hits]290    recent = [r["price"] for _, r in hits if (r["year"] or 0) >= 2023]291    base = recent if len(recent) >= 8 else prices292    quart = ({"p10": _q(base, 0.10), "p25": _q(base, 0.25),293              "p75": _q(base, 0.75), "p90": _q(base, 0.90)}294             if len(base) >= 5 else None)295    by_rooms: dict[str, dict] = {}296    for _, r in hits:297        if r["rooms"] is None:298            continue299        b = by_rooms.setdefault(str(r["rooms"]), {"n": 0, "prices": []})300        b["n"] += 1301        b["prices"].append(r["price"])302    for b in by_rooms.values():303        b["median"] = round(median(b.pop("prices")))304305    def item(d: float, r: sqlite3.Row) -> dict:306        addr = " ".join(x for x in (r["street_number"], r["street_name"]) if x)307        if r["apartment_number"]:308            addr += f", app. {r['apartment_number']}"309        return {"address": addr or r["full_address"], "city": r["city"],310                "price": r["price"], "rooms": r["rooms"], "year": r["year"],311                "date": r["start_date"], "dist_m": round(d),312                "heating": bool(r["heating_included"]),313                "furnished": bool(r["furnishing_included"])}314315    return {316        "n": len(hits),317        "radius_m": radius_m,318        "median": round(median(prices)),319        "median_recent": round(median(recent)) if recent else None,320        "n_recent": len(recent),321        "quartiles": quart,322        "by_rooms": by_rooms,323        "items": [item(d, r) for d, r in hits[:limit]],324    }325
Files main
Menu

Theme