terraproof 0.0.0-stage → 0.4.1
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.
- package/LICENSE +21 -0
- package/README.md +356 -2
- package/bin/terraproof.js +4 -0
- package/dist/router/apply.js +147 -0
- package/dist/router/classify.js +111 -0
- package/dist/router/explain.js +9 -0
- package/dist/router/index.js +272 -0
- package/dist/router/resolve.js +239 -0
- package/dist/router/score.js +60 -0
- package/dist/router/types.js +1 -0
- package/dist/router/validate.js +81 -0
- package/instructions/engineering.md +14 -0
- package/instructions/security.md +14 -0
- package/instructions/simplicity.md +13 -0
- package/package.json +65 -4
- package/routing/DOMAIN_ROUTING.md +161 -0
- package/routing/ROUTER_DESIGN.md +173 -0
- package/routing/SKILL_MANIFEST.md +86 -0
- package/routing/checks.json +121 -0
- package/routing/collections.json +47 -0
- package/routing/registry.json +2211 -0
- package/routing/rules.json +64 -0
- package/skills/accuracy-assessment/SKILL.md +213 -0
- package/skills/accuracy-assessment/UPSTREAM.md +7 -0
- package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
- package/skills/accuracy-assessment/skill.json +103 -0
- package/skills/brainstorming/SKILL.md +250 -0
- package/skills/brainstorming/UPSTREAM.md +29 -0
- package/skills/brainstorming/scripts/frame-template.html +213 -0
- package/skills/brainstorming/scripts/helper.js +167 -0
- package/skills/brainstorming/scripts/server.cjs +723 -0
- package/skills/brainstorming/scripts/start-server.sh +209 -0
- package/skills/brainstorming/scripts/stop-server.sh +120 -0
- package/skills/brainstorming/skill.json +73 -0
- package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
- package/skills/brainstorming/visual-companion.md +299 -0
- package/skills/crs-and-units/SKILL.md +200 -0
- package/skills/crs-and-units/UPSTREAM.md +7 -0
- package/skills/crs-and-units/skill.json +74 -0
- package/skills/design-postgis-tables/SKILL.md +494 -0
- package/skills/design-postgis-tables/UPSTREAM.md +21 -0
- package/skills/design-postgis-tables/skill.json +90 -0
- package/skills/gdal/SKILL.md +125 -0
- package/skills/gdal/UPSTREAM.md +22 -0
- package/skills/gdal/references/gdal-recipes.md +103 -0
- package/skills/gdal/skill.json +66 -0
- package/skills/geomaster/README.md +105 -0
- package/skills/geomaster/SKILL.md +366 -0
- package/skills/geomaster/UPSTREAM.md +21 -0
- package/skills/geomaster/references/advanced-gis.md +376 -0
- package/skills/geomaster/references/big-data.md +363 -0
- package/skills/geomaster/references/code-examples.md +531 -0
- package/skills/geomaster/references/coordinate-systems.md +364 -0
- package/skills/geomaster/references/core-libraries.md +273 -0
- package/skills/geomaster/references/data-sources.md +330 -0
- package/skills/geomaster/references/gis-software.md +369 -0
- package/skills/geomaster/references/industry-applications.md +420 -0
- package/skills/geomaster/references/machine-learning.md +462 -0
- package/skills/geomaster/references/programming-languages.md +456 -0
- package/skills/geomaster/references/remote-sensing.md +370 -0
- package/skills/geomaster/references/scientific-domains.md +416 -0
- package/skills/geomaster/references/specialized-topics.md +428 -0
- package/skills/geomaster/references/troubleshooting.md +439 -0
- package/skills/geomaster/skill.json +157 -0
- package/skills/geopandas/SKILL.md +250 -0
- package/skills/geopandas/UPSTREAM.md +22 -0
- package/skills/geopandas/references/crs-management.md +231 -0
- package/skills/geopandas/references/data-io.md +323 -0
- package/skills/geopandas/references/data-structures.md +207 -0
- package/skills/geopandas/references/geometric-operations.md +262 -0
- package/skills/geopandas/references/spatial-analysis.md +294 -0
- package/skills/geopandas/references/visualization.md +230 -0
- package/skills/geopandas/scripts/_common.py +605 -0
- package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
- package/skills/geopandas/scripts/export_plan.py +305 -0
- package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
- package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
- package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
- package/skills/geopandas/scripts/vector_inventory.py +140 -0
- package/skills/geopandas/skill.json +116 -0
- package/skills/geoparquet-validation/SKILL.md +125 -0
- package/skills/geoparquet-validation/UPSTREAM.md +24 -0
- package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
- package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
- package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
- package/skills/geoparquet-validation/skill.json +71 -0
- package/skills/geospatial-data-discovery/SKILL.md +49 -0
- package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
- package/skills/geospatial-data-discovery/skill.json +51 -0
- package/skills/geospatial-frontend/SKILL.md +86 -0
- package/skills/geospatial-frontend/UPSTREAM.md +23 -0
- package/skills/geospatial-frontend/references/design-system.md +283 -0
- package/skills/geospatial-frontend/references/user-preferences.md +96 -0
- package/skills/geospatial-frontend/skill.json +87 -0
- package/skills/geozarr/SKILL.md +244 -0
- package/skills/geozarr/UPSTREAM.md +21 -0
- package/skills/geozarr/skill.json +97 -0
- package/skills/networkx/SKILL.md +440 -0
- package/skills/networkx/UPSTREAM.md +22 -0
- package/skills/networkx/references/algorithms.md +384 -0
- package/skills/networkx/references/generators.md +385 -0
- package/skills/networkx/references/graph-basics.md +284 -0
- package/skills/networkx/references/io.md +457 -0
- package/skills/networkx/references/visualization.md +531 -0
- package/skills/networkx/skill.json +93 -0
- package/skills/raster-processing/SKILL.md +222 -0
- package/skills/raster-processing/UPSTREAM.md +7 -0
- package/skills/raster-processing/skill.json +81 -0
- package/skills/sar-basics/SKILL.md +202 -0
- package/skills/sar-basics/UPSTREAM.md +7 -0
- package/skills/sar-basics/references/calibration-lut.md +98 -0
- package/skills/sar-basics/skill.json +97 -0
- package/skills/satellite-preprocessing/SKILL.md +241 -0
- package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
- package/skills/satellite-preprocessing/skill.json +84 -0
- package/skills/scientific-visualization/SKILL.md +285 -0
- package/skills/scientific-visualization/UPSTREAM.md +25 -0
- package/skills/scientific-visualization/assets/color_palettes.py +263 -0
- package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
- package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
- package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
- package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
- package/skills/scientific-visualization/references/color_palettes.md +227 -0
- package/skills/scientific-visualization/references/journal_requirements.md +169 -0
- package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
- package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
- package/skills/scientific-visualization/references/sources.md +76 -0
- package/skills/scientific-visualization/scripts/_common.py +136 -0
- package/skills/scientific-visualization/scripts/export_plan.py +493 -0
- package/skills/scientific-visualization/scripts/figure_export.py +642 -0
- package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
- package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
- package/skills/scientific-visualization/scripts/style_presets.py +501 -0
- package/skills/scientific-visualization/scripts/style_preview.py +232 -0
- package/skills/scientific-visualization/skill.json +95 -0
- package/skills/spectral-indices/SKILL.md +235 -0
- package/skills/spectral-indices/UPSTREAM.md +7 -0
- package/skills/spectral-indices/skill.json +88 -0
- package/skills/stac-and-cloud-access/SKILL.md +209 -0
- package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
- package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
- package/skills/stac-and-cloud-access/skill.json +98 -0
- package/skills/statistical-analysis/SKILL.md +446 -0
- package/skills/statistical-analysis/UPSTREAM.md +24 -0
- package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
- package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
- package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
- package/skills/statistical-analysis/references/reporting_standards.md +482 -0
- package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
- package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
- package/skills/statistical-analysis/skill.json +127 -0
- package/skills/systematic-debugging/SKILL.md +283 -0
- package/skills/systematic-debugging/UPSTREAM.md +28 -0
- package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
- package/skills/systematic-debugging/condition-based-waiting.md +115 -0
- package/skills/systematic-debugging/defense-in-depth.md +122 -0
- package/skills/systematic-debugging/find-polluter.sh +72 -0
- package/skills/systematic-debugging/root-cause-tracing.md +169 -0
- package/skills/systematic-debugging/skill.json +88 -0
- package/skills/time-series-and-change/SKILL.md +217 -0
- package/skills/time-series-and-change/UPSTREAM.md +7 -0
- package/skills/time-series-and-change/references/change-methods.md +42 -0
- package/skills/time-series-and-change/skill.json +116 -0
- package/skills/vector-quality/SKILL.md +204 -0
- package/skills/vector-quality/UPSTREAM.md +7 -0
- package/skills/vector-quality/skill.json +82 -0
- package/skills/verification/SKILL.md +120 -0
- package/skills/verification/UPSTREAM.md +31 -0
- package/skills/verification/skill.json +67 -0
- package/skills/writing-plans/SKILL.md +171 -0
- package/skills/writing-plans/UPSTREAM.md +23 -0
- package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
- package/skills/writing-plans/skill.json +80 -0
- package/sources/SOURCES.md +374 -0
- package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
- package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
- package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
- package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
- package/third_party/superpowers/LICENSE +21 -0
- package/third_party/superpowers/NOTICE.md +17 -0
- package/third_party/timescale-pg-aiguide/LICENSE +176 -0
- package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"""Shared local-only safety and reporting helpers for GeoPandas CLIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import tempfile
|
|
11
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
PINNED_STACK = {
|
|
16
|
+
"geopandas": "1.1.4",
|
|
17
|
+
"numpy": "2.5.1",
|
|
18
|
+
"packaging": "26.2",
|
|
19
|
+
"pandas": "3.0.5",
|
|
20
|
+
"pyarrow": "25.0.0",
|
|
21
|
+
"pyogrio": "0.13.0",
|
|
22
|
+
"pyproj": "3.7.2",
|
|
23
|
+
"shapely": "2.1.2",
|
|
24
|
+
}
|
|
25
|
+
DEFAULT_MAX_INPUT_BYTES = 64 * 1024 * 1024
|
|
26
|
+
DEFAULT_MAX_OUTPUT_BYTES = 256 * 1024 * 1024
|
|
27
|
+
DEFAULT_MAX_FEATURES = 100_000
|
|
28
|
+
ABSOLUTE_MAX_INPUT_BYTES = 512 * 1024 * 1024
|
|
29
|
+
ABSOLUTE_MAX_OUTPUT_BYTES = 1024 * 1024 * 1024
|
|
30
|
+
ABSOLUTE_MAX_FEATURES = 1_000_000
|
|
31
|
+
GDAL_SUFFIXES = {".fgb", ".geojson", ".gpkg", ".json", ".shp"}
|
|
32
|
+
PARQUET_SUFFIXES = {".geoparquet", ".parquet"}
|
|
33
|
+
FEATHER_SUFFIXES = {".arrow", ".feather"}
|
|
34
|
+
ALLOWED_INPUT_SUFFIXES = GDAL_SUFFIXES | PARQUET_SUFFIXES | FEATHER_SUFFIXES
|
|
35
|
+
ARCHIVE_SUFFIXES = {
|
|
36
|
+
".7z",
|
|
37
|
+
".bz2",
|
|
38
|
+
".gz",
|
|
39
|
+
".kmz",
|
|
40
|
+
".rar",
|
|
41
|
+
".tar",
|
|
42
|
+
".tgz",
|
|
43
|
+
".xz",
|
|
44
|
+
".zip",
|
|
45
|
+
}
|
|
46
|
+
SENSITIVE_FIELD_TOKENS = {
|
|
47
|
+
"address",
|
|
48
|
+
"coordinate",
|
|
49
|
+
"email",
|
|
50
|
+
"latitude",
|
|
51
|
+
"location",
|
|
52
|
+
"longitude",
|
|
53
|
+
"parcel",
|
|
54
|
+
"phone",
|
|
55
|
+
"postcode",
|
|
56
|
+
"trajectory",
|
|
57
|
+
"zipcode",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CliError(ValueError):
|
|
62
|
+
"""A bounded, user-facing CLI error."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def positive_int(value: str) -> int:
|
|
66
|
+
"""Argparse converter for positive integers."""
|
|
67
|
+
try:
|
|
68
|
+
number = int(value)
|
|
69
|
+
except ValueError as exc:
|
|
70
|
+
raise ValueError("must be an integer") from exc
|
|
71
|
+
if number < 1:
|
|
72
|
+
raise ValueError("must be at least 1")
|
|
73
|
+
return number
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def bounded_limit(value: int, *, name: str, maximum: int) -> int:
|
|
77
|
+
"""Validate a positive resource limit against a hard ceiling."""
|
|
78
|
+
if value < 1:
|
|
79
|
+
raise CliError(f"{name} must be at least 1")
|
|
80
|
+
if value > maximum:
|
|
81
|
+
raise CliError(f"{name} may not exceed {maximum}")
|
|
82
|
+
return value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def finite_number(value: Any, *, name: str) -> float:
|
|
86
|
+
"""Return one finite floating-point value."""
|
|
87
|
+
try:
|
|
88
|
+
number = float(value)
|
|
89
|
+
except (TypeError, ValueError) as exc:
|
|
90
|
+
raise CliError(f"{name} must be a finite number") from exc
|
|
91
|
+
if not math.isfinite(number):
|
|
92
|
+
raise CliError(f"{name} must be finite")
|
|
93
|
+
return number
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def reject_nonlocal(value: str, *, label: str) -> None:
|
|
97
|
+
"""Reject URLs, GDAL virtual filesystems, archives, and path tricks."""
|
|
98
|
+
lowered = value.casefold().strip()
|
|
99
|
+
if not lowered or "\x00" in value:
|
|
100
|
+
raise CliError(f"{label} is empty or invalid")
|
|
101
|
+
if "://" in lowered or lowered.startswith(("/vsi", "vsi")):
|
|
102
|
+
raise CliError(f"{label} must be a local path, not a URL or GDAL VSI path")
|
|
103
|
+
if "!" in value or lowered.startswith(("zip+", "tar+")):
|
|
104
|
+
raise CliError(f"{label} may not address an archive member")
|
|
105
|
+
suffixes = {suffix.casefold() for suffix in Path(lowered).suffixes}
|
|
106
|
+
if suffixes & ARCHIVE_SUFFIXES:
|
|
107
|
+
raise CliError(f"{label} may not be an archive or compressed file")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _root_path(value: str | Path) -> Path:
|
|
111
|
+
raw = str(value)
|
|
112
|
+
reject_nonlocal(raw, label="root")
|
|
113
|
+
candidate = Path(raw).expanduser()
|
|
114
|
+
if candidate.is_symlink():
|
|
115
|
+
raise CliError("root may not be a symbolic link")
|
|
116
|
+
try:
|
|
117
|
+
root = candidate.resolve(strict=True)
|
|
118
|
+
except OSError as exc:
|
|
119
|
+
raise CliError("root does not exist or cannot be resolved") from exc
|
|
120
|
+
if not root.is_dir():
|
|
121
|
+
raise CliError("root must be a directory")
|
|
122
|
+
return root
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _reject_symlink_components(candidate: Path, root: Path) -> None:
|
|
126
|
+
current = candidate
|
|
127
|
+
while True:
|
|
128
|
+
if current.is_symlink():
|
|
129
|
+
raise CliError("symbolic-link paths are not accepted")
|
|
130
|
+
if current == root:
|
|
131
|
+
return
|
|
132
|
+
parent = current.parent
|
|
133
|
+
if parent == current:
|
|
134
|
+
raise CliError("path escapes the configured root")
|
|
135
|
+
current = parent
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _candidate_path(value: str | Path, root: Path, *, label: str) -> Path:
|
|
139
|
+
raw = str(value)
|
|
140
|
+
reject_nonlocal(raw, label=label)
|
|
141
|
+
supplied = Path(raw).expanduser()
|
|
142
|
+
if ".." in supplied.parts:
|
|
143
|
+
raise CliError(f"{label} may not contain '..'")
|
|
144
|
+
candidate = supplied if supplied.is_absolute() else root / supplied
|
|
145
|
+
resolved = candidate.resolve(strict=False)
|
|
146
|
+
if not resolved.is_relative_to(root):
|
|
147
|
+
raise CliError(f"{label} must remain inside the configured root")
|
|
148
|
+
_reject_symlink_components(candidate, root)
|
|
149
|
+
return candidate
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def checked_input_file(
|
|
153
|
+
value: str | Path,
|
|
154
|
+
*,
|
|
155
|
+
root: str | Path = ".",
|
|
156
|
+
max_bytes: int = DEFAULT_MAX_INPUT_BYTES,
|
|
157
|
+
allowed_suffixes: set[str] | None = None,
|
|
158
|
+
) -> Path:
|
|
159
|
+
"""Resolve one bounded, allowlisted local regular input file."""
|
|
160
|
+
max_bytes = bounded_limit(
|
|
161
|
+
max_bytes,
|
|
162
|
+
name="max_input_bytes",
|
|
163
|
+
maximum=ABSOLUTE_MAX_INPUT_BYTES,
|
|
164
|
+
)
|
|
165
|
+
resolved_root = _root_path(root)
|
|
166
|
+
candidate = _candidate_path(value, resolved_root, label="input")
|
|
167
|
+
try:
|
|
168
|
+
path = candidate.resolve(strict=True)
|
|
169
|
+
except OSError as exc:
|
|
170
|
+
raise CliError("input does not exist or cannot be resolved") from exc
|
|
171
|
+
if not path.is_file():
|
|
172
|
+
raise CliError("input must be a regular file")
|
|
173
|
+
suffixes = allowed_suffixes or ALLOWED_INPUT_SUFFIXES
|
|
174
|
+
if path.suffix.casefold() not in suffixes:
|
|
175
|
+
raise CliError("input suffix is not on the vector-data allowlist")
|
|
176
|
+
size = path.stat().st_size
|
|
177
|
+
if size > max_bytes:
|
|
178
|
+
raise CliError(f"input exceeds the {max_bytes}-byte limit")
|
|
179
|
+
return path
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def checked_output_file(
|
|
183
|
+
value: str | Path,
|
|
184
|
+
*,
|
|
185
|
+
root: str | Path = ".",
|
|
186
|
+
allowed_suffixes: set[str],
|
|
187
|
+
) -> Path:
|
|
188
|
+
"""Resolve a new local output path without creating or overwriting it."""
|
|
189
|
+
resolved_root = _root_path(root)
|
|
190
|
+
candidate = _candidate_path(value, resolved_root, label="output")
|
|
191
|
+
if candidate.suffix.casefold() not in allowed_suffixes:
|
|
192
|
+
raise CliError("output suffix is not allowed for this operation")
|
|
193
|
+
if candidate.exists() or candidate.is_symlink():
|
|
194
|
+
raise CliError("output already exists; choose a new path")
|
|
195
|
+
parent = candidate.parent
|
|
196
|
+
if parent.is_symlink() or not parent.exists() or not parent.is_dir():
|
|
197
|
+
raise CliError("output parent must be an existing non-symlink directory")
|
|
198
|
+
return candidate.resolve(strict=False)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def sha256_file(path: Path) -> str:
|
|
202
|
+
"""Hash a bounded local file without loading it into memory."""
|
|
203
|
+
digest = hashlib.sha256()
|
|
204
|
+
with path.open("rb") as handle:
|
|
205
|
+
while chunk := handle.read(1024 * 1024):
|
|
206
|
+
digest.update(chunk)
|
|
207
|
+
return digest.hexdigest()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def package_versions() -> dict[str, str | None]:
|
|
211
|
+
"""Return distribution versions without importing optional packages."""
|
|
212
|
+
found: dict[str, str | None] = {}
|
|
213
|
+
for name in PINNED_STACK:
|
|
214
|
+
try:
|
|
215
|
+
found[name] = version(name)
|
|
216
|
+
except PackageNotFoundError:
|
|
217
|
+
found[name] = None
|
|
218
|
+
return found
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def native_versions() -> dict[str, str | None]:
|
|
222
|
+
"""Return native-library versions after callers have accepted the boundary."""
|
|
223
|
+
try:
|
|
224
|
+
import pyogrio
|
|
225
|
+
import pyproj
|
|
226
|
+
import shapely
|
|
227
|
+
except ImportError as exc:
|
|
228
|
+
raise CliError(
|
|
229
|
+
"runtime analysis requires the pinned GeoPandas stack from SKILL.md"
|
|
230
|
+
) from exc
|
|
231
|
+
gdal_geos = getattr(pyogrio, "__gdal_geos_version__", None)
|
|
232
|
+
return {
|
|
233
|
+
"gdal": ".".join(str(part) for part in pyogrio.__gdal_version__),
|
|
234
|
+
"gdal_geos": (
|
|
235
|
+
".".join(str(part) for part in gdal_geos) if gdal_geos else None
|
|
236
|
+
),
|
|
237
|
+
"geos": str(shapely.geos_version_string),
|
|
238
|
+
"proj": str(pyproj.proj_version_str),
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def disable_proj_network() -> None:
|
|
243
|
+
"""Disable PROJ network access for this process."""
|
|
244
|
+
try:
|
|
245
|
+
from pyproj import network
|
|
246
|
+
except ImportError as exc:
|
|
247
|
+
raise CliError("pyproj is required for CRS analysis") from exc
|
|
248
|
+
network.set_network_enabled(False)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def crs_summary(value: Any) -> dict[str, Any]:
|
|
252
|
+
"""Summarize CRS semantics without serializing sensitive data extents."""
|
|
253
|
+
try:
|
|
254
|
+
from pyproj import CRS
|
|
255
|
+
except ImportError as exc:
|
|
256
|
+
raise CliError("pyproj is required for CRS analysis") from exc
|
|
257
|
+
if value is None:
|
|
258
|
+
return {
|
|
259
|
+
"present": False,
|
|
260
|
+
"authority": None,
|
|
261
|
+
"geographic": None,
|
|
262
|
+
"projected": None,
|
|
263
|
+
"axes": [],
|
|
264
|
+
}
|
|
265
|
+
try:
|
|
266
|
+
crs = CRS.from_user_input(value)
|
|
267
|
+
except (TypeError, ValueError) as exc:
|
|
268
|
+
raise CliError("CRS metadata cannot be parsed") from exc
|
|
269
|
+
authority = crs.to_authority()
|
|
270
|
+
axes = []
|
|
271
|
+
for axis in crs.axis_info:
|
|
272
|
+
factor = axis.unit_conversion_factor
|
|
273
|
+
axes.append(
|
|
274
|
+
{
|
|
275
|
+
"abbreviation": axis.abbrev,
|
|
276
|
+
"direction": axis.direction,
|
|
277
|
+
"unit": axis.unit_name,
|
|
278
|
+
"unit_to_si": float(factor) if factor is not None else None,
|
|
279
|
+
}
|
|
280
|
+
)
|
|
281
|
+
return {
|
|
282
|
+
"present": True,
|
|
283
|
+
"authority": f"{authority[0]}:{authority[1]}" if authority else None,
|
|
284
|
+
"geographic": bool(crs.is_geographic),
|
|
285
|
+
"projected": bool(crs.is_projected),
|
|
286
|
+
"axes": axes,
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _json_scalar(value: Any) -> Any:
|
|
291
|
+
"""Convert common array scalars to strict JSON values."""
|
|
292
|
+
if value is None or isinstance(value, (bool, int, str)):
|
|
293
|
+
return value
|
|
294
|
+
if isinstance(value, float):
|
|
295
|
+
return value if math.isfinite(value) else None
|
|
296
|
+
if hasattr(value, "item"):
|
|
297
|
+
return _json_scalar(value.item())
|
|
298
|
+
return str(value)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
302
|
+
result: dict[str, Any] = {}
|
|
303
|
+
for key, value in pairs:
|
|
304
|
+
if key in result:
|
|
305
|
+
raise CliError(f"duplicate JSON metadata key: {key!r}")
|
|
306
|
+
result[key] = value
|
|
307
|
+
return result
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _reject_constant(value: str) -> None:
|
|
311
|
+
raise CliError(f"non-finite JSON metadata value is not allowed: {value}")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def inspect_geoparquet(path: Path) -> dict[str, Any]:
|
|
315
|
+
"""Inspect Parquet metadata without reading feature coordinates."""
|
|
316
|
+
try:
|
|
317
|
+
from pyarrow import parquet
|
|
318
|
+
except ImportError as exc:
|
|
319
|
+
raise CliError("PyArrow is required to inventory GeoParquet") from exc
|
|
320
|
+
try:
|
|
321
|
+
parquet_file = parquet.ParquetFile(path)
|
|
322
|
+
except (OSError, ValueError) as exc:
|
|
323
|
+
raise CliError("PyArrow could not read Parquet metadata") from exc
|
|
324
|
+
file_metadata = parquet_file.metadata
|
|
325
|
+
key_values = file_metadata.metadata or {}
|
|
326
|
+
raw_geo = key_values.get(b"geo")
|
|
327
|
+
geo: dict[str, Any] | None = None
|
|
328
|
+
if raw_geo is not None:
|
|
329
|
+
try:
|
|
330
|
+
decoded = raw_geo.decode("utf-8")
|
|
331
|
+
parsed = json.loads(
|
|
332
|
+
decoded,
|
|
333
|
+
object_pairs_hook=_strict_object,
|
|
334
|
+
parse_constant=_reject_constant,
|
|
335
|
+
)
|
|
336
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
337
|
+
raise CliError("GeoParquet geo metadata is invalid JSON") from exc
|
|
338
|
+
if not isinstance(parsed, dict):
|
|
339
|
+
raise CliError("GeoParquet geo metadata must be an object")
|
|
340
|
+
geo = parsed
|
|
341
|
+
columns = geo.get("columns", {}) if geo else {}
|
|
342
|
+
if columns is not None and not isinstance(columns, dict):
|
|
343
|
+
raise CliError("GeoParquet columns metadata must be an object")
|
|
344
|
+
crs_states = {"missing": 0, "null": 0, "present": 0}
|
|
345
|
+
covering_columns = 0
|
|
346
|
+
geometry_types: dict[str, int] = {}
|
|
347
|
+
for metadata in (columns or {}).values():
|
|
348
|
+
if not isinstance(metadata, dict):
|
|
349
|
+
raise CliError("GeoParquet geometry column metadata must be an object")
|
|
350
|
+
if "crs" not in metadata:
|
|
351
|
+
crs_states["missing"] += 1
|
|
352
|
+
elif metadata["crs"] is None:
|
|
353
|
+
crs_states["null"] += 1
|
|
354
|
+
else:
|
|
355
|
+
crs_states["present"] += 1
|
|
356
|
+
if metadata.get("covering") is not None:
|
|
357
|
+
covering_columns += 1
|
|
358
|
+
for geometry_type in metadata.get("geometry_types", []):
|
|
359
|
+
key = str(geometry_type)
|
|
360
|
+
geometry_types[key] = geometry_types.get(key, 0) + 1
|
|
361
|
+
arrow_types: dict[str, int] = {}
|
|
362
|
+
for field in parquet_file.schema_arrow:
|
|
363
|
+
key = str(field.type)
|
|
364
|
+
arrow_types[key] = arrow_types.get(key, 0) + 1
|
|
365
|
+
return {
|
|
366
|
+
"kind": "geoparquet" if geo else "parquet_without_geo_metadata",
|
|
367
|
+
"declared_features": int(file_metadata.num_rows),
|
|
368
|
+
"row_groups": int(file_metadata.num_row_groups),
|
|
369
|
+
"field_count": len(parquet_file.schema_arrow),
|
|
370
|
+
"field_type_counts": dict(sorted(arrow_types.items())),
|
|
371
|
+
"geometry_column_count": len(columns or {}),
|
|
372
|
+
"primary_geometry_declared": bool(geo and geo.get("primary_column")),
|
|
373
|
+
"schema_version": _json_scalar(geo.get("version")) if geo else None,
|
|
374
|
+
"crs_metadata_states": crs_states,
|
|
375
|
+
"geometry_type_metadata_counts": dict(sorted(geometry_types.items())),
|
|
376
|
+
"covering_geometry_columns": covering_columns,
|
|
377
|
+
"bounds_redacted": True,
|
|
378
|
+
"feature_data_loaded": False,
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def inspect_gdal_vector(path: Path, *, layer: str | None = None) -> dict[str, Any]:
|
|
383
|
+
"""Inspect one GDAL vector layer without reading feature coordinates."""
|
|
384
|
+
try:
|
|
385
|
+
import pyogrio
|
|
386
|
+
except ImportError as exc:
|
|
387
|
+
raise CliError("pyogrio is required to inventory this vector format") from exc
|
|
388
|
+
try:
|
|
389
|
+
layers = pyogrio.list_layers(path)
|
|
390
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
391
|
+
raise CliError("GDAL could not enumerate local vector layers") from exc
|
|
392
|
+
layer_count = len(layers)
|
|
393
|
+
if layer_count > 1 and layer is None:
|
|
394
|
+
raise CliError("multi-layer input requires an explicit --layer")
|
|
395
|
+
try:
|
|
396
|
+
info = pyogrio.read_info(
|
|
397
|
+
path,
|
|
398
|
+
layer=layer,
|
|
399
|
+
force_feature_count=False,
|
|
400
|
+
force_total_bounds=False,
|
|
401
|
+
)
|
|
402
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
403
|
+
raise CliError("GDAL could not inspect the selected local layer") from exc
|
|
404
|
+
fields = [str(item) for item in info.get("fields", [])]
|
|
405
|
+
dtypes: dict[str, int] = {}
|
|
406
|
+
for dtype in info.get("dtypes", []):
|
|
407
|
+
key = str(dtype)
|
|
408
|
+
dtypes[key] = dtypes.get(key, 0) + 1
|
|
409
|
+
sensitive_names = 0
|
|
410
|
+
for field in fields:
|
|
411
|
+
normalized = re.sub(r"[^a-z0-9]+", "_", field.casefold())
|
|
412
|
+
if any(token in normalized for token in SENSITIVE_FIELD_TOKENS):
|
|
413
|
+
sensitive_names += 1
|
|
414
|
+
declared = info.get("features", -1)
|
|
415
|
+
try:
|
|
416
|
+
declared_features = int(declared)
|
|
417
|
+
except (TypeError, ValueError):
|
|
418
|
+
declared_features = -1
|
|
419
|
+
return {
|
|
420
|
+
"kind": "gdal_vector",
|
|
421
|
+
"driver": _json_scalar(info.get("driver")),
|
|
422
|
+
"layer_count": layer_count,
|
|
423
|
+
"layer_explicitly_selected": layer is not None,
|
|
424
|
+
"declared_features": declared_features if declared_features >= 0 else None,
|
|
425
|
+
"field_count": len(fields),
|
|
426
|
+
"field_type_counts": dict(sorted(dtypes.items())),
|
|
427
|
+
"sensitive_field_name_count": sensitive_names,
|
|
428
|
+
"geometry_type": _json_scalar(info.get("geometry_type")),
|
|
429
|
+
"encoding": _json_scalar(info.get("encoding")),
|
|
430
|
+
"crs": crs_summary(info.get("crs")),
|
|
431
|
+
"bounds_available": info.get("total_bounds") is not None,
|
|
432
|
+
"bounds_redacted": True,
|
|
433
|
+
"feature_data_loaded": False,
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def inspect_local_vector(path: Path, *, layer: str | None = None) -> dict[str, Any]:
|
|
438
|
+
"""Dispatch to a metadata-only local vector inventory."""
|
|
439
|
+
suffix = path.suffix.casefold()
|
|
440
|
+
if suffix in PARQUET_SUFFIXES:
|
|
441
|
+
if layer is not None:
|
|
442
|
+
raise CliError("--layer is not valid for GeoParquet")
|
|
443
|
+
return inspect_geoparquet(path)
|
|
444
|
+
if suffix in FEATHER_SUFFIXES:
|
|
445
|
+
raise CliError("Feather/Arrow inventory is not implemented; convert a vetted copy")
|
|
446
|
+
return inspect_gdal_vector(path, layer=layer)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def load_geodataframe(
|
|
450
|
+
path: Path,
|
|
451
|
+
*,
|
|
452
|
+
layer: str | None,
|
|
453
|
+
max_features: int,
|
|
454
|
+
) -> Any:
|
|
455
|
+
"""Load at most max_features local geometries from an allowlisted format."""
|
|
456
|
+
max_features = bounded_limit(
|
|
457
|
+
max_features,
|
|
458
|
+
name="max_features",
|
|
459
|
+
maximum=ABSOLUTE_MAX_FEATURES,
|
|
460
|
+
)
|
|
461
|
+
if path.suffix.casefold() not in GDAL_SUFFIXES:
|
|
462
|
+
raise CliError("this analysis accepts only allowlisted GDAL vector files")
|
|
463
|
+
try:
|
|
464
|
+
import geopandas as gpd
|
|
465
|
+
except ImportError as exc:
|
|
466
|
+
raise CliError("GeoPandas is required for geometry analysis") from exc
|
|
467
|
+
info = inspect_gdal_vector(path, layer=layer)
|
|
468
|
+
declared = info["declared_features"]
|
|
469
|
+
if declared is not None and declared > max_features:
|
|
470
|
+
raise CliError(f"input declares more than {max_features} features")
|
|
471
|
+
try:
|
|
472
|
+
frame = gpd.read_file(
|
|
473
|
+
path,
|
|
474
|
+
layer=layer,
|
|
475
|
+
engine="pyogrio",
|
|
476
|
+
rows=slice(0, max_features + 1),
|
|
477
|
+
use_arrow=True,
|
|
478
|
+
)
|
|
479
|
+
except (OSError, RuntimeError, TypeError, ValueError) as exc:
|
|
480
|
+
raise CliError("GeoPandas could not read the bounded local layer") from exc
|
|
481
|
+
if not isinstance(frame, gpd.GeoDataFrame):
|
|
482
|
+
raise CliError("selected layer has no geometry column")
|
|
483
|
+
if len(frame) > max_features:
|
|
484
|
+
raise CliError(f"input exceeds the {max_features}-feature limit")
|
|
485
|
+
return frame
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def geometry_state(frame: Any) -> dict[str, Any]:
|
|
489
|
+
"""Return aggregate geometry state without values, IDs, or coordinates."""
|
|
490
|
+
geometry = frame.geometry
|
|
491
|
+
missing = geometry.isna()
|
|
492
|
+
empty = geometry.is_empty
|
|
493
|
+
invalid = (~missing) & (~empty) & (~geometry.is_valid)
|
|
494
|
+
type_counts: dict[str, int] = {}
|
|
495
|
+
for value in geometry.geom_type:
|
|
496
|
+
key = "missing" if value is None else str(value)
|
|
497
|
+
type_counts[key] = type_counts.get(key, 0) + 1
|
|
498
|
+
reason_counts: dict[str, int] = {}
|
|
499
|
+
if bool(invalid.any()):
|
|
500
|
+
for reason in geometry[invalid].is_valid_reason():
|
|
501
|
+
category = str(reason).split("[", 1)[0].strip()[:120]
|
|
502
|
+
reason_counts[category] = reason_counts.get(category, 0) + 1
|
|
503
|
+
has_m = getattr(geometry, "has_m", None)
|
|
504
|
+
return {
|
|
505
|
+
"features": len(frame),
|
|
506
|
+
"missing": int(missing.sum()),
|
|
507
|
+
"empty": int(empty.sum()),
|
|
508
|
+
"invalid": int(invalid.sum()),
|
|
509
|
+
"valid_nonempty": int((~missing & ~empty & ~invalid).sum()),
|
|
510
|
+
"geometry_type_counts": dict(sorted(type_counts.items())),
|
|
511
|
+
"validity_reason_categories": dict(sorted(reason_counts.items())),
|
|
512
|
+
"has_z": int(geometry.has_z.fillna(False).sum()),
|
|
513
|
+
"has_m": int(has_m.fillna(False).sum()) if has_m is not None else None,
|
|
514
|
+
"duplicate_index_rows": int(frame.index.duplicated(keep=False).sum()),
|
|
515
|
+
"coordinates_emitted": False,
|
|
516
|
+
"identifiers_emitted": False,
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def duplicate_column_state(frame: Any, name: str | None) -> dict[str, Any]:
|
|
521
|
+
"""Report null/duplicate counts for an optional ID without emitting values."""
|
|
522
|
+
if name is None:
|
|
523
|
+
return {"provided": False, "null_rows": None, "duplicate_rows": None}
|
|
524
|
+
if name not in frame.columns:
|
|
525
|
+
raise CliError("requested ID column is not present")
|
|
526
|
+
values = frame[name]
|
|
527
|
+
return {
|
|
528
|
+
"provided": True,
|
|
529
|
+
"null_rows": int(values.isna().sum()),
|
|
530
|
+
"duplicate_rows": int(values.duplicated(keep=False).sum()),
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def write_new_geopackage(
|
|
535
|
+
frame: Any,
|
|
536
|
+
destination: Path,
|
|
537
|
+
*,
|
|
538
|
+
max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
|
|
539
|
+
) -> None:
|
|
540
|
+
"""Write a single-layer GeoPackage and link it atomically to a new path."""
|
|
541
|
+
max_output_bytes = bounded_limit(
|
|
542
|
+
max_output_bytes,
|
|
543
|
+
name="max_output_bytes",
|
|
544
|
+
maximum=ABSOLUTE_MAX_OUTPUT_BYTES,
|
|
545
|
+
)
|
|
546
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
547
|
+
prefix=".geopandas-repair-",
|
|
548
|
+
suffix=".gpkg",
|
|
549
|
+
dir=destination.parent,
|
|
550
|
+
)
|
|
551
|
+
os.close(descriptor)
|
|
552
|
+
temporary = Path(temporary_name)
|
|
553
|
+
try:
|
|
554
|
+
temporary.unlink()
|
|
555
|
+
frame.to_file(
|
|
556
|
+
temporary,
|
|
557
|
+
layer="repaired",
|
|
558
|
+
driver="GPKG",
|
|
559
|
+
engine="pyogrio",
|
|
560
|
+
index=False,
|
|
561
|
+
use_arrow=True,
|
|
562
|
+
)
|
|
563
|
+
if temporary.stat().st_size > max_output_bytes:
|
|
564
|
+
raise CliError(f"derived output exceeds the {max_output_bytes}-byte limit")
|
|
565
|
+
try:
|
|
566
|
+
os.link(temporary, destination)
|
|
567
|
+
except FileExistsError as exc:
|
|
568
|
+
raise CliError("output appeared concurrently; nothing was overwritten") from exc
|
|
569
|
+
finally:
|
|
570
|
+
temporary.unlink(missing_ok=True)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def json_text(payload: Any) -> str:
|
|
574
|
+
"""Serialize strict, deterministic JSON."""
|
|
575
|
+
return json.dumps(
|
|
576
|
+
payload,
|
|
577
|
+
allow_nan=False,
|
|
578
|
+
ensure_ascii=False,
|
|
579
|
+
indent=2,
|
|
580
|
+
sort_keys=True,
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def emit_json(payload: Any) -> None:
|
|
585
|
+
"""Print a strict JSON report."""
|
|
586
|
+
print(json_text(payload))
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def fail_json(tool: str, exc: BaseException) -> int:
|
|
590
|
+
"""Emit a redacted error and return the CLI usage/data error status."""
|
|
591
|
+
if isinstance(exc, CliError):
|
|
592
|
+
message = str(exc)
|
|
593
|
+
else:
|
|
594
|
+
message = f"{type(exc).__name__}: operation failed; details redacted"
|
|
595
|
+
emit_json(
|
|
596
|
+
{
|
|
597
|
+
"ok": False,
|
|
598
|
+
"tool": tool,
|
|
599
|
+
"error": message[:500],
|
|
600
|
+
"network_accessed": False,
|
|
601
|
+
"coordinates_emitted": False,
|
|
602
|
+
"identifiers_emitted": False,
|
|
603
|
+
}
|
|
604
|
+
)
|
|
605
|
+
return 2
|