#!/usr/bin/env python3 import sqlite3 import json import subprocess import sys from pathlib import Path def read_bounds(tif): """Legge i bounds W,S,E,N dal TIFF usando gdalinfo -json, arrotondati a 6 decimali.""" info = json.loads(subprocess.check_output(["gdalinfo", "-json", str(tif)])) if "wgs84Extent" in info: coords = info["wgs84Extent"]["coordinates"][0] minlon, minlat = coords[0] maxlon, maxlat = coords[2] else: cc = info["cornerCoordinates"] minlon, minlat = cc["lowerLeft"] maxlon, maxlat = cc["upperRight"] # Normalizzazione if minlon > maxlon: minlon, maxlon = maxlon, minlon if minlat > maxlat: minlat, maxlat = maxlat, minlat return ( round(minlon, 6), round(minlat, 6), round(maxlon, 6), round(maxlat, 6), ) def main(): if len(sys.argv) != 3: print("Uso: python3 set_mbtiles_metadata_multi.py ") sys.exit(1) tif_dir = Path(sys.argv[1]) mbtiles = Path(sys.argv[2]) if not tif_dir.exists() or not tif_dir.is_dir(): print(f"Directory TIFF non valida: {tif_dir}") sys.exit(1) if not mbtiles.exists(): print(f"MBTiles non trovato: {mbtiles}") sys.exit(1) # Trova tutti i TIFF nella directory tifs = sorted([p for p in tif_dir.iterdir() if p.suffix.lower() in (".tif", ".tiff")]) if not tifs: print("Nessun TIFF trovato nella directory.") sys.exit(1) print(f"Trovati {len(tifs)} TIFF:") for t in tifs: print(" -", t.name) # Calcolo bounds unificati bounds_list = [read_bounds(t) for t in tifs] W = min(b[0] for b in bounds_list) S = min(b[1] for b in bounds_list) E = max(b[2] for b in bounds_list) N = max(b[3] for b in bounds_list) bounds = f"{W:.6f},{S:.6f},{E:.6f},{N:.6f}" print("\nBounds unificati:", bounds) # Apri MBTiles conn = sqlite3.connect(mbtiles) cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS metadata ( name TEXT PRIMARY KEY, value TEXT ); """) # Zoom reali dal MBTiles cur.execute("SELECT MIN(zoom_level), MAX(zoom_level) FROM tiles;") minzoom, maxzoom = cur.fetchone() print(f"Zoom reali: {minzoom}..{maxzoom}") # Center centerLon = (W + E) / 2 centerLat = (S + N) / 2 centerZoom = (minzoom + maxzoom) // 2 center = f"{centerLon:.6f},{centerLat:.6f},{centerZoom}" # Scrittura metadata cur.execute("REPLACE INTO metadata VALUES ('bounds', ?)", (bounds,)) cur.execute("REPLACE INTO metadata VALUES ('center', ?)", (center,)) cur.execute("REPLACE INTO metadata VALUES ('minzoom', ?)", (str(minzoom),)) cur.execute("REPLACE INTO metadata VALUES ('maxzoom', ?)", (str(maxzoom),)) cur.execute("REPLACE INTO metadata VALUES ('format', 'png')") cur.execute("REPLACE INTO metadata VALUES ('type', 'overlay')") cur.execute("REPLACE INTO metadata VALUES ('scheme', 'xyz')") conn.commit() conn.close() print("\nMetadata scritti correttamente:") print("bounds:", bounds) print("center:", center) print("minzoom:", minzoom) print("maxzoom:", maxzoom) print("format: png") print("type: overlay") print("scheme: xyz") if __name__ == "__main__": main()