SPB Git

Repository Public

hydro.py 21.6 KB 522 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/hydro.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2313# 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# hydro.py : estimation du coût d'électricité à une adresse — Hydro-Québec91#92#   Reproduit le parcours PUBLIC de l'outil « Estimer les coûts d'électricité93#   à une résidence » (session.hydroquebec.com), rétro-conçu depuis son SPA :94#     1. POST {clWebServicePublicApiURL}public/api/v3_0/lieu-consommation95#        body {noCivique, codePostal, recaptchaResponse} -> liste de lieux96#        (idConso, cleUnique, adresse) ;97#     2. POST {drcvPublicApiURL}public/api/v3_0/consommation/estimation98#        body {cleUnique, idConso} -> coût annuel estimé.99#   Les deux étapes exigent un jeton reCAPTCHA v2 valide100#   (site key 6Lf08Q0UAAAAABCA7z47p2tMxa5_fY0wmn8DDPsu). Il est obtenu via un101#   solveur enfichable (2captcha / CapSolver) ET les requêtes sortent par le102#   proxy résidentiel canadien Bright Data (contourne le géoblocage / anti-bot).103#104#   Configuration (.env) :105#     HQ_CAPTCHA_KEY       clé du solveur (obligatoire pour l'appel live)106#     HQ_CAPTCHA_PROVIDER  "2captcha" (défaut) | "capsolver"107#     BRIGHTDATA_* / OXYLABS_* : proxy résidentiel (réutilise la pile projet)108#109#   Sans HQ_CAPTCHA_KEY : estimate() renvoie {"disponible": False, ...} et le110#   bloc fiche reste masqué — jamais d'estimation inventée.111# -----------------------------------------------------------------------------112from __future__ import annotations113114import json115import os116import re117import sqlite3118import time119import urllib.parse120import urllib.request121from pathlib import Path122123DB_PATH = Path(__file__).resolve().parent.parent / "data" / "hydro.db"124TTL = 180 * 86400                    # succès : la conso bouge lentement125NEG_TTL = 30 * 86400                 # échec (adresse inconnue) : re-tenter dans 30 j126                                     # — borne le coût captcha des cycles watch127128SITE_KEY = "6Lf08Q0UAAAAABCA7z47p2tMxa5_fY0wmn8DDPsu"129PAGE_URL = ("https://session.hydroquebec.com/portail/fr/web/clientele/"130            "estimation-consommation")131URL_LIEU = ("https://services-cl.solutions.hydroquebec.com/wsapi/webpublic/"132            "public/api/v3_0/lieu-consommation")133URL_ESTIM = ("https://services-cl.solutions.hydroquebec.com/conso/webpublic/"134             "public/api/v3_0/consommation/estimation")135UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "136      "(KHTML, like Gecko) Chrome/126.0 Safari/537.36")137138139# --- proxy résidentiel (Bright Data Web Unlocker en repli d'Oxylabs) ----------140def _opener() -> urllib.request.OpenerDirector:141    proxy = None142    if os.environ.get("OXYLABS_PROXY_USER"):143        u = os.environ["OXYLABS_PROXY_USER"]144        p = os.environ["OXYLABS_PROXY_PASS"]145        host = os.environ.get("OXYLABS_PROXY", "pr.oxylabs.io:7777")146        proxy = f"http://{u}-cc-CA:{p}@{host}"147    if proxy:148        h = urllib.request.ProxyHandler({"http": proxy, "https": proxy})149        return urllib.request.build_opener(h)150    return urllib.request.build_opener()151152153# --- solveur reCAPTCHA v2 enfichable ------------------------------------------154def _solve_captcha() -> str | None:155    key = os.environ.get("HQ_CAPTCHA_KEY")156    if not key:157        return None158    provider = os.environ.get("HQ_CAPTCHA_PROVIDER", "2captcha").lower()159    if provider == "capsolver":160        return _capsolver(key)161    return _twocaptcha(key)162163164def _twocaptcha(key: str) -> str | None:165    r = urllib.request.urlopen(urllib.request.Request(166        "https://2captcha.com/in.php",167        data=urllib.parse.urlencode({168            "key": key, "method": "userrecaptcha", "googlekey": SITE_KEY,169            "pageurl": PAGE_URL, "json": 1}).encode()), timeout=30)170    got = json.load(r)171    if got.get("status") != 1:172        return None173    cid = got["request"]174    for _ in range(24):175        time.sleep(5)176        res = json.load(urllib.request.urlopen(177            f"https://2captcha.com/res.php?key={key}&action=get&id={cid}&json=1",178            timeout=30))179        if res.get("status") == 1:180            return res["request"]181        if res.get("request") != "CAPCHA_NOT_READY":182            return None183    return None184185186def _capsolver(key: str) -> str | None:187    r = urllib.request.urlopen(urllib.request.Request(188        "https://api.capsolver.com/createTask",189        data=json.dumps({"clientKey": key, "task": {190            "type": "ReCaptchaV2TaskProxyLess",191            "websiteURL": PAGE_URL, "websiteKey": SITE_KEY}}).encode(),192        headers={"Content-Type": "application/json"}), timeout=30)193    tid = json.load(r).get("taskId")194    if not tid:195        return None196    for _ in range(24):197        time.sleep(5)198        res = json.load(urllib.request.urlopen(urllib.request.Request(199            "https://api.capsolver.com/getTaskResult",200            data=json.dumps({"clientKey": key, "taskId": tid}).encode(),201            headers={"Content-Type": "application/json"}), timeout=30))202        if res.get("status") == "ready":203            return res["solution"]["gRecaptchaResponse"]204        if res.get("status") != "processing":205            return None206    return None207208209def _post(opener, url: str, payload: dict) -> dict | None:210    req = urllib.request.Request(url, data=json.dumps(payload).encode(),211                                 headers={"Content-Type": "application/json",212                                          "User-Agent": UA,213                                          "Origin": "https://session.hydroquebec.com",214                                          "Referer": PAGE_URL})215    try:216        with opener.open(req, timeout=60) as r:217            return json.load(r)218    except Exception:219        return None220221222# --- cache --------------------------------------------------------------------223def _connect() -> sqlite3.Connection:224    DB_PATH.parent.mkdir(parents=True, exist_ok=True)225    con = sqlite3.connect(DB_PATH, timeout=15)226    con.row_factory = sqlite3.Row227    con.execute("""CREATE TABLE IF NOT EXISTS hydro_cache (228        cle TEXT PRIMARY KEY, adresse TEXT, cout_annuel REAL,229        cout_mensuel REAL, payload TEXT, fetched_at REAL)""")230    cols = {r[1] for r in con.execute("PRAGMA table_info(hydro_cache)")}231    if "uid" not in cols:232        con.execute("ALTER TABLE hydro_cache ADD COLUMN uid TEXT")233        con.execute("CREATE INDEX IF NOT EXISTS idx_hydro_uid "234                    "ON hydro_cache(uid)")235    if "kwh" not in cols:236        con.execute("ALTER TABLE hydro_cache ADD COLUMN kwh INTEGER")237    return con238239240def _mark_negatif(con: sqlite3.Connection, cle: str, uid: str | None) -> None:241    """Échec (adresse inconnue d'HQ) : ligne sans coût, pour ne pas re-résoudre242    de captcha avant NEG_TTL. N'écrase jamais un succès existant."""243    with con:244        con.execute(245            "INSERT OR IGNORE INTO hydro_cache "246            "(cle, adresse, cout_annuel, cout_mensuel, payload, fetched_at, "247            "uid, kwh) VALUES (?,?,NULL,NULL,NULL,?,?,NULL)",248            (cle, "", time.time(), uid))249        con.execute(250            "UPDATE hydro_cache SET fetched_at=?, uid=COALESCE(?, uid) "251            "WHERE cle=? AND cout_annuel IS NULL",252            (time.time(), uid, cle))253254255def _civic(adresse: str) -> str | None:256    m = re.match(r"\s*(\d+)([A-Za-z]{0,3})\b", adresse or "")257    if not m:258        return None259    num, suf = m.group(1), m.group(2)260    reste = (adresse or "")[m.end():].lstrip(" ,")261    # rues ordinales : « 15e Avenue », « 1re Avenue », « 2e Rang » — le suffixe262    # ordinal colle au chiffre et est suivi d'un type de voie263    if (suf.lower() in ("e", "re", "er", "eme", "ieme", "ième", "nd", "nde")264            and re.match(r"(av|ave|avenue|rue|rang|boul|ch|chemin)\b",265                         reste, re.I)):266        return None267    return num + suf            # numéro civique, avec lettre d'appartement (24A)268269270def _parse_addr(adresse: str) -> tuple[str, str] | None:271    """Extrait (numéro civique, code postal) d'une adresse de fiche."""272    cp = re.search(r"([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d)", adresse or "")273    civ = _civic(adresse or "")274    if not cp or not civ:275        return None276    return civ, cp.group(1).upper().replace(" ", "")277278279_MAPBOX_TOKEN: list[str] = []280281282def _mapbox_token() -> str | None:283    if not _MAPBOX_TOKEN:284        cfg = (Path(__file__).resolve().parent.parent / "frontend" / "src"285               / "kamaps" / "config.ts")286        if cfg.exists():287            m = re.search(r'"(pk\.[A-Za-z0-9._-]+)"', cfg.read_text())288            _MAPBOX_TOKEN.append(m.group(1) if m else "")289        else:290            _MAPBOX_TOKEN.append("")291    return _MAPBOX_TOKEN[0] or None292293294def _postal_from_latlng(lat: float, lng: float) -> str | None:295    """Code postal via géocodage inverse Mapbox (adresses sans CP)."""296    tok = _mapbox_token()297    if not tok:298        return None299    url = (f"https://api.mapbox.com/geocoding/v5/mapbox.places/{lng},{lat}.json"300           f"?types=postcode&country=CA&access_token={tok}")301    try:302        with urllib.request.urlopen(url, timeout=15) as r:303            feats = json.load(r).get("features") or []304        if feats:305            return (feats[0].get("text") or "").upper().replace(" ", "")306    except Exception:307        return None308    return None309310311def _resolve_postal(civic: str, adresse: str,312                    lat: float | None, lng: float | None) -> str | None:313    """Code postal le plus PRÉCIS pour civic+adresse. Priorité au géocodage314    AVANT de l'adresse complète (rooftop) ancré par proximity=lat/lng — plus315    fiable que l'inverse du lat/lng souvent approximatif des annonces. Vérifie316    que le numéro civique du résultat correspond ; sinon repli sur l'inverse."""317    tok = _mapbox_token()318    if tok and adresse:319        try:320            q = urllib.parse.quote(adresse)321            url = (f"https://api.mapbox.com/geocoding/v5/mapbox.places/{q}.json"322                   f"?country=CA&types=address&limit=1&language=fr")323            if lat is not None and lng is not None:324                url += f"&proximity={lng},{lat}"325            url += f"&access_token={tok}"326            with urllib.request.urlopen(url, timeout=15) as r:327                f = (json.load(r).get("features") or [{}])[0]328            num = str(f.get("address") or "")329            pc = next((c["text"] for c in (f.get("context") or [])330                       if c.get("id", "").startswith("postcode")), None)331            # accepter si le numéro civique concorde (évite les dérives de rue)332            if pc and num and num.rstrip("abABcC ") == re.sub(r"[A-Za-z]$", "",333                                                              civic):334                return pc.upper().replace(" ", "")335        except Exception:336            pass337    if lat is not None and lng is not None:338        return _postal_from_latlng(lat, lng)339    return None340341342def _montant(d: dict) -> tuple[float | None, float | None, int | None]:343    """(coût annuel, coût mensuel, conso annuelle kWh) de l'estimation."""344    a = d.get("montantAnnuel")345    kwh = d.get("consommationAnnuelle")346    if a is None:347        m = re.search(r'"montantAnnuel"\s*:\s*([0-9]+(?:\.[0-9]+)?)',348                      json.dumps(d))349        a = float(m.group(1)) if m else None350    if a is None:351        return None, None, kwh352    return round(a), round(a / 12), kwh353354355def estimate(civic: str | None = None, postal: str | None = None,356             adresse: str | None = None, lat: float | None = None,357             lng: float | None = None, uid: str | None = None,358             solve: bool = True) -> dict:359    """Coût d'électricité annuel estimé à une adresse (cache 6 mois).360361    `solve=False` : ne consulte QUE le cache (aucune résolution de captcha,362    aucun coût) — utilisé pour l'affichage automatique des fiches.363    Le code postal est extrait de l'adresse, ou dérivé du couple lat/lng par364    géocodage inverse Mapbox si l'adresse n'en contient pas (cas d'Immo-Ka).365    Le cache est indexé par `uid` (clé stable de l'annonce) ET par366    civique|code postal, pour que l'affichage cache-only fonctionne même367    quand l'adresse ne porte pas de code postal.368    """369    # lecture cache par uid d'abord (ne nécessite ni CP ni Mapbox)370    if uid:371        con = _connect()372        row = con.execute(373            "SELECT * FROM hydro_cache WHERE uid=? AND cout_annuel IS NOT NULL "374            "AND fetched_at>?", (uid, time.time() - TTL)).fetchone()375        con.close()376        if row:377            return {"disponible": True, "adresse": row["adresse"],378                    "cout_annuel": row["cout_annuel"],379                    "cout_mensuel": row["cout_mensuel"],380                    "kwh_annuel": row["kwh"], "cache": True}381382    if not civic and adresse:383        civic = _civic(adresse)384    if not postal and adresse:385        cp = re.search(r"([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d)", adresse)386        if cp:387            postal = cp.group(1)388    # cache-only : ne pas déclencher Mapbox ; proposer le bouton si un calcul389    # est faisable (civique connu + CP OU coordonnées disponibles)390    if not solve:391        faisable = bool(civic) and (bool(postal) or392                                    (lat is not None and lng is not None))393        return {"disponible": False,394                "raison": "non calculé" if faisable else "adresse incomplète",395                "en_attente": faisable}396    if not postal and civic:397        postal = _resolve_postal(civic, adresse or "", lat, lng)  # au calcul398    if not civic or not postal:399        return {"disponible": False, "raison": "adresse incomplète"}400    postal = postal.upper().replace(" ", "")401    cle = f"{civic}|{postal}"402403    postal_espace = re.sub(r"^([A-Z]\d[A-Z])\s*(\d[A-Z]\d)$", r"\1 \2", postal)404405    con = _connect()406    row = con.execute("SELECT * FROM hydro_cache WHERE cle=? AND fetched_at>?",407                      (cle, time.time() - TTL)).fetchone()408    if row and row["cout_annuel"]:409        con.close()410        return {"disponible": True, "adresse": row["adresse"],411                "cout_annuel": row["cout_annuel"],412                "cout_mensuel": row["cout_mensuel"],413                "kwh_annuel": row["kwh"], "cache": True}414415    if not os.environ.get("HQ_CAPTCHA_KEY"):416        con.close()417        return {"disponible": False, "raison": "solveur captcha non configuré"}418419    token = _solve_captcha()420    if not token:421        con.close()422        return {"disponible": False, "raison": "échec du captcha"}423424    opener = _opener()425    lieux = _post(opener, URL_LIEU, {"noCivique": civic,426                                     "codePostal": postal_espace,427                                     "recaptchaResponse": token})428    items = (lieux or {}).get("listeLieuxConsommation") or []429    cle_unique = (lieux or {}).get("cleUnique")430    if not items or not cle_unique:431        _mark_negatif(con, cle, uid)     # cache négatif : pas de re-tentative 30 j432        con.close()433        return {"disponible": False,434                "raison": "adresse inconnue d'Hydro-Québec"}435    lieu = items[0]436    id_conso = lieu.get("id")437    adr = lieu.get("libelleAdresse") or f"{civic} {lieu.get('rue', '')}".strip()438439    est = _post(opener, URL_ESTIM, {"cleUnique": cle_unique,440                                    "idConso": id_conso})441    if not est:442        con.close()443        return {"disponible": False, "raison": "estimation indisponible"}444    an, mens, kwh = _montant(est)445    if not an:446        _mark_negatif(con, cle, uid)447        con.close()448        return {"disponible": False, "raison": "montant introuvable"}449    with con:450        con.execute(451            "INSERT OR REPLACE INTO hydro_cache "452            "(cle, adresse, cout_annuel, cout_mensuel, payload, fetched_at, "453            "uid, kwh) VALUES (?,?,?,?,?,?,?,?)",454            (cle, adr, an, mens, json.dumps(est), time.time(), uid, kwh))455    con.close()456    return {"disponible": True, "adresse": adr, "cout_annuel": an,457            "cout_mensuel": mens, "kwh_annuel": kwh, "cache": False}458459460def _main_db() -> Path | None:461    d = DB_PATH.parent462    for n in ("louka.db", "immoka.db", "immo.db"):463        if (d / n).exists():464            return d / n465    return None466467468def precompute(limit: int = 100, budget: int = 40) -> dict:469    """Pré-calcule l'estimation Hydro des `limit` annonces les plus récentes470    non encore en cache. `budget` = nb max de résolutions captcha par appel471    (borne le coût ; le reliquat sera comblé aux cycles suivants).472473    Appelé au démarrage (100 dernières) et à chaque cycle de `watch` pour les474    nouvelles annonces — le cache persiste entre les releases (data/hydro.db).475    """476    db = _main_db()477    if db is None:478        return {"erreur": "base des annonces introuvable"}479    src = sqlite3.connect(f"file:{db}?mode=ro", uri=True)480    src.row_factory = sqlite3.Row481    rows = src.execute(482        "SELECT uid, address, lat, lng FROM listings "483        "WHERE address IS NOT NULL AND address != '' "484        "ORDER BY first_seen DESC LIMIT ?", (limit,)).fetchall()485    src.close()486487    con = _connect()488    fait = calcules = saut = echec = negatif = 0489    for r in rows:490        # déjà traité pour cet uid ? succès (TTL) ou échec récent (NEG_TTL) —491        # dans les deux cas on ne re-résout PAS de captcha492        cached = con.execute(493            "SELECT cout_annuel FROM hydro_cache WHERE uid=? AND ("494            "(cout_annuel IS NOT NULL AND fetched_at>?) OR "495            "(cout_annuel IS NULL AND fetched_at>?))",496            (r["uid"], time.time() - TTL, time.time() - NEG_TTL)).fetchone()497        if cached is not None:498            if cached["cout_annuel"] is not None:499                fait += 1500            else:501                negatif += 1502            continue503        civic = _civic(r["address"])504        if not civic or (r["lat"] is None and not _parse_addr(r["address"])):505            saut += 1506            continue507        if calcules >= budget:508            break509        con.close()                       # estimate() ouvre sa propre connexion510        res = estimate(adresse=r["address"], lat=r["lat"], lng=r["lng"],511                       uid=r["uid"])512        con = _connect()513        calcules += 1514        if not res.get("disponible"):515            echec += 1516    con.close()517    stats = {"vises": len(rows), "deja_en_cache": fait,518             "deja_echoue": negatif, "nouveaux_calcules": calcules,519             "sans_adresse": saut, "echecs": echec, "budget": budget}520    print(f"[hydro] précalcul : {stats}")521    return stats522
Files main
Menu

Theme