Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Lou·Ka10# File : scripts/build_demenageurs.py11# Module : scripts12# Repository : https://git.spboucher.ai/lou-ka13# Created : 2026-08-2414# Last Modified : 2026-08-2415#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author : Simon-Pierre Boucher21# Position : Professor of Finance22# Institution : Université du Québec en Outaouais (UQO)23# Department : Département des sciences administratives24# Organization : SP Boucher25#26# Website : https://spboucher.ai27# Git : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General : info@spboucher.ai34# Professional : contact@spboucher.ai35# Direct : simon@spboucher.ai36# Research : research@spboucher.ai37# Development : dev@spboucher.ai38# Support : support@spboucher.ai39# Security/Admin : admin@spboucher.ai40# Notifications : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification : Public67# Distribution : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License : None specified (no license file in this repository)81# Maintainer : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# -----------------------------------------------------------------------------89# Groupe KA — Annuaire des déménageurs du Québec90# build_demenageurs.py : balayage Serper Places sur ~200 villes des 17 régions91# administratives, filtre « déménagement », dédoublonnage CID/téléphone,92# sortie canonique data/demenageurs.json (consommée par Lou-Ka et Immo-Ka).93# -----------------------------------------------------------------------------94from __future__ import annotations9596import json97import os98import re99import sys100import time101import unicodedata102from concurrent.futures import ThreadPoolExecutor, as_completed103from pathlib import Path104from threading import Lock105from urllib.request import Request, urlopen106107API_KEY = os.environ.get("SERPER_API_KEY", "")108OUT = Path(__file__).parent / "demenageurs.json"109110# Région administrative → villes balayées (couverture provinciale complète)111REGIONS: dict[str, list[str]] = {112 "Bas-Saint-Laurent": [113 "Rimouski", "Rivière-du-Loup", "Matane", "Mont-Joli", "Amqui",114 "La Pocatière", "Témiscouata-sur-le-Lac", "Trois-Pistoles", "Dégelis"],115 "Saguenay–Lac-Saint-Jean": [116 "Saguenay", "Chicoutimi", "Jonquière", "La Baie", "Alma",117 "Dolbeau-Mistassini", "Roberval", "Saint-Félicien", "Normandin"],118 "Capitale-Nationale": [119 "Québec", "L'Ancienne-Lorette", "Saint-Augustin-de-Desmaures",120 "Beaupré", "Baie-Saint-Paul", "La Malbaie", "Donnacona", "Pont-Rouge",121 "Saint-Raymond", "Sainte-Catherine-de-la-Jacques-Cartier",122 "Stoneham-et-Tewkesbury", "Boischatel", "Château-Richer"],123 "Mauricie": [124 "Trois-Rivières", "Shawinigan", "La Tuque", "Louiseville",125 "Saint-Tite", "Saint-Étienne-des-Grès"],126 "Estrie": [127 "Sherbrooke", "Magog", "Granby", "Cowansville", "Bromont",128 "Coaticook", "Lac-Mégantic", "Windsor", "East Angus",129 "Val-des-Sources", "Waterloo"],130 "Montréal": [131 "Montréal", "Montréal-Nord", "Saint-Laurent Montréal", "LaSalle",132 "Anjou", "Ahuntsic", "Rosemont", "Hochelaga-Maisonneuve",133 "Le Plateau-Mont-Royal", "Verdun", "Lachine", "Pierrefonds",134 "Rivière-des-Prairies", "Côte-des-Neiges", "Westmount",135 "Côte-Saint-Luc", "Dollard-des-Ormeaux", "Pointe-Claire", "Dorval",136 "Kirkland", "Beaconsfield", "Sainte-Anne-de-Bellevue", "Outremont",137 "Mont-Royal"],138 "Outaouais": [139 "Gatineau", "Hull Gatineau", "Aylmer Gatineau", "Buckingham Gatineau",140 "Cantley", "Chelsea", "Val-des-Monts", "Maniwaki", "Papineauville",141 "La Pêche"],142 "Abitibi-Témiscamingue": [143 "Rouyn-Noranda", "Val-d'Or", "Amos", "La Sarre", "Ville-Marie QC",144 "Senneterre", "Malartic"],145 "Côte-Nord": [146 "Baie-Comeau", "Sept-Îles", "Port-Cartier", "Forestville",147 "Havre-Saint-Pierre", "Fermont"],148 "Nord-du-Québec": [149 "Chibougamau", "Lebel-sur-Quévillon", "Matagami", "Chapais"],150 "Gaspésie–Îles-de-la-Madeleine": [151 "Gaspé", "Chandler", "New Richmond", "Bonaventure",152 "Carleton-sur-Mer", "Sainte-Anne-des-Monts", "Percé",153 "Les Îles-de-la-Madeleine"],154 "Chaudière-Appalaches": [155 "Lévis", "Saint-Georges", "Thetford Mines", "Montmagny",156 "Sainte-Marie", "Beauceville", "Saint-Joseph-de-Beauce", "L'Islet",157 "Lac-Etchemin", "Saint-Anselme", "Saint-Henri"],158 "Laval": ["Laval", "Chomedey Laval", "Sainte-Rose Laval"],159 "Lanaudière": [160 "Terrebonne", "Repentigny", "Mascouche", "Joliette", "L'Assomption",161 "Rawdon", "Saint-Lin-Laurentides", "Berthierville", "Lavaltrie",162 "Saint-Charles-Borromée", "Chertsey"],163 "Laurentides": [164 "Saint-Jérôme", "Blainville", "Boisbriand", "Sainte-Thérèse",165 "Mirabel", "Saint-Eustache", "Deux-Montagnes", "Rosemère",166 "Bois-des-Filion", "Sainte-Adèle", "Sainte-Agathe-des-Monts",167 "Mont-Tremblant", "Mont-Laurier", "Prévost", "Saint-Sauveur",168 "Lachute", "Saint-Colomban"],169 "Montérégie": [170 "Longueuil", "Brossard", "Saint-Lambert", "Boucherville",171 "Saint-Bruno-de-Montarville", "Saint-Hubert Longueuil",172 "Châteauguay", "Saint-Jean-sur-Richelieu", "Salaberry-de-Valleyfield",173 "Vaudreuil-Dorion", "Saint-Hyacinthe", "Sorel-Tracy", "Beloeil",174 "Mont-Saint-Hilaire", "Chambly", "La Prairie", "Candiac",175 "Sainte-Catherine QC", "Saint-Constant", "Mercier", "Beauharnois",176 "Varennes", "Sainte-Julie", "Contrecoeur", "Marieville", "Farnham",177 "Acton Vale", "Rigaud", "L'Île-Perrot", "Pincourt", "Saint-Rémi"],178 "Centre-du-Québec": [179 "Drummondville", "Victoriaville", "Bécancour", "Nicolet",180 "Plessisville", "Princeville", "Kingsey Falls", "Warwick QC"],181}182183# Grandes villes : pagination plus profonde + variante de requête184BIG = {"Montréal", "Québec", "Laval", "Gatineau", "Longueuil", "Sherbrooke",185 "Trois-Rivières", "Saguenay", "Lévis", "Terrebonne", "Saint-Jérôme",186 "Brossard", "Repentigny", "Drummondville", "Saint-Jean-sur-Richelieu"}187188MOVER_RE = re.compile(r"demenag|moving|movers|transport et demenagement", re.I)189190_lock = Lock()191_stats = {"queries": 0, "kept": 0, "raw": 0}192193194def norm(s: str) -> str:195 return unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode()196197198def slugify(s: str) -> str:199 s = norm(s).lower()200 s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")201 return s or "x"202203204def norm_phone(p: str | None) -> str:205 d = re.sub(r"\D", "", p or "")206 return d[-10:] if len(d) >= 10 else d207208209def serper_places(q: str, page: int) -> list[dict]:210 body = json.dumps({"q": q, "gl": "ca", "hl": "fr", "page": page}).encode()211 req = Request("https://google.serper.dev/places", data=body,212 headers={"X-API-KEY": API_KEY, "Content-Type": "application/json"})213 for attempt in range(3):214 try:215 with urlopen(req, timeout=30) as r:216 with _lock:217 _stats["queries"] += 1218 return json.loads(r.read()).get("places", [])219 except Exception:220 time.sleep(2 * (attempt + 1))221 return []222223224def is_mover(p: dict) -> bool:225 return bool(MOVER_RE.search(norm(p.get("category", "")))226 or MOVER_RE.search(norm(p.get("title", ""))))227228229def in_quebec(p: dict) -> bool:230 addr = p.get("address", "")231 return (", QC" in addr or " QC " in addr or addr.endswith(" QC")232 or not addr) # certaines fiches n'ont pas d'adresse : région du balayage233234235CITY_RE = re.compile(r",\s*([^,]+?),\s*(?:QC|Québec)\b")236237238def parse_city(addr: str) -> str:239 m = CITY_RE.search(addr or "")240 return m.group(1).strip() if m else ""241242243def sweep_city(region: str, city: str) -> list[dict]:244 label = city.replace(" QC", "").replace(" Montréal", "").replace(" Gatineau", "").replace(" Laval", "").replace(" Longueuil", "")245 queries = [f"déménageur {city} QC"]246 max_pages = 5 if city in BIG else 3247 if city in BIG:248 queries.append(f"entreprise de déménagement {city} QC")249 out = []250 for q in queries:251 for page in range(1, max_pages + 1):252 places = serper_places(q, page)253 with _lock:254 _stats["raw"] += len(places)255 for p in places:256 if is_mover(p) and in_quebec(p):257 p["_region"] = region258 p["_query_city"] = label259 out.append(p)260 if len(places) < 10:261 break262 return out263264265def main() -> None:266 if not API_KEY:267 sys.exit("SERPER_API_KEY manquante")268 jobs = [(r, c) for r, cities in REGIONS.items() for c in cities]269 # ville balayée → région (pour rattacher la ville réelle de l'adresse)270 city_region = {}271 for r, cities in REGIONS.items():272 for c in cities:273 city_region[norm(c.split(" QC")[0]).lower()] = r274275 raw: list[dict] = []276 with ThreadPoolExecutor(max_workers=8) as ex:277 futs = {ex.submit(sweep_city, r, c): (r, c) for r, c in jobs}278 done = 0279 for f in as_completed(futs):280 raw.extend(f.result())281 done += 1282 if done % 25 == 0:283 print(f" … {done}/{len(jobs)} villes, {len(raw)} fiches brutes, "284 f"{_stats['queries']} requêtes", flush=True)285286 # Dédoublonnage : CID d'abord, sinon téléphone, sinon (nom, ville)287 by_key: dict[str, dict] = {}288 for p in raw:289 key = ("cid:" + p["cid"]) if p.get("cid") else ""290 if not key:291 ph = norm_phone(p.get("phoneNumber"))292 key = ("tel:" + ph) if ph else ("nc:" + slugify(p.get("title", "")) + ":" + slugify(parse_city(p.get("address", ""))))293 cur = by_key.get(key)294 if cur is None or (not cur.get("website") and p.get("website")):295 if cur:296 p.setdefault("_region", cur["_region"])297 by_key[key] = p298299 movers = []300 seen_slug: set[str] = set()301 for p in by_key.values():302 addr_city = parse_city(p.get("address", ""))303 region = city_region.get(norm(addr_city).lower(), p["_region"])304 city = addr_city or p["_query_city"]305 base = slugify(f"{p.get('title','')}-{city}")306 slug = base307 i = 2308 while slug in seen_slug:309 slug = f"{base}-{i}"310 i += 1311 seen_slug.add(slug)312 movers.append({313 "id": slug,314 "name": (p.get("title") or "").strip(),315 "city": city,316 "region": region,317 "address": p.get("address", ""),318 "phone": p.get("phoneNumber", ""),319 "website": p.get("website", ""),320 "rating": p.get("rating"),321 "reviews": p.get("ratingCount"),322 "lat": p.get("latitude"),323 "lng": p.get("longitude"),324 "category": p.get("category", ""),325 "cid": p.get("cid", ""),326 })327328 movers.sort(key=lambda m: (norm(m["region"]), norm(m["city"]), norm(m["name"])))329 doc = {330 "generated": time.strftime("%Y-%m-%d"),331 "source": "Google Places via Serper — balayage " + str(len(jobs)) + " villes, 17 régions",332 "count": len(movers),333 "movers": movers,334 }335 OUT.write_text(json.dumps(doc, ensure_ascii=False, indent=1), encoding="utf-8")336 regions = {}337 for m in movers:338 regions[m["region"]] = regions.get(m["region"], 0) + 1339 print(f"\n✅ {len(movers)} déménageurs uniques ({_stats['raw']} fiches brutes, "340 f"{_stats['queries']} requêtes Serper) → {OUT}")341 for r, n in sorted(regions.items(), key=lambda x: -x[1]):342 print(f" {r}: {n}")343344345if __name__ == "__main__":346 main()347