SPB Git

Repository Public

osm_to_tsv.py 5.8 KB 146 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : KA Maps Engine10# File             : server/pipeline/geo/osm_to_tsv.py11# Description      : GeoJSONSeq (osmium export) -> TSV : type, id, lon, lat,12#                    superficie approx.13# Module           : server14# Repository       : https://git.spboucher.ai/ka-maps-engine15# Created          : 2026-12-0116# Last Modified    : 2026-12-0117#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: support@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"""GeoJSONSeq (osmium export) -> TSV : type, id, lon, lat, superficie approx. (m², polygones), étiquettes JSON."""91import json, math, sys9293KEEP = ("name", "name:fr", "name:en", "alt_name", "short_name", "old_name", "amenity", "shop", "leisure", "railway", "station", "highway",94        "public_transport", "place", "aeroway", "network", "operator", "population", "subway", "light_rail", "train",95        "isced:level", "operator:type", "brand")969798def ring_centroid_area(ring):99    a = cx = cy = 0.0100    for (x0, y0), (x1, y1) in zip(ring, ring[1:]):101        c = x0 * y1 - x1 * y0102        a += c; cx += (x0 + x1) * c; cy += (y0 + y1) * c103    if abs(a) < 1e-14:104        n = len(ring)105        return sum(p[0] for p in ring) / n, sum(p[1] for p in ring) / n, 0.0106    a *= 0.5107    return cx / (6 * a), cy / (6 * a), abs(a)108109110def main(src, dst):111    n = 0112    with open(src, encoding="utf-8") as f, open(dst, "w", encoding="utf-8") as out:113        for line in f:114            line = line.strip()115            if not line:116                continue117            ft = json.loads(line)118            g, p = ft.get("geometry") or {}, ft.get("properties") or {}119            t = g.get("type")120            area = 0.0121            if t == "Point":122                lon, lat = g["coordinates"][:2]123            elif t in ("Polygon", "MultiPolygon"):124                polys = [g["coordinates"]] if t == "Polygon" else g["coordinates"]125                best = None126                for poly in polys:127                    x, y, a = ring_centroid_area([c[:2] for c in poly[0]])128                    area += a129                    if best is None or a > best[2]:130                        best = (x, y, a)131                lon, lat = best[0], best[1]132                area *= (111320.0 ** 2) * math.cos(math.radians(lat))133            else:134                continue135            tags = {k: v for k, v in p.items() if k in KEEP or k.startswith("addr:")}136            if not tags:137                continue138            js = json.dumps(tags, ensure_ascii=False).replace("\t", " ").replace("\n", " ").replace("\r", " ")139            out.write(f"{p.get('@type', '')}\t{p.get('@id', 0)}\t{lon:.7f}\t{lat:.7f}\t{area:.1f}\t{js}\n")140            n += 1141    print(n, "objets")142143144if __name__ == "__main__":145    main(sys.argv[1], sys.argv[2])146
Files main
Menu

Theme