matchgeodem / scripts /metadata_update_info.py
paeslemesa's picture
Updated statcs/ splis/ and scrips/
0a7933d verified
Raw History Blame Contribute Delete
9.26 kB
#!/usr/bin/env python3
"""
Update GeoMatch-DEM metadata JSON files from a CSV summary.
Usage:
python update_metadata_from_csv.py <csv_file> <metadata_dir> [--fix-ata-mv]
The script reads a CSV with raster-derived statistics and updates the
corresponding *_metadata.json files in-place (with backup).
"""
import argparse
import csv
import json
import shutil
from pathlib import Path
def fix_ata_mv_processing(json_data: dict) -> dict:
"""
ATA_MV_metadata.json has a syntax error: the 'processing' section is
missing its opening key and 'pipeline' array. This reconstructs it
from the trailing fields that are present in the file.
"""
if "processing" in json_data:
return json_data
# Reconstruct processing section based on file notes and sibling files
json_data["processing"] = {
"software": "PDAL",
"software_version": "2.6.0",
"python_version": "3.10.20",
"pipeline": [
{
"stage": "readers.las",
"description": "Read LAZ point cloud"
},
{
"stage": "writers.gdal",
"description": "Rasterize to DSM (max height per cell)",
"parameters": {
"resolution": json_data["raster"]["resolution_meters"],
"output_type": "max",
"data_type": "float32",
"nodata": -9999,
"gdalopts": "COMPRESS=DEFLATE|TILED=YES|BIGTIFF=YES|BLOCKXSIZE=256|BLOCKYSIZE=256",
"override_srs": json_data["spatial"]["crs"]["name"]
}
}
],
"output_type": "max",
"gdal_options": "COMPRESS=DEFLATE|TILED=YES|BIGTIFF=YES|BLOCKXSIZE=256|BLOCKYSIZE=256",
"resampling": "none",
"patch_extraction": {
"method": "grid_split",
"patch_size": [256, 256],
"overlap": 0,
"resampling": "none"
}
}
return json_data
def parse_csv(csv_path: Path) -> dict[str, dict]:
"""Read CSV and return dict keyed by region code."""
rows = {}
with open(csv_path, "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
region = row["region"]
rows[region] = row
return rows
def update_json_from_csv(json_data: dict, csv_row: dict) -> dict:
"""
Update JSON metadata with values derived from the actual raster file.
Mapping:
CSV field -> JSON path
---------------- --------------------------------------------
file_size_mb -> (new top-level field, not in schema)
nodata -> raster.nodata_value
crs -> spatial.crs (parsed for EPSG code)
dtype -> raster.data_type
resolution -> raster.resolution_meters
width -> spatial.tile_index.tile_size_pixels[0] (or new field)
heigth -> spatial.tile_index.tile_size_pixels[1] (or new field)
n_tiles -> spatial.tile_index.n_tiles
tile_size -> spatial.tile_index.tile_size_pixels
x_min, x_max -> spatial.extent.bbox[0], bbox[2]
y_min, y_max -> spatial.extent.bbox[1], bbox[3]
long_min, long_max -> spatial.extent.bbox_min_x/max_x (in degrees)
lat_min, lat_max -> spatial.extent.bbox_min_y/max_y (in degrees)
"""
# --- spatial.extent ---
extent = json_data.setdefault("spatial", {}).setdefault("extent", {})
# UTM bounds from CSV (projected coordinates)
x_min = float(csv_row["x_min"])
x_max = float(csv_row["x_max"])
y_min = float(csv_row["y_min"])
y_max = float(csv_row["y_max"])
extent["bbox"] = [x_min, y_min, x_max, y_max]
#extent["bbox_min_x"] = x_min
#extent["bbox_min_y"] = y_min
#extent["bbox_max_x"] = x_max
#extent["bbox_max_y"] = y_max
# Geographic bounds (lat/lon) - stored alongside projected bounds
# Note: The JSON schema doesn't have dedicated lat/lon bbox fields,
# so we add them as new fields in extent
extent["bbox_lonlat"] = [
float(csv_row["long_min"]),
float(csv_row["lat_min"]),
float(csv_row["long_max"]),
float(csv_row["lat_max"])
]
#extent["lon_min"] = float(csv_row["long_min"])
#extent["lon_max"] = float(csv_row["long_max"])
#extent["lat_min"] = float(csv_row["lat_min"])
#extent["lat_max"] = float(csv_row["lat_max"])
# --- spatial.tile_index ---
tile_index = json_data.setdefault("spatial", {}).setdefault("tile_index", {})
tile_index["n_tiles"] = int(csv_row["n_tiles"])
# Tile size in pixels from CSV
tile_size_px = int(csv_row["tile_size"])
tile_index["tile_size_pixels"] = [tile_size_px, tile_size_px]
# Tile size in meters: resolution * tile_size_pixels
resolution = float(csv_row["resolution"])
tile_size_m = resolution * tile_size_px
tile_index["tile_size_meters"] = [tile_size_m, tile_size_m]
# --- raster ---
raster = json_data.setdefault("raster", {})
raster["data_type"] = csv_row["dtype"]
raster["nodata_value"] = float(csv_row["nodata"])
raster["resolution_meters"] = resolution
# Internal tile dimensions (GeoTIFF block size)
raster["tile_dimensions"] = [tile_size_px, tile_size_px]
# --- spatial.crs ---
# Parse EPSG from the CRS WKT string in CSV
crs_str = csv_row["crs"]
epsg_code = extract_epsg_from_crs(crs_str)
if epsg_code:
json_data["spatial"]["crs"]["epsg"] = epsg_code
json_data["spatial"]["crs"]["name"] = f"EPSG:{epsg_code}"
# --- Add file_size_mb as a new top-level convenience field ---
json_data["file_size_mb"] = float(csv_row["file_size_mb"])
return json_data
def extract_epsg_from_crs(crs_str: str) -> int | None:
"""Extract EPSG code from WKT or EPSG:xxxx string."""
if crs_str.startswith("EPSG:"):
try:
return int(crs_str.split(":")[1])
except (IndexError, ValueError):
pass
# Try to find AUTHORITY["EPSG","xxxx"] pattern in WKT
import re
matches = re.findall(r'AUTHORITY\["EPSG","(\d+)"\]', crs_str)
if matches:
# Return the last match (usually the projection CRS, not datum/spheroid)
return int(matches[-1])
# Try COMPD_CS or PROJCS with EPSG in name
match = re.search(r'EPSG[:\s]*(\d+)', crs_str)
if match:
return int(match.group(1))
return None
def load_json_robust(path: Path, fix_ata_mv: bool = False) -> dict:
"""Load JSON, with optional repair for known-broken ATA_MV file."""
with open(path, "r", encoding="utf-8") as f:
content = f.read()
try:
data = json.loads(content)
except json.JSONDecodeError as e:
raise
if fix_ata_mv and "ATA_MV" in path.name:
data = fix_ata_mv_processing(data)
return data
def main():
REGIONS = {'ATA_MV', 'BRA_SP', 'CHN_WS', 'ESP_EH', 'FIN_LM', 'GER_BN', 'IDN_SV', 'KAZ_AC', 'KSA_WA', 'NAM_HF', 'NZL_KP', 'PHL_TA', 'USA_GC'}
csv_file = '/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/metadadata.csv'
dry_run = False
fix_ata_mv = False
for region in REGIONS:
metadata_dir = Path(f"/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/{region}/metadata")
csv_rows = parse_csv(csv_file)
print(f"Loaded {len(csv_rows)} rows from CSV")
json_files = sorted(metadata_dir.glob("*_metadata.json"))
print(f"Found {len(json_files)} metadata JSON files")
for json_path in json_files:
region = json_path.stem.replace("_metadata", "")
if region not in csv_rows:
print(f" ⚠ No CSV row for {region}, skipping")
continue
print(f" Processing {region}...")
# Load JSON (with repair if needed)
json_data = load_json_robust(json_path, fix_ata_mv=fix_ata_mv)
# Apply CSV updates
updated = update_json_from_csv(json_data, csv_rows[region])
# Write back
if not dry_run:
backup_path = json_path.with_suffix(".json.bak")
shutil.copy2(json_path, backup_path)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(updated, f, indent=2, ensure_ascii=False)
f.write("\n")
print(f" ✓ Updated {json_path.name}")
else:
print(f" [dry-run] Would update {json_path.name}")
# Print key changes for verification
print(f" file_size_mb: {updated.get('file_size_mb')}")
print(f" n_tiles: {updated['spatial']['tile_index']['n_tiles']}")
print(f" resolution: {updated['raster']['resolution_meters']}")
print(f" extent bbox: {updated['spatial']['extent']['bbox']}")
print("Done!")
if __name__ == "__main__":
main()