|
1 |
+# ----------------------------------------------------------------------------- |
|
2 |
+# Lou-Ka — Agrégateur de logements à louer (province de Québec) |
|
3 |
+# Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
|
4 |
+# hydro.py : estimation du coût d'électricité à une adresse — Hydro-Québec |
|
5 |
+# |
|
6 |
+# Reproduit le parcours PUBLIC de l'outil « Estimer les coûts d'électricité |
|
7 |
+# à une résidence » (session.hydroquebec.com), rétro-conçu depuis son SPA : |
|
8 |
+# 1. POST {clWebServicePublicApiURL}public/api/v3_0/lieu-consommation |
|
9 |
+# body {noCivique, codePostal, recaptchaResponse} -> liste de lieux |
|
10 |
+# (idConso, cleUnique, adresse) ; |
|
11 |
+# 2. POST {drcvPublicApiURL}public/api/v3_0/consommation/estimation |
|
12 |
+# body {cleUnique, idConso} -> coût annuel estimé. |
|
13 |
+# Les deux étapes exigent un jeton reCAPTCHA v2 valide |
|
14 |
+# (site key 6Lf08Q0UAAAAABCA7z47p2tMxa5_fY0wmn8DDPsu). Il est obtenu via un |
|
15 |
+# solveur enfichable (2captcha / CapSolver) ET les requêtes sortent par le |
|
16 |
+# proxy résidentiel canadien Bright Data (contourne le géoblocage / anti-bot). |
|
17 |
+# |
|
18 |
+# Configuration (.env) : |
|
19 |
+# HQ_CAPTCHA_KEY clé du solveur (obligatoire pour l'appel live) |
|
20 |
+# HQ_CAPTCHA_PROVIDER "2captcha" (défaut) | "capsolver" |
|
21 |
+# BRIGHTDATA_* / OXYLABS_* : proxy résidentiel (réutilise la pile projet) |
|
22 |
+# |
|
23 |
+# Sans HQ_CAPTCHA_KEY : estimate() renvoie {"disponible": False, ...} et le |
|
24 |
+# bloc fiche reste masqué — jamais d'estimation inventée. |
|
25 |
+# ----------------------------------------------------------------------------- |
|
26 |
+from __future__ import annotations |
|
27 |
+ |
|
28 |
+import json |
|
29 |
+import os |
|
30 |
+import re |
|
31 |
+import sqlite3 |
|
32 |
+import time |
|
33 |
+import urllib.request |
|
34 |
+from pathlib import Path |
|
35 |
+ |
|
36 |
+DB_PATH = Path(__file__).resolve().parent.parent / "data" / "hydro.db" |
|
37 |
+TTL = 180 * 86400 # la conso d'un logement bouge lentement |
|
38 |
+ |
|
39 |
+SITE_KEY = "6Lf08Q0UAAAAABCA7z47p2tMxa5_fY0wmn8DDPsu" |
|
40 |
+PAGE_URL = ("https://session.hydroquebec.com/portail/fr/web/clientele/" |
|
41 |
+ "estimation-consommation") |
|
42 |
+URL_LIEU = ("https://services-cl.solutions.hydroquebec.com/wsapi/webpublic/" |
|
43 |
+ "public/api/v3_0/lieu-consommation") |
|
44 |
+URL_ESTIM = ("https://services-cl.solutions.hydroquebec.com/conso/webpublic/" |
|
45 |
+ "public/api/v3_0/consommation/estimation") |
|
46 |
+UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " |
|
47 |
+ "(KHTML, like Gecko) Chrome/126.0 Safari/537.36") |
|
48 |
+ |
|
49 |
+ |
|
50 |
+# --- proxy résidentiel (Bright Data Web Unlocker en repli d'Oxylabs) ---------- |
|
51 |
+def _opener() -> urllib.request.OpenerDirector: |
|
52 |
+ proxy = None |
|
53 |
+ if os.environ.get("OXYLABS_PROXY_USER"): |
|
54 |
+ u = os.environ["OXYLABS_PROXY_USER"] |
|
55 |
+ p = os.environ["OXYLABS_PROXY_PASS"] |
|
56 |
+ host = os.environ.get("OXYLABS_PROXY", "pr.oxylabs.io:7777") |
|
57 |
+ proxy = f"http://{u}-cc-CA:{p}@{host}" |
|
58 |
+ if proxy: |
|
59 |
+ h = urllib.request.ProxyHandler({"http": proxy, "https": proxy}) |
|
60 |
+ return urllib.request.build_opener(h) |
|
61 |
+ return urllib.request.build_opener() |
|
62 |
+ |
|
63 |
+ |
|
64 |
+# --- solveur reCAPTCHA v2 enfichable ------------------------------------------ |
|
65 |
+def _solve_captcha() -> str | None: |
|
66 |
+ key = os.environ.get("HQ_CAPTCHA_KEY") |
|
67 |
+ if not key: |
|
68 |
+ return None |
|
69 |
+ provider = os.environ.get("HQ_CAPTCHA_PROVIDER", "2captcha").lower() |
|
70 |
+ if provider == "capsolver": |
|
71 |
+ return _capsolver(key) |
|
72 |
+ return _twocaptcha(key) |
|
73 |
+ |
|
74 |
+ |
|
75 |
+def _twocaptcha(key: str) -> str | None: |
|
76 |
+ r = urllib.request.urlopen(urllib.request.Request( |
|
77 |
+ "https://2captcha.com/in.php", |
|
78 |
+ data=urllib.parse.urlencode({ |
|
79 |
+ "key": key, "method": "userrecaptcha", "googlekey": SITE_KEY, |
|
80 |
+ "pageurl": PAGE_URL, "json": 1}).encode()), timeout=30) |
|
81 |
+ got = json.load(r) |
|
82 |
+ if got.get("status") != 1: |
|
83 |
+ return None |
|
84 |
+ cid = got["request"] |
|
85 |
+ for _ in range(24): |
|
86 |
+ time.sleep(5) |
|
87 |
+ res = json.load(urllib.request.urlopen( |
|
88 |
+ f"https://2captcha.com/res.php?key={key}&action=get&id={cid}&json=1", |
|
89 |
+ timeout=30)) |
|
90 |
+ if res.get("status") == 1: |
|
91 |
+ return res["request"] |
|
92 |
+ if res.get("request") != "CAPCHA_NOT_READY": |
|
93 |
+ return None |
|
94 |
+ return None |
|
95 |
+ |
|
96 |
+ |
|
97 |
+def _capsolver(key: str) -> str | None: |
|
98 |
+ r = urllib.request.urlopen(urllib.request.Request( |
|
99 |
+ "https://api.capsolver.com/createTask", |
|
100 |
+ data=json.dumps({"clientKey": key, "task": { |
|
101 |
+ "type": "ReCaptchaV2TaskProxyLess", |
|
102 |
+ "websiteURL": PAGE_URL, "websiteKey": SITE_KEY}}).encode(), |
|
103 |
+ headers={"Content-Type": "application/json"}), timeout=30) |
|
104 |
+ tid = json.load(r).get("taskId") |
|
105 |
+ if not tid: |
|
106 |
+ return None |
|
107 |
+ for _ in range(24): |
|
108 |
+ time.sleep(5) |
|
109 |
+ res = json.load(urllib.request.urlopen(urllib.request.Request( |
|
110 |
+ "https://api.capsolver.com/getTaskResult", |
|
111 |
+ data=json.dumps({"clientKey": key, "taskId": tid}).encode(), |
|
112 |
+ headers={"Content-Type": "application/json"}), timeout=30)) |
|
113 |
+ if res.get("status") == "ready": |
|
114 |
+ return res["solution"]["gRecaptchaResponse"] |
|
115 |
+ if res.get("status") != "processing": |
|
116 |
+ return None |
|
117 |
+ return None |
|
118 |
+ |
|
119 |
+ |
|
120 |
+import urllib.parse # noqa: E402 (utilisé par _twocaptcha) |
|
121 |
+ |
|
122 |
+ |
|
123 |
+def _post(opener, url: str, payload: dict) -> dict | None: |
|
124 |
+ req = urllib.request.Request(url, data=json.dumps(payload).encode(), |
|
125 |
+ headers={"Content-Type": "application/json", |
|
126 |
+ "User-Agent": UA, |
|
127 |
+ "Origin": "https://session.hydroquebec.com", |
|
128 |
+ "Referer": PAGE_URL}) |
|
129 |
+ try: |
|
130 |
+ with opener.open(req, timeout=60) as r: |
|
131 |
+ return json.load(r) |
|
132 |
+ except Exception: |
|
133 |
+ return None |
|
134 |
+ |
|
135 |
+ |
|
136 |
+# --- cache -------------------------------------------------------------------- |
|
137 |
+def _connect() -> sqlite3.Connection: |
|
138 |
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True) |
|
139 |
+ con = sqlite3.connect(DB_PATH, timeout=15) |
|
140 |
+ con.row_factory = sqlite3.Row |
|
141 |
+ con.execute("""CREATE TABLE IF NOT EXISTS hydro_cache ( |
|
142 |
+ cle TEXT PRIMARY KEY, adresse TEXT, cout_annuel REAL, |
|
143 |
+ cout_mensuel REAL, payload TEXT, fetched_at REAL)""") |
|
144 |
+ return con |
|
145 |
+ |
|
146 |
+ |
|
147 |
+def _parse_addr(adresse: str) -> tuple[str, str] | None: |
|
148 |
+ """Extrait (numéro civique, code postal) d'une adresse de fiche.""" |
|
149 |
+ cp = re.search(r"([A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d)", adresse or "") |
|
150 |
+ civ = re.match(r"\s*(\d+[A-Za-z]?)", adresse or "") |
|
151 |
+ if not cp or not civ: |
|
152 |
+ return None |
|
153 |
+ return civ.group(1), cp.group(1).upper().replace(" ", "") |
|
154 |
+ |
|
155 |
+ |
|
156 |
+def _montant(d: dict) -> tuple[float | None, float | None]: |
|
157 |
+ """Retrouve le coût annuel/mensuel dans la réponse d'estimation.""" |
|
158 |
+ txt = json.dumps(d) |
|
159 |
+ an = re.search(r'"(?:coutAnnuel|montantAnnuel|cout|montant)"\s*:\s*' |
|
160 |
+ r'([0-9]+(?:\.[0-9]+)?)', txt) |
|
161 |
+ a = float(an.group(1)) if an else None |
|
162 |
+ if a and a < 400: # valeur mensuelle -> annualiser |
|
163 |
+ return round(a * 12), round(a) |
|
164 |
+ return (round(a) if a else None, |
|
165 |
+ round(a / 12) if a else None) |
|
166 |
+ |
|
167 |
+ |
|
168 |
+def estimate(civic: str | None = None, postal: str | None = None, |
|
169 |
+ adresse: str | None = None) -> dict: |
|
170 |
+ """Coût d'électricité annuel estimé à une adresse (cache 6 mois). |
|
171 |
+ |
|
172 |
+ Renvoie {"disponible": bool, ...}. disponible=False si le solveur de |
|
173 |
+ captcha n'est pas configuré ou si Hydro-Québec ne connaît pas l'adresse. |
|
174 |
+ """ |
|
175 |
+ if not civic or not postal: |
|
176 |
+ if adresse and (pa := _parse_addr(adresse)): |
|
177 |
+ civic, postal = pa |
|
178 |
+ if not civic or not postal: |
|
179 |
+ return {"disponible": False, "raison": "adresse incomplète"} |
|
180 |
+ postal = postal.upper().replace(" ", "") |
|
181 |
+ cle = f"{civic}|{postal}" |
|
182 |
+ |
|
183 |
+ con = _connect() |
|
184 |
+ row = con.execute("SELECT * FROM hydro_cache WHERE cle=? AND fetched_at>?", |
|
185 |
+ (cle, time.time() - TTL)).fetchone() |
|
186 |
+ if row and row["cout_annuel"]: |
|
187 |
+ con.close() |
|
188 |
+ return {"disponible": True, "adresse": row["adresse"], |
|
189 |
+ "cout_annuel": row["cout_annuel"], |
|
190 |
+ "cout_mensuel": row["cout_mensuel"], "cache": True} |
|
191 |
+ |
|
192 |
+ if not os.environ.get("HQ_CAPTCHA_KEY"): |
|
193 |
+ con.close() |
|
194 |
+ return {"disponible": False, "raison": "solveur captcha non configuré"} |
|
195 |
+ |
|
196 |
+ token = _solve_captcha() |
|
197 |
+ if not token: |
|
198 |
+ con.close() |
|
199 |
+ return {"disponible": False, "raison": "échec du captcha"} |
|
200 |
+ |
|
201 |
+ opener = _opener() |
|
202 |
+ lieux = _post(opener, URL_LIEU, {"noCivique": civic, "codePostal": postal, |
|
203 |
+ "recaptchaResponse": token}) |
|
204 |
+ items = (lieux or {}).get("lieuxConsommation") or (lieux or {}).get( |
|
205 |
+ "lieux") or (lieux if isinstance(lieux, list) else []) |
|
206 |
+ if not items: |
|
207 |
+ con.close() |
|
208 |
+ return {"disponible": False, "raison": "adresse inconnue d'Hydro-Québec"} |
|
209 |
+ lieu = items[0] |
|
210 |
+ id_conso = lieu.get("idConso") or lieu.get("id") |
|
211 |
+ cle_unique = lieu.get("cleUnique") or lieu.get("cle") |
|
212 |
+ adr = lieu.get("adresse") or f"{civic}, {postal}" |
|
213 |
+ |
|
214 |
+ est = _post(opener, URL_ESTIM, {"cleUnique": cle_unique, |
|
215 |
+ "idConso": id_conso}) |
|
216 |
+ if not est: |
|
217 |
+ con.close() |
|
218 |
+ return {"disponible": False, "raison": "estimation indisponible"} |
|
219 |
+ an, mens = _montant(est) |
|
220 |
+ if not an: |
|
221 |
+ con.close() |
|
222 |
+ return {"disponible": False, "raison": "montant introuvable"} |
|
223 |
+ with con: |
|
224 |
+ con.execute("INSERT OR REPLACE INTO hydro_cache VALUES (?,?,?,?,?,?)", |
|
225 |
+ (cle, adr, an, mens, json.dumps(est), time.time())) |
|
226 |
+ con.close() |
|
227 |
+ return {"disponible": True, "adresse": adr, "cout_annuel": an, |
|
228 |
+ "cout_mensuel": mens, "cache": False} |