Datasets:
Modalities:
Geospatial
License:
Upload convert.py
Browse files- convert.py +187 -0
convert.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import zipfile
|
3 |
+
import geopandas as gpd
|
4 |
+
import pandas as pd
|
5 |
+
from tqdm import tqdm # For progress bars
|
6 |
+
import warnings
|
7 |
+
import multiprocessing as mp
|
8 |
+
import sys # Import the sys module
|
9 |
+
|
10 |
+
# Ignore specific warnings
|
11 |
+
warnings.filterwarnings("ignore", category=RuntimeWarning,
|
12 |
+
message="driver GML does not support open option DRIVER")
|
13 |
+
warnings.filterwarnings("ignore", category=RuntimeWarning,
|
14 |
+
message="Non closed ring detected. To avoid accepting it, set the OGR_GEOMETRY_ACCEPT_UNCLOSED_RING configuration option to NO")
|
15 |
+
|
16 |
+
|
17 |
+
def process_region(region_zip_path, output_dir):
|
18 |
+
"""Processes a single region zip file to extract and save commune and parcel data."""
|
19 |
+
region_name = os.path.basename(region_zip_path).replace(".zip", "") # Extract region name from filename.
|
20 |
+
all_communes = []
|
21 |
+
all_parcels = []
|
22 |
+
|
23 |
+
try:
|
24 |
+
with zipfile.ZipFile(region_zip_path, 'r') as region_zip:
|
25 |
+
city_zip_names = [f.filename for f in region_zip.filelist if f.filename.endswith('.zip')]
|
26 |
+
|
27 |
+
for city_zip_name in city_zip_names:
|
28 |
+
city_zip_path = region_zip.open(city_zip_name)
|
29 |
+
|
30 |
+
try:
|
31 |
+
with zipfile.ZipFile(city_zip_path, 'r') as city_zip:
|
32 |
+
commune_zip_names = [f.filename for f in city_zip.filelist if f.filename.endswith('.zip')]
|
33 |
+
|
34 |
+
for commune_zip_name in commune_zip_names:
|
35 |
+
try:
|
36 |
+
commune_zip_path = city_zip.open(commune_zip_name)
|
37 |
+
with zipfile.ZipFile(commune_zip_path, 'r') as commune_zip:
|
38 |
+
# Find GML files
|
39 |
+
gml_files = [f.filename for f in commune_zip.filelist if
|
40 |
+
f.filename.endswith('.gml')]
|
41 |
+
|
42 |
+
commune_gml = next((f for f in gml_files if '_map.gml' in f),
|
43 |
+
None) # Find map.gml
|
44 |
+
parcel_gml = next((f for f in gml_files if '_ple.gml' in f),
|
45 |
+
None) # Find ple.gml
|
46 |
+
|
47 |
+
if commune_gml:
|
48 |
+
try:
|
49 |
+
commune_gdf = gpd.read_file(commune_zip.open(commune_gml),
|
50 |
+
driver='GML')
|
51 |
+
all_communes.append(commune_gdf)
|
52 |
+
except Exception as e:
|
53 |
+
print(
|
54 |
+
f"Error reading commune GML {commune_gml} from {commune_zip_name}: {e}")
|
55 |
+
|
56 |
+
if parcel_gml:
|
57 |
+
try:
|
58 |
+
parcel_gdf = gpd.read_file(commune_zip.open(parcel_gml),
|
59 |
+
driver='GML')
|
60 |
+
all_parcels.append(parcel_gdf)
|
61 |
+
except Exception as e:
|
62 |
+
print(
|
63 |
+
f"Error reading parcel GML {parcel_gml} from {commune_zip_name}: {e}")
|
64 |
+
|
65 |
+
except zipfile.BadZipFile as e:
|
66 |
+
print(f"Bad Zip file encountered: {commune_zip_name} - {e}")
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error processing {commune_zip_name}: {e}")
|
69 |
+
|
70 |
+
except zipfile.BadZipFile as e:
|
71 |
+
print(f"Bad Zip file encountered: {city_zip_name} - {e}")
|
72 |
+
except Exception as e:
|
73 |
+
print(f"Error processing {city_zip_name}: {e}")
|
74 |
+
except zipfile.BadZipFile as e:
|
75 |
+
print(f"Bad Zip file encountered: {region_zip_name} - {e}")
|
76 |
+
except Exception as e:
|
77 |
+
print(f"Error processing {region_zip_name}: {e}")
|
78 |
+
|
79 |
+
# Concatenate and save for the region
|
80 |
+
try:
|
81 |
+
if all_communes:
|
82 |
+
communes_gdf = gpd.GeoDataFrame(pd.concat(all_communes, ignore_index=True))
|
83 |
+
|
84 |
+
# handle crs here.
|
85 |
+
if all_communes and hasattr(all_communes[0], 'crs') and all_communes[0].crs: # Check if not empty list
|
86 |
+
try:
|
87 |
+
communes_gdf.crs = all_communes[0].crs
|
88 |
+
except AttributeError as e:
|
89 |
+
print(f"Could not set CRS: {e}")
|
90 |
+
else:
|
91 |
+
print("WARNING: CRS information is missing from the input data.")
|
92 |
+
|
93 |
+
# Identify and convert problematic columns to strings
|
94 |
+
problem_columns = []
|
95 |
+
for col in communes_gdf.columns:
|
96 |
+
if col != 'geometry':
|
97 |
+
try:
|
98 |
+
communes_gdf[col] = pd.to_numeric(communes_gdf[col], errors='raise')
|
99 |
+
except (ValueError, TypeError):
|
100 |
+
problem_columns.append(col)
|
101 |
+
|
102 |
+
for col in problem_columns:
|
103 |
+
communes_gdf[col] = communes_gdf[col].astype(str)
|
104 |
+
|
105 |
+
# Try to set the geometry
|
106 |
+
if 'msGeometry' in communes_gdf.columns:
|
107 |
+
communes_gdf = communes_gdf.set_geometry('msGeometry')
|
108 |
+
elif 'geometry' in communes_gdf.columns:
|
109 |
+
communes_gdf = communes_gdf.set_geometry('geometry') # Already the default, but be explicit
|
110 |
+
else:
|
111 |
+
print(
|
112 |
+
"WARNING: No 'geometry' or 'msGeometry' column found in commune data. Spatial operations will not work.")
|
113 |
+
|
114 |
+
communes_gdf.to_parquet(
|
115 |
+
os.path.join(output_dir, f"{region_name}_communes.geoparquet"),
|
116 |
+
compression='gzip')
|
117 |
+
print(
|
118 |
+
f"Successfully saved {region_name} communes to {output_dir}/{region_name}_communes.geoparquet")
|
119 |
+
|
120 |
+
if all_parcels:
|
121 |
+
parcels_gdf = gpd.GeoDataFrame(pd.concat(all_parcels, ignore_index=True))
|
122 |
+
|
123 |
+
# handle crs here.
|
124 |
+
if all_parcels and hasattr(all_parcels[0], 'crs') and all_parcels[0].crs:
|
125 |
+
try:
|
126 |
+
parcels_gdf.crs = all_parcels[0].crs
|
127 |
+
except AttributeError as e:
|
128 |
+
print(f"Could not set CRS: {e}")
|
129 |
+
else:
|
130 |
+
print("WARNING: CRS information is missing from the input data.")
|
131 |
+
|
132 |
+
# Identify and convert problematic columns to strings
|
133 |
+
problem_columns = []
|
134 |
+
for col in parcels_gdf.columns:
|
135 |
+
if col != 'geometry':
|
136 |
+
try:
|
137 |
+
parcels_gdf[col] = pd.to_numeric(parcels_gdf[col], errors='raise')
|
138 |
+
except (ValueError, TypeError):
|
139 |
+
problem_columns.append(col)
|
140 |
+
|
141 |
+
for col in problem_columns:
|
142 |
+
parcels_gdf[col] = parcels_gdf[col].astype(str)
|
143 |
+
|
144 |
+
# Try to set the geometry
|
145 |
+
if 'msGeometry' in parcels_gdf.columns:
|
146 |
+
parcels_gdf = parcels_gdf.set_geometry('msGeometry')
|
147 |
+
elif 'geometry' in parcels_gdf.columns:
|
148 |
+
parcels_gdf = parcels_gdf.set_geometry('geometry') # Already the default, but be explicit
|
149 |
+
else:
|
150 |
+
print(
|
151 |
+
"WARNING: No 'geometry' or 'msGeometry' column found in parcel data. Spatial operations will not work.")
|
152 |
+
|
153 |
+
parcels_gdf.to_parquet(os.path.join(output_dir, f"{region_name}_parcels.geoparquet"),
|
154 |
+
compression='gzip')
|
155 |
+
print(
|
156 |
+
f"Successfully saved {region_name} parcels to {output_dir}/{region_name}_parcels.geoparquet")
|
157 |
+
|
158 |
+
except Exception as e:
|
159 |
+
print(f"Error saving GeoParquet files for {region_name}: {e}")
|
160 |
+
|
161 |
+
|
162 |
+
def process_italy_data_unzipped_parallel(root_dir, output_dir, num_processes=mp.cpu_count()):
|
163 |
+
"""
|
164 |
+
Processes the Italian data in parallel, leveraging multiprocessing.
|
165 |
+
"""
|
166 |
+
|
167 |
+
os.makedirs(output_dir, exist_ok=True)
|
168 |
+
region_zip_paths = [os.path.join(root_dir, f) for f in os.listdir(root_dir) if f.endswith('.zip')]
|
169 |
+
total_regions = len(region_zip_paths)
|
170 |
+
|
171 |
+
# Add this block to protect the entry point
|
172 |
+
if __name__ == '__main__':
|
173 |
+
# For macOS, you might need to set the start method to 'spawn'
|
174 |
+
if sys.platform == 'darwin':
|
175 |
+
mp.set_start_method('spawn')
|
176 |
+
|
177 |
+
with mp.Pool(processes=num_processes) as pool:
|
178 |
+
# Use pool.starmap to pass multiple arguments to process_region
|
179 |
+
results = list(tqdm(pool.starmap(process_region, [(region_zip_path, output_dir) for region_zip_path in region_zip_paths]), total=total_regions, desc="Overall Progress: Regions"))
|
180 |
+
|
181 |
+
|
182 |
+
# Example Usage:
|
183 |
+
root_dir = "ITALIA" # Path to the ITALIA directory
|
184 |
+
output_dir = "output" # Path to save the GeoParquet files
|
185 |
+
num_processes = mp.cpu_count() # Use all available CPU cores
|
186 |
+
|
187 |
+
process_italy_data_unzipped_parallel(root_dir, output_dir, num_processes)
|