#!/usr/bin/env python3 """Télécharge les bâtiments OpenStreetMap dans un couloir autour du tracé, par cellules de ~2 km (requêtes Overpass petites, avec relances), puis fusionne le tout en un JSON au format Overpass. Usage : python3 tools/fetch_osm_buildings.py www/data/trace.json OUT_DIR [buffer_m] → OUT_DIR/cells/*.json et OUT_DIR/corridor.json Données © contributeurs OpenStreetMap (ODbL). """ import json, math, os, sys, time, urllib.parse, urllib.request SERVERS = ['https://overpass-api.de/api/interpreter', 'https://overpass.kumi.systems/api/interpreter', 'https://overpass.private.coffee/api/interpreter'] DLAT, DLON = 0.02, 0.03 R = 6371008.8 K = math.cos(math.radians(50.6)) def proj(lat, lon): return R * K * math.radians(lon), R * math.radians(lat) def seg_dist(p, a, b): dx, dy = b[0] - a[0], b[1] - a[1] l2 = dx * dx + dy * dy t = max(0, min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2)) if l2 else 0 return math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy) def cells_for(line, buf): pts = [proj(la, lo) for la, lo in line[::5]] + [proj(*line[-1])] la0, la1 = min(p[0] for p in line) - 0.05, max(p[0] for p in line) + 0.05 lo0, lo1 = min(p[1] for p in line) - 0.07, max(p[1] for p in line) + 0.07 out = [] i = math.floor(la0 / DLAT) while i * DLAT < la1: j = math.floor(lo0 / DLON) while j * DLON < lo1: c = proj((i + 0.5) * DLAT, (j + 0.5) * DLON) d = min(seg_dist(c, pts[k], pts[k + 1]) for k in range(len(pts) - 1)) if d < buf + 1600: out.append((i, j)) j += 1 i += 1 return out def fetch(i, j): s, w, n, e = i * DLAT, j * DLON, (i + 1) * DLAT, (j + 1) * DLON q = f'[out:json][timeout:180];(way["building"]({s},{w},{n},{e});relation["building"]({s},{w},{n},{e}););out geom tags qt;' data = urllib.parse.urlencode({'data': q}).encode() for attempt in range(12): url = SERVERS[attempt % len(SERVERS)] try: req = urllib.request.Request(url, data=data, headers={'User-Agent': 'bdh-ar-extract/1.0'}) with urllib.request.urlopen(req, timeout=240) as r: body = r.read() d = json.loads(body) if 'remark' in d and 'error' in d['remark'].lower(): raise RuntimeError(d['remark'][:120]) return d except Exception as ex: print(f' cellule {i},{j} essai {attempt + 1} ({url.split("/")[2]}) : {str(ex)[:100]}', flush=True) time.sleep(min(60, 10 + attempt * 10)) raise RuntimeError(f'cellule {i},{j} : échec') def main(trace_path, out, buf=3000): line = json.load(open(trace_path))['line'] cdir = os.path.join(out, 'cells') os.makedirs(cdir, exist_ok=True) cells = cells_for(line, float(buf)) print(f'{len(cells)} cellules', flush=True) for k, (i, j) in enumerate(cells): f = os.path.join(cdir, f'{i}_{j}.json') if os.path.exists(f): continue d = fetch(i, j) json.dump(d, open(f, 'w')) print(f'[{k + 1}/{len(cells)}] {i},{j} : {len(d["elements"])} bâtiments', flush=True) time.sleep(2) seen, elements, stamp = set(), [], None for f in sorted(os.listdir(cdir)): d = json.load(open(os.path.join(cdir, f))) stamp = stamp or d.get('osm3s', {}).get('timestamp_osm_base') for el in d['elements']: key = (el['type'], el['id']) if key not in seen: seen.add(key); elements.append(el) json.dump({'osm3s': {'timestamp_osm_base': stamp}, 'elements': elements}, open(os.path.join(out, 'corridor.json'), 'w')) print(f'fusion : {len(elements)} bâtiments', flush=True) if __name__ == '__main__': main(*sys.argv[1:])