Premier commit
Cette révision appartient à :
révision
f8b65c8f4e
121 fichiers modifiés
+2489804
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Collecteur carrefours nommes (OSM via overpass-api.de). Usage: python _collect_carrefours.py [slug ...]
|
||||
Definition: noeud OSM partage par >=2 voies highway in (trunk,primary,secondary,tertiary) portant
|
||||
>=2 noms (name) DISTINCTS. Noeuds a <=35 m fusionnes (ronds-points, chaussees separees)."""
|
||||
import sys, os, json, time, math, urllib.request, urllib.parse, urllib.error
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _collect_region import REGIONS, ROOT
|
||||
URL = "https://overpass-api.de/api/interpreter"
|
||||
UA = "FranceMapPOI/1.0 (contact: projet perso)"
|
||||
HW = "trunk|primary|secondary|tertiary"
|
||||
MERGE_M = 35
|
||||
REGIONS["auvergne-rhone-alpes"] = {"nom": "Auvergne-Rhone-Alpes", "departements": {
|
||||
"01":"Ain","03":"Allier","07":"Ardeche","15":"Cantal","26":"Drome","38":"Isere","42":"Loire",
|
||||
"43":"Haute-Loire","63":"Puy-de-Dome","69":"Rhone","73":"Savoie","74":"Haute-Savoie"}}
|
||||
def log(m): print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
||||
|
||||
def query(dcode):
|
||||
ql = (f'[out:json][timeout:180];'
|
||||
f'rel["boundary"="administrative"]["admin_level"="6"]["ref:INSEE"="{dcode}"];map_to_area->.a;'
|
||||
f'way(area.a)["highway"~"^({HW})$"]["name"];out geom qt;')
|
||||
data = urllib.parse.urlencode({"data": ql}).encode()
|
||||
for att in range(8):
|
||||
try:
|
||||
req = urllib.request.Request(URL, data=data, headers={"User-Agent": UA, "Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=700) as r:
|
||||
d = json.loads(r.read().decode("utf-8"))
|
||||
if "remark" in d and not d.get("elements"): raise RuntimeError(d["remark"][:200])
|
||||
return d
|
||||
except urllib.error.HTTPError as e:
|
||||
log(f" HTTP {e.code}"); time.sleep(30 if e.code in (429, 504) else 10)
|
||||
except Exception as e:
|
||||
log(f" erreur {e} (essai {att+1})"); time.sleep(20)
|
||||
raise RuntimeError("echec " + dcode)
|
||||
|
||||
def process(d):
|
||||
nodes = {} # id -> (lat, lon, {name: set(hw)}, nways, roundabout)
|
||||
nways = 0
|
||||
for w in d.get("elements", []):
|
||||
if w.get("type") != "way": continue
|
||||
t = w.get("tags", {}); nm = t.get("name")
|
||||
if not nm or "geometry" not in w: continue
|
||||
nways += 1
|
||||
for nid, g in zip(w["nodes"], w["geometry"]):
|
||||
if g is None: continue
|
||||
e = nodes.get(nid)
|
||||
if e is None: e = nodes[nid] = [g["lat"], g["lon"], {}, 0, False]
|
||||
e[2].setdefault(nm, set()).add(t["highway"]); e[3] += 1
|
||||
if t.get("junction") == "roundabout": e[4] = True
|
||||
cand = [(nid, e) for nid, e in nodes.items() if len(e[2]) >= 2]
|
||||
# fusion spatiale
|
||||
cell = {}; out = []
|
||||
for nid, e in cand:
|
||||
k = (round(e[0] / 0.0004), round(e[1] / 0.0006))
|
||||
merged = None
|
||||
for dx in (-1, 0, 1):
|
||||
for dy in (-1, 0, 1):
|
||||
for c in cell.get((k[0] + dx, k[1] + dy), []):
|
||||
dy_m = (c["lat"] - e[0]) * 111000
|
||||
dx_m = (c["lon"] - e[1]) * 111000 * math.cos(math.radians(e[0]))
|
||||
if math.hypot(dx_m, dy_m) <= MERGE_M: merged = c
|
||||
if merged:
|
||||
for n, hs in e[2].items(): merged["_n"].setdefault(n, set()).update(hs)
|
||||
merged["_ids"].append(nid); merged["rond"] |= e[4]
|
||||
else:
|
||||
c = {"lat": e[0], "lon": e[1], "_n": {n: set(h) for n, h in e[2].items()}, "_ids": [nid], "rond": e[4]}
|
||||
cell.setdefault(k, []).append(c); out.append(c)
|
||||
return out, nways, len(nodes), len(cand)
|
||||
|
||||
def main():
|
||||
slugs = sys.argv[1:] or list(REGIONS)
|
||||
for slug in slugs:
|
||||
reg = REGIONS[slug]; t0 = time.time(); entries = []; detail = {}; date = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
for dcode, dname in reg["departements"].items():
|
||||
t1 = time.time(); log(f"{slug} {dcode} {dname}")
|
||||
try:
|
||||
d = query(dcode)
|
||||
except Exception as e:
|
||||
detail[dcode] = {"departement": dname, "erreur": str(e)}; continue
|
||||
cs, nways, nn, ncand = process(d); del d
|
||||
for c in cs:
|
||||
names = sorted(c["_n"]); hws = sorted({h for hs in c["_n"].values() for h in hs})
|
||||
# classe la plus haute pour categorie
|
||||
rank = [h for h in ("trunk", "primary", "secondary", "tertiary") if h in hws]
|
||||
entries.append({
|
||||
"id": f"osm-node-{c['_ids'][0]}",
|
||||
"nom": "Carrefour " + " / ".join(names[:3]) + (" ..." if len(names) > 3 else ""),
|
||||
"categorie": "carrefour/rond-point" if c["rond"] else "carrefour/route",
|
||||
"type_detail": "+".join(rank),
|
||||
"lat": round(c["lat"], 7), "lon": round(c["lon"], 7),
|
||||
"departement": dcode,
|
||||
"voies": names, "nb_voies_nommees": len(names), "nb_noeuds_fusionnes": len(c["_ids"]),
|
||||
"source": "OpenStreetMap via overpass-api.de"})
|
||||
detail[dcode] = {"departement": dname, "voies_nommees": nways, "noeuds_voies": nn,
|
||||
"noeuds_candidats": ncand, "collecte": len(cs), "duree_secondes": round(time.time() - t1, 1)}
|
||||
log(f" ways={nways} candidats={ncand} carrefours={len(cs)} en {time.time()-t1:.0f}s")
|
||||
time.sleep(15)
|
||||
dur = round(time.time() - t0, 1); outdir = os.path.join(ROOT, slug); os.makedirs(os.path.join(outdir, "_logs"), exist_ok=True)
|
||||
par = {}
|
||||
for e in entries: par[e["departement"]] = par.get(e["departement"], 0) + 1
|
||||
with open(os.path.join(outdir, "carrefours.json"), "w", encoding="utf-8") as f:
|
||||
json.dump({"categorie": "carrefours", "region": reg["nom"], "source": "OpenStreetMap via overpass-api.de",
|
||||
"definition": f"noeud partage par >=2 voies highway ({HW}) portant >=2 noms distincts; noeuds a <={MERGE_M} m fusionnes",
|
||||
"date_collecte": date, "duree_secondes": dur, "nb_entrees": len(entries), "entrees": entries}, f, ensure_ascii=False, indent=1)
|
||||
with open(os.path.join(outdir, "_logs", "carrefours_stats.json"), "w", encoding="utf-8") as f:
|
||||
json.dump({"duree_secondes": dur, "total": len(entries), "par_departement": par, "detail": detail}, f, ensure_ascii=False, indent=1)
|
||||
log(f"ECRIT {slug}: {len(entries)} carrefours en {dur}s")
|
||||
if __name__ == "__main__": main()
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur