SPB Git

Repository Public

build_inspecteurs.py 14.1 KB 348 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Immo·Ka10# File             : scripts/build_inspecteurs.py11# Module           : scripts12# Repository       : https://git.spboucher.ai/immo-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 inspecteurs en bâtiment du Québec90# build_inspecteurs.py : balayage Serper Places sur ~200 villes des 17 régions91# administratives, filtre « inspection de bâtiment », dédoublonnage92# CID/téléphone, sortie canonique data/inspecteurs.json (consommée par 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 / "inspecteurs.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"inspect", re.I)189EXCLUDE_RE = re.compile(r"auto|vehicul|camion|mecanique|pneu|extermin|parasit|ascenseur|saaq|voiture|urbanisme|securite publique|metallurg|agricole|sanitaire", re.I)190191_lock = Lock()192_stats = {"queries": 0, "kept": 0, "raw": 0}193194195def norm(s: str) -> str:196    return unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode()197198199def slugify(s: str) -> str:200    s = norm(s).lower()201    s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")202    return s or "x"203204205def norm_phone(p: str | None) -> str:206    d = re.sub(r"\D", "", p or "")207    return d[-10:] if len(d) >= 10 else d208209210def serper_places(q: str, page: int) -> list[dict]:211    body = json.dumps({"q": q, "gl": "ca", "hl": "fr", "page": page}).encode()212    req = Request("https://google.serper.dev/places", data=body,213                  headers={"X-API-KEY": API_KEY, "Content-Type": "application/json"})214    for attempt in range(3):215        try:216            with urlopen(req, timeout=30) as r:217                with _lock:218                    _stats["queries"] += 1219                return json.loads(r.read()).get("places", [])220        except Exception:221            time.sleep(2 * (attempt + 1))222    return []223224225def is_mover(p: dict) -> bool:226    blob = norm(p.get("category", "")) + " " + norm(p.get("title", ""))227    return bool(MOVER_RE.search(blob)) and not EXCLUDE_RE.search(blob)228229230def in_quebec(p: dict) -> bool:231    addr = p.get("address", "")232    return (", QC" in addr or " QC " in addr or addr.endswith(" QC")233            or not addr)  # certaines fiches n'ont pas d'adresse : région du balayage234235236CITY_RE = re.compile(r",\s*([^,]+?),\s*(?:QC|Québec)\b")237238239def parse_city(addr: str) -> str:240    m = CITY_RE.search(addr or "")241    return m.group(1).strip() if m else ""242243244def sweep_city(region: str, city: str) -> list[dict]:245    label = city.replace(" QC", "").replace(" Montréal", "").replace(" Gatineau", "").replace(" Laval", "").replace(" Longueuil", "")246    queries = [f"inspecteur en bâtiment {city} QC"]247    max_pages = 5 if city in BIG else 3248    if city in BIG:249        queries.append(f"inspection préachat {city} QC")250    out = []251    for q in queries:252        for page in range(1, max_pages + 1):253            places = serper_places(q, page)254            with _lock:255                _stats["raw"] += len(places)256            for p in places:257                if is_mover(p) and in_quebec(p):258                    p["_region"] = region259                    p["_query_city"] = label260                    out.append(p)261            if len(places) < 10:262                break263    return out264265266def main() -> None:267    if not API_KEY:268        sys.exit("SERPER_API_KEY manquante")269    jobs = [(r, c) for r, cities in REGIONS.items() for c in cities]270    # ville balayée → région (pour rattacher la ville réelle de l'adresse)271    city_region = {}272    for r, cities in REGIONS.items():273        for c in cities:274            city_region[norm(c.split(" QC")[0]).lower()] = r275276    raw: list[dict] = []277    with ThreadPoolExecutor(max_workers=8) as ex:278        futs = {ex.submit(sweep_city, r, c): (r, c) for r, c in jobs}279        done = 0280        for f in as_completed(futs):281            raw.extend(f.result())282            done += 1283            if done % 25 == 0:284                print(f"  … {done}/{len(jobs)} villes, {len(raw)} fiches brutes, "285                      f"{_stats['queries']} requêtes", flush=True)286287    # Dédoublonnage : CID d'abord, sinon téléphone, sinon (nom, ville)288    by_key: dict[str, dict] = {}289    for p in raw:290        key = ("cid:" + p["cid"]) if p.get("cid") else ""291        if not key:292            ph = norm_phone(p.get("phoneNumber"))293            key = ("tel:" + ph) if ph else ("nc:" + slugify(p.get("title", "")) + ":" + slugify(parse_city(p.get("address", ""))))294        cur = by_key.get(key)295        if cur is None or (not cur.get("website") and p.get("website")):296            if cur:297                p.setdefault("_region", cur["_region"])298            by_key[key] = p299300    movers = []301    seen_slug: set[str] = set()302    for p in by_key.values():303        addr_city = parse_city(p.get("address", ""))304        region = city_region.get(norm(addr_city).lower(), p["_region"])305        city = addr_city or p["_query_city"]306        base = slugify(f"{p.get('title','')}-{city}")307        slug = base308        i = 2309        while slug in seen_slug:310            slug = f"{base}-{i}"311            i += 1312        seen_slug.add(slug)313        movers.append({314            "id": slug,315            "name": (p.get("title") or "").strip(),316            "city": city,317            "region": region,318            "address": p.get("address", ""),319            "phone": p.get("phoneNumber", ""),320            "website": p.get("website", ""),321            "rating": p.get("rating"),322            "reviews": p.get("ratingCount"),323            "lat": p.get("latitude"),324            "lng": p.get("longitude"),325            "category": p.get("category", ""),326            "cid": p.get("cid", ""),327        })328329    movers.sort(key=lambda m: (norm(m["region"]), norm(m["city"]), norm(m["name"])))330    doc = {331        "generated": time.strftime("%Y-%m-%d"),332        "source": "Google Places via Serper — balayage " + str(len(jobs)) + " villes, 17 régions",333        "count": len(movers),334        "movers": movers,335    }336    OUT.write_text(json.dumps(doc, ensure_ascii=False, indent=1), encoding="utf-8")337    regions = {}338    for m in movers:339        regions[m["region"]] = regions.get(m["region"], 0) + 1340    print(f"\n✅ {len(movers)} inspecteurs uniques ({_stats['raw']} fiches brutes, "341          f"{_stats['queries']} requêtes Serper) → {OUT}")342    for r, n in sorted(regions.items(), key=lambda x: -x[1]):343        print(f"   {r}: {n}")344345346if __name__ == "__main__":347    main()348
Files main
Menu

Theme