Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Immo·Ka10# File : immoka/inspecteurs.py11# Module : immoka12# 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# Immo-Ka — Annuaire des inspecteurs en bâtiment du Québec90# inspecteurs.py : sert data/inspecteurs.json — entreprises d'inspection de91# bâtiment couvrant les 17 régions administratives (Google Places via Serper).92# Régénération du dataset : scripts/build_inspecteurs.py puis remplacer le JSON.93# NB : le JSON garde la clé générique « movers » (pipeline partagé avec94# l'annuaire des déménageurs) — ce sont les entrées de l'annuaire.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import threading100from pathlib import Path101102from fastapi import APIRouter103104ROOT = Path(__file__).resolve().parent.parent105DATA = ROOT / "data" / "inspecteurs.json"106107router = APIRouter()108_cache: dict = {"mtime": None, "doc": None}109_lock = threading.Lock()110111112def load() -> dict:113 """Charge (avec cache par mtime) l'annuaire canonique des inspecteurs."""114 try:115 mtime = DATA.stat().st_mtime116 except FileNotFoundError:117 return {"generated": None, "count": 0, "movers": [], "regions": []}118 with _lock:119 if _cache["doc"] is None or mtime != _cache["mtime"]:120 from . import public121 doc = json.loads(DATA.read_text(encoding="utf-8"))122 regs: dict[str, int] = {}123 fixed = 0124 for m in doc.get("movers", []):125 # La région du fichier est celle de la ville BALAYÉE lors de la126 # collecte, pas toujours celle de l'entreprise trouvée (une127 # entreprise de Charlesbourg classée « Bas-Saint-Laurent »). On la128 # recalcule d'après les coordonnées de l'entreprise quand elle en a.129 stated = public.region_name(m.get("region")) or m.get("region")130 by_city = public.region_index()["city_region"].get(m.get("city") or "")131 reg = stated132 if m.get("lat") is not None:133 # deux indices indépendants doivent s'accorder (les cellules134 # de 10 km chevauchent les frontières : Bécancour / Trois-Rivières)135 here = public.region_at(m["lat"], m["lng"])136 if here and here == by_city:137 reg = here138 elif here and by_city is None:139 reg = public.region_at(m["lat"], m["lng"], 0.95) or stated140 if reg != m.get("region"):141 m["region_source"] = m.get("region")142 m["region"] = reg143 fixed += 1144 regs[m["region"]] = regs.get(m["region"], 0) + 1145 doc["regions_fixed"] = fixed146 doc["regions"] = [{"region": r, "n": n}147 for r, n in sorted(regs.items(),148 key=lambda x: (-x[1], x[0]))]149 _cache["doc"], _cache["mtime"] = doc, mtime150 return _cache["doc"]151152153@router.get("/api/inspecteurs")154def api_inspecteurs(region: str | None = None, q: str | None = None):155 """Annuaire des inspecteurs en bâtiment du Québec (filtres : région, texte)."""156 doc = load()157 movers = doc.get("movers", [])158 if region:159 movers = [m for m in movers if m["region"] == region]160 if q:161 needle = q.strip().lower()162 movers = [m for m in movers163 if needle in (m["name"] + " " + m["city"]).lower()]164 return {"generated": doc.get("generated"),165 "total": doc.get("count", 0),166 "count": len(movers),167 "regions": doc.get("regions", []),168 "movers": movers}169