geo2glb 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
geo2glb/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """geo2glb: compile geospatial features into a 3D .glb scene."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ # Set at build time by setuptools-scm from the latest git tag (v0.1.0 -> 0.1.0)
7
+ __version__ = version("geo2glb")
8
+ except PackageNotFoundError: # running from a source tree that was never installed
9
+ __version__ = "0+unknown"
geo2glb/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
geo2glb/buildlog.py ADDED
@@ -0,0 +1,37 @@
1
+ """Collects the build report and writes it to .build_log."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as _dt
6
+ from collections import Counter
7
+ from pathlib import Path
8
+
9
+
10
+ class BuildLog:
11
+ def __init__(self) -> None:
12
+ self.lines: list[str] = []
13
+ self.warnings: list[str] = []
14
+ self.counts: Counter = Counter()
15
+
16
+ def info(self, msg: str) -> None:
17
+ self.lines.append(f"INFO {msg}")
18
+
19
+ def warn(self, msg: str) -> None:
20
+ self.warnings.append(msg)
21
+ self.lines.append(f"WARN {msg}")
22
+
23
+ def count(self, key: str, n: int = 1) -> None:
24
+ self.counts[key] += n
25
+
26
+ def summary(self) -> str:
27
+ width = max((len(k) for k in self.counts), default=10)
28
+ rows = [f" {k.ljust(width)} {v}" for k, v in sorted(self.counts.items())]
29
+ return "\n".join(rows)
30
+
31
+ def write(self, path: Path, header: dict) -> None:
32
+ now = _dt.datetime.now().isoformat(timespec="seconds")
33
+ out = [f"geo2glb build log {now}"]
34
+ out += [f"{k}: {v}" for k, v in header.items()]
35
+ out += ["", "Feature counts", self.summary(), "", f"Warnings: {len(self.warnings)}", ""]
36
+ out += self.lines
37
+ path.write_text("\n".join(out) + "\n", encoding="utf-8")
geo2glb/cli.py ADDED
@@ -0,0 +1,210 @@
1
+ """geo2glb: compile GeoJSON / GeoPackage features into a .glb scene."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import shapely
11
+ from shapely.geometry import box
12
+
13
+ from . import __version__
14
+ from .buildlog import BuildLog
15
+ from .config import load_config
16
+ from .convert import geojson_to_gpkg, gpkg_to_geojson
17
+ from .meshing import SceneBuilder, extrude, flat, hex_to_rgba, tree_meshes
18
+ from .reader import read_inputs
19
+ from .railways import build_railways
20
+ from .roads import _num, build_roads
21
+ from .template import write_template
22
+
23
+
24
+ def build(inputs: list[str], output: Path, config: str | None = None,
25
+ log_path: Path | None = None, ground: bool = True) -> BuildLog:
26
+ t0 = time.time()
27
+ log = BuildLog()
28
+ cfg = load_config(config)
29
+ features, info = read_inputs(inputs, cfg, log)
30
+ sb = SceneBuilder()
31
+ flat_types = cfg["flat"]["types"]
32
+
33
+ # ---- roads, junctions, markings, medians, sidewalks; then railways, which
34
+ # cut level crossings into the road specs before anything is meshed
35
+ specs, roads = build_roads(features, cfg, log)
36
+ specs += build_railways(features, cfg, log, specs)
37
+ for s in specs:
38
+ rgba = hex_to_rgba(s["colour"], cfg["road"]["colour"])
39
+ if "mesh" in s:
40
+ mesh = s["mesh"]
41
+ elif s.get("flat"):
42
+ mesh = flat(s["geom"], s["z0"])
43
+ else:
44
+ mesh = extrude(s["geom"], s["z0"], s["z1"])
45
+ if not sb.add(s["name"], mesh, rgba, s["type"], s.get("attrs"), s.get("computed")):
46
+ log.warn(f"{s['name']}: produced no geometry")
47
+
48
+ # ---- polygons
49
+ for f in features:
50
+ if f.geom_kind != "polygon" or f.type == "junction":
51
+ continue
52
+ a = f.attrs
53
+ if f.type in flat_types:
54
+ top = cfg["flat"]["top"]
55
+ rgba = hex_to_rgba(a.get("colour"), flat_types[f.type])
56
+ ok = sb.add(f.fid, extrude(f.geometry, 0.0, top), rgba, f.type, a)
57
+ log.count(f"flat: {f.type}", 1 if ok else 0)
58
+ continue
59
+ base = _num(a, "base_height") or 0.0
60
+ height = _num(a, "height")
61
+ source = "height"
62
+ if height is None:
63
+ levels = _num(a, "levels")
64
+ if levels:
65
+ height = levels * cfg["building"]["storey_height"]
66
+ source = f"levels x {cfg['building']['storey_height']} m"
67
+ else:
68
+ height = cfg["building"]["height"]
69
+ source = "default"
70
+ if height <= base:
71
+ log.warn(f"{f.fid}: height {height} m is not above base_height {base} m, using base + 3 m")
72
+ height = base + 3.0
73
+ rgba = hex_to_rgba(a.get("colour"), cfg["building"]["colour"])
74
+ computed = {"height": height, "base_height": base, "height_source": source}
75
+ ok = sb.add(f.fid, extrude(f.geometry, base, height), rgba, f.type, a, computed)
76
+ log.count(f"extruded: {f.type}", 1 if ok else 0)
77
+ if not ok:
78
+ log.warn(f"{f.fid}: extrusion failed")
79
+
80
+ # ---- points
81
+ for f in features:
82
+ if f.geom_kind != "point":
83
+ continue
84
+ a = f.attrs
85
+ x, y = f.geometry.x, f.geometry.y
86
+ if f.type == "tree":
87
+ h = _num(a, "height") or cfg["tree"]["height"]
88
+ trunk, crown = tree_meshes(x, y, h)
89
+ computed = {"height": h}
90
+ sb.add(f"{f.fid}/trunk", trunk, hex_to_rgba(cfg["tree"]["trunk_colour"], "#6b4f3a"),
91
+ "tree", a, computed, feature_id=f.fid)
92
+ sb.add(f"{f.fid}/crown", crown, hex_to_rgba(a.get("colour"), cfg["tree"]["colour"]),
93
+ "tree", a, computed, feature_id=f.fid)
94
+ log.count("trees", 1)
95
+ else:
96
+ size = _num(a, "size") or cfg["point"]["size"]
97
+ h = _num(a, "height") or size
98
+ g = box(x - size / 2, y - size / 2, x + size / 2, y + size / 2)
99
+ sb.add(f.fid, extrude(g, 0.0, h), hex_to_rgba(a.get("colour"), cfg["point"]["colour"]),
100
+ f.type, a)
101
+ log.count(f"points: {f.type}", 1)
102
+
103
+ # ---- ground
104
+ allg = shapely.union_all([f.geometry.envelope for f in features])
105
+ minx, miny, maxx, maxy = allg.bounds
106
+ m = cfg["ground"]["margin"]
107
+ if ground:
108
+ g = box(minx - m, miny - m, maxx + m, maxy + m)
109
+ sb.add("ground", flat(g, 0.0), hex_to_rgba(cfg["ground"]["colour"], "#e9e6df"),
110
+ "ground")
111
+
112
+ scene_extras = {
113
+ "generator": f"geo2glb {__version__}",
114
+ "origin_lonlat": info["origin_lonlat"],
115
+ "origin_projected": info["origin_projected"],
116
+ "crs_projected": info["crs_projected"],
117
+ "axes": "x = east, y = up, -z = north, metres",
118
+ "extent_m": info["extent_m"],
119
+ "counts": dict(log.counts),
120
+ }
121
+ output.parent.mkdir(parents=True, exist_ok=True)
122
+ sb.export(output, scene_extras)
123
+
124
+ log_path = log_path or output.parent / ".build_log"
125
+ log.write(log_path, {
126
+ "inputs": ", ".join(inputs),
127
+ "output": str(output),
128
+ "projected CRS": info["crs_projected"],
129
+ "origin (lon, lat)": "%.7f, %.7f" % tuple(info["origin_lonlat"]),
130
+ "extent (m)": "%.0f x %.0f" % tuple(info["extent_m"]),
131
+ "size": f"{output.stat().st_size / 1024:.0f} KB",
132
+ "time": f"{time.time() - t0:.1f} s",
133
+ })
134
+ return log
135
+
136
+
137
+ def main(argv: list[str] | None = None) -> int:
138
+ p = argparse.ArgumentParser(
139
+ prog="geo2glb",
140
+ description="Compile GeoJSON / GeoPackage features (EPSG:4326) into a 3D .glb.",
141
+ )
142
+ p.add_argument("inputs", nargs="*",
143
+ help="GeoJSON (.geojson, .json) or GeoPackage (.gpkg) files; a GeoPackage "
144
+ "contributes every layer, or use 'file.gpkg:layer' for one")
145
+ p.add_argument("-o", "--output", type=Path, help="output .glb")
146
+ p.add_argument("--template", type=Path, metavar="GPKG",
147
+ help="write an empty GeoPackage with the geo2glb layers, fields and QGIS "
148
+ "styles, then exit")
149
+ p.add_argument("--to-geojson", action="store_true",
150
+ help="convert one GeoPackage to <layer>.geojson + <layer>.qml (QGIS style) "
151
+ "files in -o DIR (default: <name>_geojson next to it), then exit")
152
+ p.add_argument("--to-gpkg", action="store_true",
153
+ help="convert GeoJSON files (or folders of them) to the GeoPackage -o, using "
154
+ "each file's .qml as its layer style, then exit")
155
+ p.add_argument("--force", action="store_true",
156
+ help="with --template, --to-geojson or --to-gpkg, replace existing files")
157
+ p.add_argument("-c", "--config", help="YAML file overriding defaults and road classes")
158
+ p.add_argument("--log", type=Path, help="build log path (default: .build_log next to the output)")
159
+ p.add_argument("--no-ground", action="store_true", help="do not add a ground plane")
160
+ p.add_argument("--version", action="version", version=f"geo2glb {__version__}")
161
+ args = p.parse_args(argv)
162
+
163
+ modes = [m for m in ("template", "to_geojson", "to_gpkg") if getattr(args, m)]
164
+ if len(modes) > 1:
165
+ p.error("use only one of --template, --to-geojson, --to-gpkg")
166
+ if args.to_geojson or args.to_gpkg:
167
+ if args.to_geojson and len(args.inputs) != 1:
168
+ p.error("--to-geojson takes exactly one GeoPackage")
169
+ if args.to_gpkg and (not args.inputs or not args.output):
170
+ p.error("--to-gpkg needs GeoJSON inputs and -o output.gpkg")
171
+ try:
172
+ if args.to_geojson:
173
+ report = gpkg_to_geojson(args.inputs[0], args.output, overwrite=args.force)
174
+ else:
175
+ report = geojson_to_gpkg(args.inputs, args.output, overwrite=args.force)
176
+ except Exception as e:
177
+ print(f"geo2glb: error: {e}", file=sys.stderr)
178
+ return 1
179
+ print("\n".join(report))
180
+ return 0
181
+ if args.template:
182
+ if args.inputs or args.output:
183
+ p.error("--template takes no inputs or --output")
184
+ try:
185
+ styled = write_template(args.template, overwrite=args.force)
186
+ except Exception as e:
187
+ print(f"geo2glb: error: {e}", file=sys.stderr)
188
+ return 1
189
+ print(f"wrote template {args.template}")
190
+ print(f"layers with QGIS default styles: {', '.join(styled)}")
191
+ return 0
192
+ if not args.inputs:
193
+ p.error("at least one input is required (or use --template)")
194
+ if not args.output:
195
+ p.error("-o/--output is required")
196
+
197
+ try:
198
+ log = build(args.inputs, args.output, args.config, args.log, ground=not args.no_ground)
199
+ except Exception as e: # report cleanly on the command line
200
+ print(f"geo2glb: error: {e}", file=sys.stderr)
201
+ return 1
202
+ log_path = args.log or args.output.parent / ".build_log"
203
+ print(f"wrote {args.output}")
204
+ print(log.summary())
205
+ print(f"{len(log.warnings)} warning(s), see {log_path}")
206
+ return 0
207
+
208
+
209
+ if __name__ == "__main__":
210
+ raise SystemExit(main())
geo2glb/config.py ADDED
@@ -0,0 +1,135 @@
1
+ """Defaults, fallbacks and the road cross-section table.
2
+
3
+ Road widths follow Permen PUPR No. 5 Tahun 2023 (Persyaratan Teknis Jalan dan
4
+ Perencanaan Teknis Jalan), Lampiran I-II, "Penampang Melintang Jalan".
5
+ The secondary (urban) network table is used because the tool targets sites
6
+ and urban design projects, with the design speed VD <= 60 km/h case.
7
+
8
+ All distances are metres.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ from pathlib import Path
15
+
16
+ # --------------------------------------------------------------------------
17
+ # Road cross-sections (PUPR 5/2023, Lampiran II, sistem jaringan jalan sekunder)
18
+ #
19
+ # carriageway : lebar jalur lalu lintas (both directions, excluding median)
20
+ # lanes : total number of lanes (from the "tipe jalan" code n/2)
21
+ # median : lebar median paling kecil, raised median Tipe 1 for
22
+ # VD <= 60 km/h = 1.50 m (0.50 inner shoulder + 0.50 raised
23
+ # island + 0.50 inner shoulder)
24
+ # median_island : width of the raised part of the median
25
+ # shoulder : lebar bahu luar paling kecil, new road "dengan kereb dan
26
+ # trotoar" = 0.50 m (Jalan Raya / Sedang), 0.25 m (Jalan Kecil
27
+ # / motorcycle lane)
28
+ #
29
+ # Kerb-to-kerb width = carriageway + median + 2 x shoulder.
30
+ # Check: 4/2-T -> 14.00 + 1.50 + 2 x 0.50 = 16.50 m
31
+ # --------------------------------------------------------------------------
32
+ ROAD_CLASSES: dict[str, dict] = {
33
+ "8/2-T": {"carriageway": 28.00, "lanes": 8, "median": 1.50, "median_island": 0.50, "shoulder": 0.50},
34
+ "6/2-T": {"carriageway": 21.00, "lanes": 6, "median": 1.50, "median_island": 0.50, "shoulder": 0.50},
35
+ "4/2-T": {"carriageway": 14.00, "lanes": 4, "median": 1.50, "median_island": 0.50, "shoulder": 0.50},
36
+ "4/2-TT": {"carriageway": 14.00, "lanes": 4, "median": 0.00, "median_island": 0.00, "shoulder": 0.50},
37
+ "2/2-TT": {"carriageway": 7.00, "lanes": 2, "median": 0.00, "median_island": 0.00, "shoulder": 0.50},
38
+ "1/1-TT": {"carriageway": 1.75, "lanes": 1, "median": 0.00, "median_island": 0.00, "shoulder": 0.25},
39
+ }
40
+
41
+ # Per-lane width when only road_total_lane is known. 3.50 m is the lane width
42
+ # implied by every multi-lane row of the table (e.g. 4/2-T: 2 x 7.00 / 4).
43
+ LANE_WIDTH = 3.50
44
+ DEFAULT_ROAD_CLASS = "2/2-TT"
45
+ # Trotoar minimum width, PUPR 5/2023 Pasal 29 (2) a.
46
+ SIDEWALK_MIN_WIDTH = 1.85
47
+
48
+ DEFAULTS: dict = {
49
+ "road": {
50
+ "colour": "#4a4d52",
51
+ "kerb_radius": 6.0, # junction corner radius
52
+ "snap_tolerance": 0.5, # endpoint snapping when noding the network
53
+ "layer_height": 6.0, # z per 'layer' step (flyovers)
54
+ "surface_top": 0.04,
55
+ },
56
+ "junction": {"colour": None}, # None = colour of the widest incident road
57
+ "marking": {
58
+ "colour": "#f2f2f2",
59
+ "width": 0.12,
60
+ "dash": 3.0,
61
+ "gap": 5.0,
62
+ "top": 0.05,
63
+ },
64
+ # Railways. Gauge 1.067 m is the Cape gauge of the Indonesian (KAI) network.
65
+ # Track spacing and sleeper pitch are typical values after PM 60/2012
66
+ # (Persyaratan Teknis Jalur Kereta Api); check them against the project's
67
+ # standard and override with -c style.yaml or the rail_* attributes.
68
+ "railway": {
69
+ "gauge": 1.067,
70
+ "track_spacing": 4.0, # centre to centre of adjacent tracks
71
+ "sleeper_spacing": 0.6,
72
+ "sleeper_width": 0.22,
73
+ "sleeper_overhang": 0.47, # sleeper length = gauge + 2 x overhang (2.0 m for 1.067)
74
+ "ballast_shoulder": 0.50, # ballast beyond the sleeper ends
75
+ "bed_height": 0.30,
76
+ "sleeper_height": 0.05, # above the ballast
77
+ "rail_width": 0.07,
78
+ "rail_height": 0.15,
79
+ "colour": "#8c857b", # ballast
80
+ "sleeper_colour": "#a9a49c",
81
+ "rail_colour": "#5a5d63",
82
+ },
83
+ "median": {"colour": "#8a8f85", "height": 0.20},
84
+ "sidewalk": {"colour": "#b9b4aa", "height": 0.15},
85
+ "building": {"colour": "#b4bcc7", "height": 4.0, "storey_height": 3.0},
86
+ # Flat polygon types: rendered as thin slabs, never extruded.
87
+ "flat": {
88
+ "top": 0.02,
89
+ "types": {
90
+ "park": "#7fb069",
91
+ "green": "#7fb069",
92
+ "grass": "#8cbf72",
93
+ "water": "#5b9bd5",
94
+ "plaza": "#cfc6b8",
95
+ "pavement": "#cfc6b8",
96
+ "parking": "#9a9ca0",
97
+ "landuse": "#e3dfd6",
98
+ },
99
+ },
100
+ "tree": {"colour": "#4f8a3c", "trunk_colour": "#6b4f3a", "height": 10.0},
101
+ "point": {"colour": "#e0644f", "size": 1.0}, # any non-tree point type
102
+ "ground": {"colour": "#e9e6df", "margin": 50.0},
103
+ }
104
+
105
+ # Accepted alternative spellings of attribute names.
106
+ FIELD_ALIASES = {
107
+ "color": "colour",
108
+ }
109
+
110
+
111
+ def _deep_merge(base: dict, override: dict) -> dict:
112
+ out = copy.deepcopy(base)
113
+ for k, v in override.items():
114
+ if isinstance(v, dict) and isinstance(out.get(k), dict):
115
+ out[k] = _deep_merge(out[k], v)
116
+ else:
117
+ out[k] = v
118
+ return out
119
+
120
+
121
+ def load_config(path: str | Path | None) -> dict:
122
+ """Built-in defaults, optionally overridden by a YAML file.
123
+
124
+ The YAML may contain any key of DEFAULTS plus a ``road_classes`` mapping
125
+ that adds or replaces entries in ROAD_CLASSES.
126
+ """
127
+ cfg = copy.deepcopy(DEFAULTS)
128
+ cfg["road_classes"] = copy.deepcopy(ROAD_CLASSES)
129
+ if path:
130
+ import yaml
131
+
132
+ with open(path, encoding="utf-8") as f:
133
+ user = yaml.safe_load(f) or {}
134
+ cfg = _deep_merge(cfg, user)
135
+ return cfg
geo2glb/convert.py ADDED
@@ -0,0 +1,203 @@
1
+ """Convert between a geo2glb GeoPackage and GeoJSON files with QGIS .qml styles.
2
+
3
+ geo2glb --to-geojson site.gpkg -> site_geojson/<layer>.geojson + <layer>.qml
4
+ geo2glb --to-gpkg site_geojson -o site.gpkg
5
+
6
+ QGIS applies a .qml with the same name as a file-based layer automatically, so
7
+ each GeoJSON opens with its style and attribute form. Going back, each .qml
8
+ becomes the layer's default style in the GeoPackage, and the fields are put
9
+ back to the template schema (GeoJSON has no schema: a field that is empty on
10
+ every feature comes back as text, and an empty layer loses its fields and its
11
+ geometry type, which is then taken from the .qml).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from pathlib import Path
18
+
19
+ import geopandas as gpd
20
+ import numpy as np
21
+ import pandas as pd
22
+ import pyogrio
23
+
24
+ from .qgis_styles import default_styles, style_for_geometry, write_styles
25
+ from .reader import INPUT_CRS
26
+ from .template import SCHEMA
27
+
28
+ # Geometry family -> template layer (whose fields that family gets)
29
+ FAMILY_LAYER = {"point": "points", "line": "lines", "polygon": "polygons"}
30
+ GEOM_FAMILY = {
31
+ "Point": "point", "MultiPoint": "point",
32
+ "LineString": "line", "MultiLineString": "line",
33
+ "Polygon": "polygon", "MultiPolygon": "polygon",
34
+ }
35
+ QML_FAMILY = {"0": "point", "1": "line", "2": "polygon"} # <layerGeometryType>
36
+ NULLABLE = {"str": object, "float": "float64", "int": "Int64"} # dtypes that can hold nulls
37
+
38
+
39
+ def _refuse_existing(paths: list[Path], overwrite: bool) -> None:
40
+ existing = [p for p in paths if p.exists()]
41
+ if existing and not overwrite:
42
+ names = ", ".join(str(p) for p in existing[:3]) + (" ..." if len(existing) > 3 else "")
43
+ raise FileExistsError(f"{names} already exists (use --force to replace)")
44
+ for p in existing:
45
+ p.unlink()
46
+
47
+
48
+ # --------------------------------------------------------------------------
49
+ # GeoPackage -> GeoJSON + .qml
50
+ # --------------------------------------------------------------------------
51
+ def gpkg_to_geojson(gpkg: str | Path, out_dir: str | Path | None = None,
52
+ overwrite: bool = False) -> list[str]:
53
+ """Write <out_dir>/<layer>.geojson and <layer>.qml for every spatial layer."""
54
+ gpkg = Path(gpkg)
55
+ if gpkg.suffix.lower() != ".gpkg" or not gpkg.exists():
56
+ raise ValueError(f"--to-geojson needs an existing GeoPackage (.gpkg), got '{gpkg}'")
57
+ out = Path(out_dir) if out_dir else gpkg.with_name(f"{gpkg.stem}_geojson")
58
+ layers = [(name, gtype) for name, gtype in pyogrio.list_layers(gpkg) if gtype is not None]
59
+ if not layers:
60
+ raise ValueError(f"{gpkg.name} has no spatial layers")
61
+ _refuse_existing([out / f"{n}{ext}" for n, _ in layers for ext in (".geojson", ".qml")],
62
+ overwrite)
63
+ out.mkdir(parents=True, exist_ok=True)
64
+ styles = default_styles(gpkg)
65
+
66
+ report = []
67
+ for name, gtype in layers:
68
+ gdf = pyogrio.read_dataframe(gpkg, layer=name)
69
+ if gdf.crs is None:
70
+ gdf = gdf.set_crs(INPUT_CRS)
71
+ elif gdf.crs.to_epsg() != 4326:
72
+ gdf = gdf.to_crs(INPUT_CRS)
73
+ pyogrio.write_dataframe(gdf, out / f"{name}.geojson", driver="GeoJSON", layer=name)
74
+ qml, source = styles.get(name), "style from the GeoPackage"
75
+ if not qml:
76
+ qml, source = style_for_geometry(gtype), "generated geo2glb style"
77
+ if qml:
78
+ (out / f"{name}.qml").write_text(qml, encoding="utf-8")
79
+ else:
80
+ source = "no style (unsupported geometry type)"
81
+ note = (", empty: GeoJSON keeps no fields for an empty layer; draw in the GeoPackage "
82
+ "or add a feature before converting") if len(gdf) == 0 else ""
83
+ report.append(f"{out / name}.geojson: {len(gdf)} features, {source}{note}")
84
+ return report
85
+
86
+
87
+ # --------------------------------------------------------------------------
88
+ # GeoJSON (+ .qml) -> GeoPackage
89
+ # --------------------------------------------------------------------------
90
+ def _expand(inputs: list[str]) -> list[Path]:
91
+ files = []
92
+ for spec in inputs:
93
+ p = Path(spec)
94
+ if p.is_dir():
95
+ files += sorted(q for q in p.iterdir() if q.suffix.lower() in (".geojson", ".json"))
96
+ elif p.exists() and p.suffix.lower() in (".geojson", ".json"):
97
+ files.append(p)
98
+ else:
99
+ raise ValueError(f"--to-gpkg takes GeoJSON files or folders of them, got '{spec}'")
100
+ if not files:
101
+ raise ValueError("No GeoJSON files found")
102
+ return files
103
+
104
+
105
+ def _qml_family(qml: str | None) -> str | None:
106
+ m = re.search(r"<layerGeometryType>\s*(\d)\s*</layerGeometryType>", qml or "")
107
+ return QML_FAMILY.get(m.group(1)) if m else None
108
+
109
+
110
+ def conform(gdf: gpd.GeoDataFrame, family: str, log: list[str], where: str) -> gpd.GeoDataFrame:
111
+ """Add missing template fields and restore their types. Values that don't
112
+ convert are kept as they are (with a note), never dropped."""
113
+ gdf = gdf.copy()
114
+ fields = SCHEMA[FAMILY_LAYER[family]][1]
115
+ for name, kind in fields:
116
+ if name not in gdf.columns:
117
+ gdf[name] = pd.Series([None] * len(gdf), index=gdf.index, dtype=NULLABLE[kind])
118
+ continue
119
+ col = gdf[name]
120
+ if kind == "str":
121
+ gdf[name] = col.astype(object).where(col.notna(), None).map(
122
+ lambda v: v if v is None or isinstance(v, str) else
123
+ (str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)))
124
+ continue
125
+ num = pd.to_numeric(col, errors="coerce")
126
+ bad = col.notna() & num.isna()
127
+ if bad.any():
128
+ log.append(f"{where}: {name} has {int(bad.sum())} value(s) that aren't numbers, "
129
+ f"kept as text")
130
+ continue
131
+ if kind == "int":
132
+ frac = num.notna() & (num != np.round(num))
133
+ if frac.any():
134
+ log.append(f"{where}: {name} has non-whole values, kept as decimals")
135
+ gdf[name] = num.astype("float64")
136
+ else:
137
+ gdf[name] = num.round().astype("Int64")
138
+ else:
139
+ gdf[name] = num.astype("float64")
140
+ order = [n for n, _ in fields if n in gdf.columns]
141
+ rest = [c for c in gdf.columns if c not in order and c != gdf.geometry.name]
142
+ return gdf[order + rest + [gdf.geometry.name]]
143
+
144
+
145
+ def geojson_to_gpkg(inputs: list[str], gpkg: str | Path, overwrite: bool = False) -> list[str]:
146
+ """Write every GeoJSON as a layer of gpkg, with its .qml as the default style."""
147
+ gpkg = Path(gpkg)
148
+ if gpkg.suffix.lower() != ".gpkg":
149
+ raise ValueError(f"--to-gpkg output must be a GeoPackage (.gpkg), got '{gpkg.name}'")
150
+ files = _expand(inputs)
151
+ _refuse_existing([gpkg], overwrite)
152
+ gpkg.parent.mkdir(parents=True, exist_ok=True)
153
+
154
+ report: list[str] = []
155
+ qml_by_table: dict[str, str] = {}
156
+ used: set[str] = set()
157
+ for f in files:
158
+ gdf = pyogrio.read_dataframe(f)
159
+ gdf = gdf.set_crs(INPUT_CRS) if gdf.crs is None else gdf.to_crs(INPUT_CRS)
160
+ qml_path = f.with_suffix(".qml")
161
+ qml = qml_path.read_text(encoding="utf-8") if qml_path.exists() else None
162
+
163
+ families = sorted({GEOM_FAMILY[t] for t in gdf.geom_type.dropna() if t in GEOM_FAMILY})
164
+ unsupported = gdf.geometry.notna() & ~gdf.geom_type.isin(list(GEOM_FAMILY))
165
+ if unsupported.any():
166
+ report.append(f"{f.name}: {int(unsupported.sum())} feature(s) with other geometry "
167
+ f"types (e.g. GeometryCollection) skipped")
168
+ if not families: # empty layer: geometry type from the .qml, else the file name
169
+ fam = _qml_family(qml) or {v: k for k, v in FAMILY_LAYER.items()}.get(f.stem)
170
+ if fam is None:
171
+ report.append(f"{f.name}: empty and no geometry type known (no .qml), skipped")
172
+ continue
173
+ families = [fam]
174
+
175
+ for fam in families:
176
+ part = gdf[gdf.geom_type.map(GEOM_FAMILY) == fam] if len(gdf) else gdf
177
+ layer = f.stem if len(families) == 1 else f"{f.stem}_{FAMILY_LAYER[fam]}"
178
+ base, n = layer, 1
179
+ while layer in used:
180
+ n += 1
181
+ layer = f"{base}_{n}"
182
+ used.add(layer)
183
+
184
+ notes: list[str] = []
185
+ part = conform(part, fam, notes, f.name)
186
+ kinds = set(part.geom_type.dropna())
187
+ if len(part) == 0:
188
+ geom_type = SCHEMA[FAMILY_LAYER[fam]][0]
189
+ elif len(kinds) == 1:
190
+ geom_type = kinds.pop()
191
+ else: # mix of single and multi parts
192
+ geom_type = "Multi" + SCHEMA[FAMILY_LAYER[fam]][0]
193
+ pyogrio.write_dataframe(part, gpkg, layer=layer, driver="GPKG",
194
+ geometry_type=geom_type, promote_to_multi=geom_type.startswith("Multi"))
195
+ if qml and _qml_family(qml) in (None, fam):
196
+ qml_by_table[layer] = qml
197
+ style = f"style from {qml_path.name}"
198
+ else:
199
+ style = "generated geo2glb style"
200
+ report.append(f"{layer}: {len(part)} features from {f.name}, {style}")
201
+ report += notes
202
+ write_styles(gpkg, qml_by_table)
203
+ return report