SPB Git

Repository Public

geocode_stores.py 7.8 KB 203 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Fabri·Ka10# File             : scripts/geocode_stores.py11# Description      : Phase 2 — géocodage massif des boutiques via leur RTA12#                    (postal_prefix).13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1916# Last Modified    : 2026-08-1917#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Phase 2 — géocodage massif des boutiques via leur RTA (postal_prefix).9192Le registre porte un préfixe postal (RTA, ex. « J0V ») pour 86,6 % des93boutiques mais aucune n'était géocodée. On géocode chaque RTA UNIQUE94(≈ 360) via Nominatim — politesse 1 req/s, cache disque95data/geocode_cache/fsa.json (seedé une fois, rejouable sans réseau) —96puis on propage ville approx. + lat/lng à toutes les boutiques porteuses.9798Précision : centroïde de la RTA (quartier/secteur), pas l'adresse civique —99suffisant pour une carte régionale et le tri par proximité. La ville n'est100écrite que si Nominatim la fournit (aucune donnée inventée).101102Écrit : stores.city (si vide) / stores.lat / stores.lng en DB103        + champ "geo" {lat,lng,city,precision:"fsa"} dans data/stores.json.104105Usage : .venv/bin/python scripts/geocode_stores.py [--dry-run] [--max-requests N]106"""107import argparse108import json109import os110import sys111import time112113import requests114115ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))116sys.path.insert(0, ROOT)117CACHE_DIR = os.path.join(ROOT, "data", "geocode_cache")118os.makedirs(CACHE_DIR, exist_ok=True)119CACHE = os.path.join(CACHE_DIR, "fsa.json")120121from fabrika import db as fdb  # noqa: E402122123# Nominatim ne résout PAS les RTA seules (postalcode=H2X -> []), constaté le124# 2026-08-19. zippopotam.us les résout nativement pour le Canada (centroïde +125# nom du secteur). Même politesse : 1 req/s, cache disque.126ZIPPO = "https://api.zippopotam.us/CA/{fsa}"127HDRS = {"User-Agent": "FabriKaBot/1.0 (+https://www.fabri-ka.com/bot; contact@spboucher.ai)"}128129130def geocode_fsa(fsa: str) -> dict | None:131    """RTA -> {lat, lng, city} via zippopotam.us (données GeoNames)."""132    r = requests.get(ZIPPO.format(fsa=fsa), headers=HDRS, timeout=20)133    if r.status_code == 404:134        return None135    r.raise_for_status()136    data = r.json()137    places = data.get("places") or []138    if not places:139        return None140    p = places[0]141    if (p.get("state abbreviation") or "") not in ("QC", ""):142        return None            # garde-fou : rester au Québec143    return {"lat": round(float(p["latitude"]), 5),144            "lng": round(float(p["longitude"]), 5),145            "city": (p.get("place name") or "").strip()}146147148def main():149    ap = argparse.ArgumentParser()150    ap.add_argument("--dry-run", action="store_true")151    ap.add_argument("--max-requests", type=int, default=400)152    args = ap.parse_args()153154    reg_path = os.path.join(ROOT, "data", "stores.json")155    reg = json.load(open(reg_path))156    fsas = sorted({(s.get("postal_prefix") or "").strip().upper()[:3]157                   for s in reg["stores"] if s.get("postal_prefix")})158    cache = json.load(open(CACHE)) if os.path.exists(CACHE) else {}159    todo = [f for f in fsas if f not in cache][:args.max_requests]160    print(f"[geocode] {len(fsas)} RTA uniques, {len(todo)} à résoudre "161          f"(cache: {len(cache)})", flush=True)162163    n_req = 0164    for fsa in todo:165        try:166            cache[fsa] = geocode_fsa(fsa)167        except Exception as exc:168            print(f"  ! {fsa}: {exc}", flush=True)169        n_req += 1170        if n_req % 25 == 0:171            print(f"  {n_req}/{len(todo)}", flush=True)172            json.dump(cache, open(CACHE, "w"))173        time.sleep(1.1)          # politesse Nominatim : 1 req/s max174    json.dump(cache, open(CACHE, "w"))175    resolved = {k: v for k, v in cache.items() if v}176    print(f"[geocode] RTA résolues : {len(resolved)}/{len(fsas)} "177          f"({n_req} requêtes réseau)")178179    if args.dry_run:180        return181182    n_store = 0183    con = fdb.connect()184    for s in reg["stores"]:185        fsa = (s.get("postal_prefix") or "").strip().upper()[:3]186        geo = resolved.get(fsa)187        if not geo:188            continue189        s["geo"] = {"lat": geo["lat"], "lng": geo["lng"],190                    "city": geo["city"], "precision": "fsa"}191        con.execute("UPDATE stores SET lat=?, lng=?, "192                    "city=CASE WHEN COALESCE(city,'')='' THEN ? ELSE city END "193                    "WHERE id=?",194                    (geo["lat"], geo["lng"], geo["city"], s["id"]))195        n_store += 1196    con.commit(); con.close()197    json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)198    print(f"[geocode] boutiques géocodées : {n_store}")199200201if __name__ == "__main__":202    main()203
Files main
Menu

Theme