SPB Git

Repository Public

tal.py 22.1 KB 533 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/tal.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#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# tal.py : historique au Tribunal administratif du logement (TAL / ex-RDL)91#92#   Les décisions du TAL sont diffusées gratuitement par SOQUIJ93#   (citoyens.soquij.qc.ca, tribunal no 35, plein texte depuis ~2009). Le site94#   est protégé par une détection de bot (byscuit) : la RECHERCHE exige un95#   rendu JS + IP résidentielle (Scrapfly, asp + render_js + session), mais la96#   page d'une DÉCISION se charge ensuite sans rendu (même session = moins97#   cher). Le moteur ne supporte pas les phrases entre guillemets : les mots98#   sont combinés en ET implicite, d'où la stratégie99#       recherche « <no civique> <nom de rue sans le type> »100#       puis VÉRIFICATION de l'adresse exacte dans le texte intégral.101#102#   Tout est mis en cache dans data/tal.db (base séparée : jamais de verrou103#   sur louka.db) par adresse normalisée (no civique + rue + ville) :104#     · tal_lookup    : une ligne par adresse vérifiée (ou en file d'attente) ;105#     · tal_decisions : décisions confirmées à l'adresse, classées par mots106#                       clés (non-paiement, résiliation, expulsion, reprise…)107#                       et par partie demanderesse (locateur vs locataire).108#109#   Usage :  python run.py tal [n] [budget_s]   # précalcul par lots110#   Lecture : lookup(address, city) — bloc « Historique TAL » de la fiche111#             (/api/tal) ; une adresse jamais vérifiée est mise en file112#             prioritaire et traitée au prochain passage du watch.113# -----------------------------------------------------------------------------114from __future__ import annotations115116import html117import json118import os119import re120import sqlite3121import threading122import time123import unicodedata124import urllib.parse125import urllib.request126from concurrent.futures import ThreadPoolExecutor, as_completed127from pathlib import Path128129DATA_DIR = Path(__file__).resolve().parent.parent / "data"130DB_PATH = DATA_DIR / "tal.db"131LOUKA_DB = DATA_DIR / "louka.db"132133SCRAPFLY_API = "https://api.scrapfly.io/scrape"134SOQUIJ_BASE = "https://citoyens.soquij.qc.ca"135TRIBUNAL_ID = "35"                 # Tribunal administratif du logement / RDL136137REFRESH_DAYS = 180                 # revérifier une adresse après ~6 mois138ERROR_RETRY_DAYS = 7               # réessayer plus vite après une erreur139MAX_DECISIONS = 12                 # décisions lues au maximum par adresse140WORKERS = 4141142_SCHEMA = """143CREATE TABLE IF NOT EXISTS tal_lookup (144    addr_key   TEXT PRIMARY KEY,145    civic      TEXT, street TEXT, city TEXT, query TEXT,146    status     TEXT,               -- queued | ok | error147    found      INTEGER,            -- résultats bruts SOQUIJ (avant vérification)148    matched    INTEGER,            -- décisions confirmées à l'adresse149    priority   INTEGER DEFAULT 0,  -- 1 = demandé par une fiche (file rapide)150    checked_at TEXT,151    error      TEXT152);153CREATE TABLE IF NOT EXISTS tal_decisions (154    addr_key    TEXT,155    decision_id TEXT,               -- ID hexadécimal SOQUIJ156    citation    TEXT,               -- ex. « 2026 QCTAL 21509 »157    parties     TEXT,158    date        TEXT,159    demandeur   TEXT,               -- locateur | locataire | NULL (indéterminé)160    tags        TEXT,               -- JSON : ["non-paiement", "résiliation de bail", …]161    verdict     TEXT,               -- accueillie | rejetée | NULL162    url         TEXT,163    PRIMARY KEY (addr_key, decision_id)164);165"""166167# ---------------------------------------------------------------------------168# Normalisation d'adresse169# ---------------------------------------------------------------------------170171_TYPES_VOIE = {172    "rue", "avenue", "av", "ave", "boulevard", "boul", "blvd", "bd", "chemin",173    "ch", "place", "pl", "cote", "allee", "montee", "carre", "impasse",174    "terrasse", "tsse", "croissant", "crois", "rang", "route", "rte",175    "promenade", "prom", "voie", "square", "cours", "sentier", "parc",176    # types anglais (annonces montréalaises)177    "st", "street", "rd", "road", "dr", "drive", "cres", "crescent",178    "ct", "court", "lane", "ln", "hwy", "way",179}180_STOPWORDS = {"de", "du", "des", "la", "le", "les", "l", "d", "a", "au", "aux",181              "app", "apt", "unite", "suite", "bureau", "local"}182183184def _fold(s: str) -> str:185    """Minuscules sans accents (comparaisons et clés)."""186    s = unicodedata.normalize("NFD", s)187    return "".join(c for c in s if not unicodedata.combining(c)).lower()188189190def parse_address(address: str | None, city: str | None = None) -> dict | None:191    """« 1573, rue Pierre-Corneille, Québec, Québec, G2E4W9 » ->192    civic + rue + mots significatifs pour la recherche SOQUIJ."""193    if not address:194        return None195    parts = [p.strip() for p in address.split(",") if p.strip()]196    if not parts:197        return None198    m = re.match(r"^(\d+[a-zA-Z]?)\b[\s,]*(.*)$", parts[0])199    if not m:200        return None201    civic = m.group(1)202    street = m.group(2).strip()203    if not street and len(parts) > 1:          # « 1573 » puis « rue X » à part204        street = parts[1]205    if not street:206        return None207    ville = (city or "").strip()208    if not ville and len(parts) > 2:209        for p in parts[1:]:                    # sauter « Suite 1106 », « app. 4 »…210            if not re.match(r"^(app|apt|suite|unit|unité|bureau|local|#|\d)",211                            p, re.I):212                ville = p213                break214215    toks = [t for t in re.split(r"[^\w-]+", street) if t]216    core = [t for t in toks217            if _fold(t).rstrip(".") not in _TYPES_VOIE218            and _fold(t) not in _STOPWORDS and len(t) >= 2219            and not re.fullmatch(r"\d+[a-zA-Z]?", t)]   # no d'unité (« 16F »)220    if not core:                               # ex. « 1re Avenue » : tout garder221        core = toks222    if not core:223        return None224    key = f"{civic}|{_fold(' '.join(core))}|{_fold(ville)}"225    return {"civic": civic, "street": street, "city": ville,226            "core": core, "query": f"{civic} {' '.join(core)}", "key": key}227228229# ---------------------------------------------------------------------------230# Accès SOQUIJ via Scrapfly231# ---------------------------------------------------------------------------232233def _scrapfly(url: str, *, render: bool, session: str) -> str:234    key = os.environ.get("SCRAPFLY_KEY")235    if not key:236        raise RuntimeError("SCRAPFLY_KEY absent de l'environnement")237    params = {"key": key, "url": url, "asp": "true", "country": "ca",238              "proxy_pool": "public_residential_pool", "session": session}239    if render:240        params["render_js"] = "true"241        params["rendering_wait"] = "5000"242    u = SCRAPFLY_API + "?" + urllib.parse.urlencode(params)243    data = None244    for attempt in range(3):245        try:246            with urllib.request.urlopen(u, timeout=170) as resp:247                data = json.load(resp)248            break249        except urllib.error.HTTPError as exc:250            # 429 = limite de concurrence Scrapfly : attendre puis réessayer251            if exc.code == 429 and attempt < 2:252                time.sleep(8 * (attempt + 1))253                continue254            raise255    res = (data or {}).get("result") or {}256    if res.get("status_code") != 200:257        raise RuntimeError(f"SOQUIJ HTTP {res.get('status_code')}")258    return res.get("content") or ""259260261def _to_text(html_doc: str) -> str:262    """HTML -> texte plat, entités décodées, espaces normalisés."""263    doc = re.sub(r"<script.*?</script>|<style.*?</style>", " ",264                 html_doc, flags=re.S | re.I)265    doc = re.sub(r"<[^>]+>", " ", doc)266    doc = html.unescape(doc).replace("\xa0", " ")267    return re.sub(r"\s+", " ", doc)268269270def _search(query: str, session: str) -> list[dict]:271    """Recherche plein texte TAL ; -> [{id, parties, date}] (max 200)."""272    recher = f"{TRIBUNAL_ID}_{query}_0___date"273    target = SOQUIJ_BASE + "/index.php?" + urllib.parse.urlencode(274        {"type": "listemc", "recher": recher},275        encoding="iso-8859-1", errors="replace")276    content = _scrapfly(target, render=True, session=session)277    text = _to_text(content)278    if "Décisions trouvées" not in text and "Aucun résultat" not in text:279        raise RuntimeError("page de résultats SOQUIJ non reconnue (anti-bot ?)")280    rows = []281    for m in re.finditer(282            r'href="(/php/decision\.php\?ID=([0-9A-Fa-f]+))"[^>]*>(.*?)</a>'283            r'.*?class="tb-date"[^>]*>\s*([\d-]{8,10})', content, re.S):284        rows.append({"id": m.group(2).upper(),285                     "parties": _to_text(m.group(3)).strip(),286                     "date": m.group(4),287                     "url": SOQUIJ_BASE + m.group(1)})288    return rows289290291_RE_CITATION = re.compile(r"\b(\d{4}\s+QC(?:TAL|RDL)\s+\d+)\b")292293_TAGS = [294    ("non-paiement de loyer", ("non-paiement", "loyer impaye",295                               "recouvrement du loyer", "ne paie pas le loyer",296                               "loyers impayes")),297    ("résiliation de bail",   ("resiliation",)),298    ("expulsion",             ("expulsion",)),299    ("éviction",              ("eviction",)),300    ("reprise du logement",   ("reprise du logement", "reprise de logement")),301    ("fixation de loyer",     ("fixation du loyer", "fixation de loyer")),302    ("insalubrité",           ("insalubr",)),303    ("harcèlement",           ("harcel",)),304]305306307def _classify(folded: str) -> tuple[str | None, list[str], str | None]:308    """Texte plié -> (partie demanderesse, tags, verdict sommaire)."""309    demandeur = None310    m = re.search(r"\b(locateurs?|locatrices?|locataires?)\b[^a-z]{0,40}"311                  r"parties?\s+demanderesses?", folded)312    if m:313        demandeur = "locataire" if m.group(1).startswith("locata") else "locateur"314    tags = [tag for tag, needles in _TAGS315            if any(n in folded for n in needles)]316    verdict = None317    if re.search(r"\baccueille\b", folded):318        verdict = "accueillie"319    elif re.search(r"\brejette la demande\b", folded):320        verdict = "rejetée"321    return demandeur, tags, verdict322323324def _address_in_text(folded: str, civic: str, core: list[str]) -> bool:325    """Le no civique suivi de près par le nom de la rue ? (adresse confirmée)"""326    name = _fold(" ".join(core))327    pat = rf"\b{re.escape(civic.lower())}\b.{{0,80}}?{re.escape(name)}"328    if re.search(pat, folded):329        return True330    # tolérance : dernier mot du nom seulement (ex. « st-jacques »)331    last = _fold(core[-1])332    return bool(len(last) >= 4 and333                re.search(rf"\b{re.escape(civic.lower())}\b.{{0,60}}?{re.escape(last)}", folded))334335336def _check_address(parsed: dict, session: str) -> dict:337    """Recherche + vérification pour UNE adresse. -> résultat à persister."""338    rows = _search(parsed["query"], session)339    decisions = []340    for r in rows[:MAX_DECISIONS]:341        try:342            page = _scrapfly(r["url"], render=False, session=session)343        except Exception:344            continue345        text = _to_text(page)346        folded = _fold(text)347        if not _address_in_text(folded, parsed["civic"], parsed["core"]):348            continue349        m = _RE_CITATION.search(text)350        demandeur, tags, verdict = _classify(folded)351        decisions.append({352            "decision_id": r["id"],353            "citation": re.sub(r"\s+", " ", m.group(1)) if m else None,354            "parties": r["parties"], "date": r["date"],355            "demandeur": demandeur, "tags": tags, "verdict": verdict,356            "url": r["url"]})357    return {"found": len(rows), "decisions": decisions}358359360# ---------------------------------------------------------------------------361# Persistance362# ---------------------------------------------------------------------------363364_lock = threading.Lock()365366367def _connect(ro: bool = False) -> sqlite3.Connection:368    if ro:369        con = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True, timeout=15)370    else:371        DATA_DIR.mkdir(parents=True, exist_ok=True)372        con = sqlite3.connect(DB_PATH, timeout=30)373        con.executescript(_SCHEMA)374    con.row_factory = sqlite3.Row375    return con376377378def _save(con: sqlite3.Connection, parsed: dict, status: str,379          found: int = 0, decisions: list[dict] | None = None,380          error: str | None = None) -> None:381    now = time.strftime("%Y-%m-%d %H:%M:%S")382    with con:383        con.execute(384            "INSERT OR REPLACE INTO tal_lookup "385            "(addr_key, civic, street, city, query, status, found, matched,"386            " priority, checked_at, error) VALUES (?,?,?,?,?,?,?,?,0,?,?)",387            (parsed["key"], parsed["civic"], parsed["street"], parsed["city"],388             parsed["query"], status, found, len(decisions or []), now, error))389        con.execute("DELETE FROM tal_decisions WHERE addr_key=?",390                    (parsed["key"],))391        for d in decisions or []:392            con.execute(393                "INSERT OR REPLACE INTO tal_decisions VALUES (?,?,?,?,?,?,?,?,?)",394                (parsed["key"], d["decision_id"], d["citation"], d["parties"],395                 d["date"], d["demandeur"], json.dumps(d["tags"],396                 ensure_ascii=False), d["verdict"], d["url"]))397398399# ---------------------------------------------------------------------------400# API de lecture (fiche / web.py)401# ---------------------------------------------------------------------------402403def lookup(address: str | None, city: str | None = None) -> dict:404    """Historique TAL d'une adresse — lecture du cache ; une adresse inconnue405    est mise en file prioritaire (traitée au prochain passage du watch)."""406    parsed = parse_address(address, city)407    if parsed is None:408        return {"status": "na"}409    con = _connect()410    try:411        row = con.execute("SELECT * FROM tal_lookup WHERE addr_key=?",412                          (parsed["key"],)).fetchone()413        if row is None:414            with _lock, con:415                con.execute(416                    "INSERT OR IGNORE INTO tal_lookup "417                    "(addr_key, civic, street, city, query, status, priority) "418                    "VALUES (?,?,?,?,?,'queued',1)",419                    (parsed["key"], parsed["civic"], parsed["street"],420                     parsed["city"], parsed["query"]))421            return {"status": "pending"}422        if row["status"] != "ok":423            return {"status": "pending" if row["status"] == "queued"424                    else "error"}425        decs = [dict(r) for r in con.execute(426            "SELECT * FROM tal_decisions WHERE addr_key=? ORDER BY date DESC",427            (parsed["key"],)).fetchall()]428    finally:429        con.close()430    items = [{"date": d["date"], "citation": d["citation"],431              "demandeur": d["demandeur"], "tags": json.loads(d["tags"] or "[]"),432              "verdict": d["verdict"], "url": d["url"]} for d in decs]433    contre = sum(1 for d in items if d["demandeur"] == "locateur")434    evict = sum(1 for d in items if d["demandeur"] == "locateur"435                and set(d["tags"]) &436                {"expulsion", "éviction", "reprise du logement",437                 "résiliation de bail", "non-paiement de loyer"})438    return {"status": "ok", "checked_at": row["checked_at"],439            "n": len(items), "contre_locataire": contre, "eviction": evict,440            "last_date": items[0]["date"] if items else None,441            "decisions": items}442443444# ---------------------------------------------------------------------------445# Précalcul par lots (boucle watch / run.py tal)446# ---------------------------------------------------------------------------447448def _candidates(con: sqlite3.Connection, limit: int) -> list[dict]:449    """File prioritaire, puis adresses jamais vérifiées (annonces récentes450    d'abord), puis revérifications périmées."""451    out: list[dict] = []452    seen: set[str] = set()453454    for r in con.execute(455            "SELECT * FROM tal_lookup WHERE status='queued' "456            "ORDER BY priority DESC LIMIT ?", (limit,)):457        p = parse_address(f"{r['civic']} {r['street']}", r["city"])458        if p and p["key"] not in seen:459            seen.add(p["key"])460            out.append(p)461    if len(out) >= limit:462        return out[:limit]463464    known = {r["addr_key"]: r for r in con.execute(465        "SELECT addr_key, status, checked_at FROM tal_lookup")}466    stale_ok = time.strftime("%Y-%m-%d %H:%M:%S",467                             time.localtime(time.time() - REFRESH_DAYS * 86400))468    stale_err = time.strftime("%Y-%m-%d %H:%M:%S",469                              time.localtime(time.time() - ERROR_RETRY_DAYS * 86400))470    try:471        lk = sqlite3.connect(f"file:{LOUKA_DB}?mode=ro", uri=True, timeout=15)472        lk.row_factory = sqlite3.Row473        rows = lk.execute(474            "SELECT DISTINCT address, city FROM listings "475            "WHERE active=1 AND published=1 AND address IS NOT NULL "476            "AND address <> '' ORDER BY rowid DESC").fetchall()477        lk.close()478    except Exception:479        rows = []480    for r in rows:481        if len(out) >= limit:482            break483        p = parse_address(r["address"], r["city"])484        if p is None or p["key"] in seen:485            continue486        k = known.get(p["key"])487        if k is not None:488            if k["status"] == "ok" and (k["checked_at"] or "") > stale_ok:489                continue490            if k["status"] == "error" and (k["checked_at"] or "") > stale_err:491                continue492            if k["status"] == "queued":493                continue                      # déjà compté plus haut494        seen.add(p["key"])495        out.append(p)496    return out497498499def precompute(limit: int = 60, budget: int = 600) -> dict:500    """Vérifie jusqu'à `limit` adresses (budget en secondes, WORKERS fils)."""501    t0 = time.time()502    con = _connect()503    cands = _candidates(con, limit)504    if not cands:505        con.close()506        return {"checked": 0, "matched": 0, "todo": 0}507    checked = matched = errors = 0508    with ThreadPoolExecutor(max_workers=WORKERS) as pool:509        futs = {}510        for i, p in enumerate(cands):511            if time.time() - t0 > budget:512                break513            futs[pool.submit(_check_address, p,514                             f"louka-tal-{i % WORKERS}")] = p515        for fut in as_completed(futs):516            p = futs[fut]517            try:518                res = fut.result()519                _save(con, p, "ok", res["found"], res["decisions"])520                checked += 1521                matched += len(res["decisions"])522                if res["decisions"]:523                    print(f"[tal] {p['civic']} {p['street']} ({p['city']}) : "524                          f"{len(res['decisions'])} décision(s) confirmée(s)")525            except Exception as exc:526                _save(con, p, "error", error=str(exc)[:300])527                errors += 1528    con.close()529    stats = {"checked": checked, "matched": matched, "errors": errors,530             "seconds": round(time.time() - t0, 1)}531    print(f"[tal] {stats}")532    return stats533
Files main
Menu

Theme