Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/hydro.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-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# Immo-Ka — Agrégateur de propriétés à vendre (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 tok = os.environ.get("MAPBOX_TOKEN", "").strip()284 if tok:285 return tok286 try: # ancien emplacement (frontend v1), s'il existe encore287 cfg = (Path(__file__).resolve().parent.parent / "frontend" / "src"288 / "kamaps" / "config.ts").read_text()289 m = re.search(r'"(pk\.[A-Za-z0-9._-]+)"', cfg)290 return m.group(1) if m else None291 except OSError:292 return None293294295def _postal_from_latlng(lat: float, lng: float) -> str | None:296 """Code postal via géocodage inverse Mapbox (adresses sans CP)."""297 tok = _mapbox_token()298 if not tok:299 return None300 url = (f"https://api.mapbox.com/geocoding/v5/mapbox.places/{lng},{lat}.json"301 f"?types=postcode&country=CA&access_token={tok}")302 try:303 with urllib.request.urlopen(url, timeout=15) as r:304 feats = json.load(r).get("features") or []305 if feats:306 return (feats[0].get("text") or "").upper().replace(" ", "")307 except Exception:308 return None309 return None310311312def _resolve_postal(civic: str, adresse: str,313 lat: float | None, lng: float | None) -> str | None:314 """Code postal le plus PRÉCIS pour civic+adresse. Priorité au géocodage315 AVANT de l'adresse complète (rooftop) ancré par proximity=lat/lng — plus316 fiable que l'inverse du lat/lng souvent approximatif des annonces. Vérifie317 que le numéro civique du résultat correspond ; sinon repli sur l'inverse."""318 tok = _mapbox_token()319 if tok and adresse:320 try:321 q = urllib.parse.quote(adresse)322 url = (f"https://api.mapbox.com/geocoding/v5/mapbox.places/{q}.json"323 f"?country=CA&types=address&limit=1&language=fr")324 if lat is not None and lng is not None:325 url += f"&proximity={lng},{lat}"326 url += f"&access_token={tok}"327 with urllib.request.urlopen(url, timeout=15) as r:328 f = (json.load(r).get("features") or [{}])[0]329 num = str(f.get("address") or "")330 pc = next((c["text"] for c in (f.get("context") or [])331 if c.get("id", "").startswith("postcode")), None)332 # accepter si le numéro civique concorde (évite les dérives de rue)333 if pc and num and num.rstrip("abABcC ") == re.sub(r"[A-Za-z]$", "",334 civic):335 return pc.upper().replace(" ", "")336 except Exception:337 pass338 if lat is not None and lng is not None:339 return _postal_from_latlng(lat, lng)340 return None341342343def _montant(d: dict) -> tuple[float | None, float | None, int | None]:344 """(coût annuel, coût mensuel, conso annuelle kWh) de l'estimation."""345 a = d.get("montantAnnuel")346 kwh = d.get("consommationAnnuelle")347 if a is None:348 m = re.search(r'"montantAnnuel"\s*:\s*([0-9]+(?:\.[0-9]+)?)',349 json.dumps(d))350 a = float(m.group(1)) if m else None351 if a is None:352 return None, None, kwh353 return round(a), round(a / 12), kwh354355356def estimate(civic: str | None = None, postal: str | None = None,357 adresse: str | None = None, lat: float | None = None,358 lng: float | None = None, uid: str | None = None,359 solve: bool = True) -> dict:360 """Coût d'électricité annuel estimé à une adresse (cache 6 mois).361362 `solve=False` : ne consulte QUE le cache (aucune résolution de captcha,363 aucun coût) — utilisé pour l'affichage automatique des fiches.364 Le code postal est extrait de l'adresse, ou dérivé du couple lat/lng par365 géocodage inverse Mapbox si l'adresse n'en contient pas (cas d'Immo-Ka).366 Le cache est indexé par `uid` (clé stable de l'annonce) ET par367 civique|code postal, pour que l'affichage cache-only fonctionne même368 quand l'adresse ne porte pas de code postal.369 """370 # lecture cache par uid d'abord (ne nécessite ni CP ni Mapbox)371 if uid:372 con = _connect()373 row = con.execute(374 "SELECT * FROM hydro_cache WHERE uid=? AND cout_annuel IS NOT NULL "375 "AND fetched_at>?", (uid, time.time() - TTL)).fetchone()376 con.close()377 if row:378 return {"disponible": True, "adresse": row["adresse"],379 "cout_annuel": row["cout_annuel"],380 "cout_mensuel": row["cout_mensuel"],381 "kwh_annuel": row["kwh"], "cache": True}382383 if not civic and adresse:384 civic = _civic(adresse)385 if not postal and adresse:386 cp = re.search(r"([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d)", adresse)387 if cp:388 postal = cp.group(1)389 # cache-only : ne pas déclencher Mapbox ; proposer le bouton si un calcul390 # est faisable (civique connu + CP OU coordonnées disponibles)391 if not solve:392 faisable = bool(civic) and (bool(postal) or393 (lat is not None and lng is not None))394 return {"disponible": False,395 "raison": "non calculé" if faisable else "adresse incomplète",396 "en_attente": faisable}397 if not postal and civic:398 postal = _resolve_postal(civic, adresse or "", lat, lng) # au calcul399 if not civic or not postal:400 return {"disponible": False, "raison": "adresse incomplète"}401 postal = postal.upper().replace(" ", "")402 cle = f"{civic}|{postal}"403404 postal_espace = re.sub(r"^([A-Z]\d[A-Z])\s*(\d[A-Z]\d)$", r"\1 \2", postal)405406 con = _connect()407 row = con.execute("SELECT * FROM hydro_cache WHERE cle=? AND fetched_at>?",408 (cle, time.time() - TTL)).fetchone()409 if row and row["cout_annuel"]:410 con.close()411 return {"disponible": True, "adresse": row["adresse"],412 "cout_annuel": row["cout_annuel"],413 "cout_mensuel": row["cout_mensuel"],414 "kwh_annuel": row["kwh"], "cache": True}415416 if not os.environ.get("HQ_CAPTCHA_KEY"):417 con.close()418 return {"disponible": False, "raison": "solveur captcha non configuré"}419420 token = _solve_captcha()421 if not token:422 con.close()423 return {"disponible": False, "raison": "échec du captcha"}424425 opener = _opener()426 lieux = _post(opener, URL_LIEU, {"noCivique": civic,427 "codePostal": postal_espace,428 "recaptchaResponse": token})429 items = (lieux or {}).get("listeLieuxConsommation") or []430 cle_unique = (lieux or {}).get("cleUnique")431 if not items or not cle_unique:432 _mark_negatif(con, cle, uid) # cache négatif : pas de re-tentative 30 j433 con.close()434 return {"disponible": False,435 "raison": "adresse inconnue d'Hydro-Québec"}436 lieu = items[0]437 id_conso = lieu.get("id")438 adr = lieu.get("libelleAdresse") or f"{civic} {lieu.get('rue', '')}".strip()439440 est = _post(opener, URL_ESTIM, {"cleUnique": cle_unique,441 "idConso": id_conso})442 if not est:443 con.close()444 return {"disponible": False, "raison": "estimation indisponible"}445 an, mens, kwh = _montant(est)446 if not an:447 _mark_negatif(con, cle, uid)448 con.close()449 return {"disponible": False, "raison": "montant introuvable"}450 with con:451 con.execute(452 "INSERT OR REPLACE INTO hydro_cache "453 "(cle, adresse, cout_annuel, cout_mensuel, payload, fetched_at, "454 "uid, kwh) VALUES (?,?,?,?,?,?,?,?)",455 (cle, adr, an, mens, json.dumps(est), time.time(), uid, kwh))456 con.close()457 return {"disponible": True, "adresse": adr, "cout_annuel": an,458 "cout_mensuel": mens, "kwh_annuel": kwh, "cache": False}459460461def _main_db() -> Path | None:462 d = DB_PATH.parent463 for n in ("louka.db", "immoka.db", "immo.db"):464 if (d / n).exists():465 return d / n466 return None467468469def precompute(limit: int = 100, budget: int = 40) -> dict:470 """Pré-calcule l'estimation Hydro des `limit` annonces les plus récentes471 non encore en cache. `budget` = nb max de résolutions captcha par appel472 (borne le coût ; le reliquat sera comblé aux cycles suivants).473474 Appelé au démarrage (100 dernières) et à chaque cycle de `watch` pour les475 nouvelles annonces — le cache persiste entre les releases (data/hydro.db).476 """477 db = _main_db()478 if db is None:479 return {"erreur": "base des annonces introuvable"}480 src = sqlite3.connect(f"file:{db}?mode=ro", uri=True)481 src.row_factory = sqlite3.Row482 rows = src.execute(483 "SELECT uid, address, lat, lng FROM listings "484 "WHERE address IS NOT NULL AND address != '' "485 "ORDER BY first_seen DESC LIMIT ?", (limit,)).fetchall()486 src.close()487488 con = _connect()489 fait = calcules = saut = echec = negatif = 0490 for r in rows:491 # déjà traité pour cet uid ? succès (TTL) ou échec récent (NEG_TTL) —492 # dans les deux cas on ne re-résout PAS de captcha493 cached = con.execute(494 "SELECT cout_annuel FROM hydro_cache WHERE uid=? AND ("495 "(cout_annuel IS NOT NULL AND fetched_at>?) OR "496 "(cout_annuel IS NULL AND fetched_at>?))",497 (r["uid"], time.time() - TTL, time.time() - NEG_TTL)).fetchone()498 if cached is not None:499 if cached["cout_annuel"] is not None:500 fait += 1501 else:502 negatif += 1503 continue504 civic = _civic(r["address"])505 if not civic or (r["lat"] is None and not _parse_addr(r["address"])):506 saut += 1507 continue508 if calcules >= budget:509 break510 con.close() # estimate() ouvre sa propre connexion511 res = estimate(adresse=r["address"], lat=r["lat"], lng=r["lng"],512 uid=r["uid"])513 con = _connect()514 calcules += 1515 if not res.get("disponible"):516 echec += 1517 con.close()518 stats = {"vises": len(rows), "deja_en_cache": fait,519 "deja_echoue": negatif, "nouveaux_calcules": calcules,520 "sans_adresse": saut, "echecs": echec, "budget": budget}521 print(f"[hydro] précalcul : {stats}")522 return stats523