python-osw-validation 0.2.6__py3-none-any.whl → 0.2.8__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.
@@ -1,12 +1,13 @@
1
1
  import os
2
2
  import gc
3
3
  import json
4
- import jsonschema
5
- from typing import Dict, Any, Optional, List
4
+ import jsonschema_rs
6
5
  import geopandas as gpd
7
6
  from .zipfile_handler import ZipFileHandler
7
+ from typing import Dict, Any, Optional, List
8
8
  from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES
9
9
  from .version import __version__
10
+ import traceback
10
11
 
11
12
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
12
13
 
@@ -37,7 +38,7 @@ class OSWValidation:
37
38
  except Exception as e:
38
39
  self.errors.append(f'Invalid or missing schema file: {e}')
39
40
  raise Exception(f'Invalid or missing schema file: {e}')
40
-
41
+
41
42
  def are_ids_unique(self, gdf):
42
43
  """Check for duplicate values in the _id field"""
43
44
  duplicates = gdf[gdf.duplicated('_id', keep=False)]['_id'].unique()
@@ -47,6 +48,7 @@ class OSWValidation:
47
48
  def validate(self, max_errors=20) -> ValidationResult:
48
49
  zip_handler = None
49
50
  OSW_DATASET = {}
51
+ validator = None
50
52
  try:
51
53
  # Extract the zipfile
52
54
  zip_handler = ZipFileHandler(self.zipfile_path)
@@ -73,7 +75,8 @@ class OSWValidation:
73
75
  # Validate data integrity
74
76
  for file in validator.files:
75
77
  file_path = os.path.join(file)
76
- osw_file = next((osw_file_any for osw_file_any in OSW_DATASET_FILES.keys() if osw_file_any in file_path), '')
78
+ osw_file = next(
79
+ (osw_file_any for osw_file_any in OSW_DATASET_FILES.keys() if osw_file_any in file_path), '')
77
80
  OSW_DATASET[osw_file] = gpd.read_file(file_path)
78
81
 
79
82
  # Are all id's unique in each file? No need to check uniqueness across files yet since we do not have a global OSW ID format yet
@@ -104,26 +107,32 @@ class OSWValidation:
104
107
  unmatched = node_ids_edges_u - node_ids
105
108
  is_valid = len(unmatched) == 0
106
109
  if not is_valid:
107
- self.errors.append(f"All _u_id's in edges should be part of _id's mentioned in nodes, _u_id's not in nodes are: {unmatched}")
110
+ self.errors.append(
111
+ f"All _u_id's in edges should be part of _id's mentioned in nodes, _u_id's not in nodes are: {unmatched}")
108
112
 
109
113
  # Do all node references in _v_id exist in nodes?
110
114
  unmatched = node_ids_edges_v - node_ids
111
115
  is_valid = len(unmatched) == 0
112
116
  if not is_valid:
113
- self.errors.append(f"All _v_id's in edges should be part of _id's mentioned in nodes, _v_id's not in nodes are: {unmatched}")
117
+ self.errors.append(
118
+ f"All _v_id's in edges should be part of _id's mentioned in nodes, _v_id's not in nodes are: {unmatched}")
114
119
 
115
120
  # Do all node references in _w_id exist in nodes?
116
121
  unmatched = node_ids_zones_w - node_ids
117
122
  is_valid = len(unmatched) == 0
118
123
  if not is_valid:
119
- self.errors.append(f"All _w_id's in zones should be part of _id's mentioned in nodes, _w_id's not in nodes are: {unmatched}")
124
+ self.errors.append(
125
+ f"All _w_id's in zones should be part of _id's mentioned in nodes, _w_id's not in nodes are: {unmatched}")
120
126
 
121
127
  # Geometry validation: check geometry type in each file and test if coordinates make a shape that is reasonable geometric shape according to the Simple Feature Access standard
122
128
  for osw_file in OSW_DATASET:
123
- invalid_geojson = OSW_DATASET[osw_file][(OSW_DATASET[osw_file].geometry.type != OSW_DATASET_FILES[osw_file]['geometry']) | (OSW_DATASET[osw_file].is_valid == False)]
129
+ invalid_geojson = OSW_DATASET[osw_file][
130
+ (OSW_DATASET[osw_file].geometry.type != OSW_DATASET_FILES[osw_file]['geometry']) | (
131
+ OSW_DATASET[osw_file].is_valid == False)]
124
132
  is_valid = len(invalid_geojson) == 0
125
133
  if not is_valid:
126
- self.errors.append(f"Invalid {osw_file} geometries found, id's of invalid geometries: {set(invalid_geojson['_id'])}")
134
+ self.errors.append(
135
+ f"Invalid {osw_file} geometries found, id's of invalid geometries: {set(invalid_geojson['_id'])}")
127
136
 
128
137
  # Validate OSW external extensions
129
138
  for file in validator.externalExtensions:
@@ -132,7 +141,8 @@ class OSWValidation:
132
141
  invalid_geojson = extensionFile[extensionFile.is_valid == False]
133
142
  is_valid = len(invalid_geojson) == 0
134
143
  if not is_valid:
135
- self.errors.append(f"Invalid geometries found in extension file {file}, list of invalid geometries: {invalid_geojson.to_json()}")
144
+ self.errors.append(
145
+ f"Invalid geometries found in extension file {file}, list of invalid geometries: {invalid_geojson.to_json()}")
136
146
 
137
147
  if self.errors:
138
148
  return ValidationResult(False, self.errors)
@@ -140,11 +150,22 @@ class OSWValidation:
140
150
  return ValidationResult(True)
141
151
  except Exception as e:
142
152
  self.errors.append(f'Unable to validate: {e}')
153
+ traceback.print_exc()
143
154
  return ValidationResult(False, self.errors)
144
155
  finally:
145
156
  del OSW_DATASET
146
157
  if zip_handler:
147
158
  zip_handler.remove_extracted_files()
159
+
160
+ # Force garbage collection to free memory
161
+ gc.collect()
162
+
163
+ # Additional memory cleanup for geopandas dataframes
164
+ if validator:
165
+ for osw_file in validator.files:
166
+ if osw_file in locals():
167
+ del osw_file
168
+ del validator
148
169
  gc.collect()
149
170
 
150
171
  def load_osw_file(self, graph_geojson_path: str) -> Dict[str, Any]:
@@ -155,7 +176,7 @@ class OSWValidation:
155
176
  def validate_osw_errors(self, file_path: str, max_errors: int) -> bool:
156
177
  """Validate OSW Data against the schema and process all errors"""
157
178
  geojson_data = self.load_osw_file(file_path)
158
- validator = jsonschema.Draft7Validator(self.load_osw_schema(self.schema_file_path))
179
+ validator = jsonschema_rs.Draft7Validator(self.load_osw_schema(self.schema_file_path))
159
180
 
160
181
  for error in validator.iter_errors(geojson_data):
161
182
  self.errors.append(f'Validation error: {error.message}')
@@ -1,4 +1,5 @@
1
1
  import os
2
+ import gc
2
3
  import glob
3
4
 
4
5
  OSW_DATASET_FILES = {
@@ -57,44 +58,55 @@ class ExtractedDataValidator:
57
58
  optional_files = [key for key, value in OSW_DATASET_FILES.items() if not value['required']]
58
59
  missing_files = []
59
60
  duplicate_files = []
60
- for required_file in required_files:
61
- file_count = 0
62
- for filename in geojson_files:
63
- base_name = os.path.basename(filename)
64
- if required_file in base_name and base_name.endswith('.geojson'):
65
- file_count += 1
66
- save_filename = filename
67
- if file_count == 0:
68
- # Missing required file
69
- missing_files.append(required_file)
70
- elif file_count == 1:
71
- self.files.append(save_filename)
72
- else:
73
- # Duplicate file
74
- duplicate_files.append(required_file)
61
+ save_filename = None # Initialize this variable
75
62
 
76
- for optional_file in optional_files:
77
- file_count = 0
78
- for filename in geojson_files:
79
- base_name = os.path.basename(filename)
80
- if optional_file in base_name and base_name.endswith('.geojson'):
81
- file_count += 1
82
- save_filename = filename
83
- if file_count == 1:
84
- self.files.append(save_filename)
85
- elif file_count > 1:
86
- # Duplicate file
87
- duplicate_files.append(optional_file)
63
+ try:
64
+ # Process required files
65
+ for required_file in required_files:
66
+ file_count = 0
67
+ for filename in geojson_files:
68
+ base_name = os.path.basename(filename)
69
+ if required_file in base_name and base_name.endswith('.geojson'):
70
+ file_count += 1
71
+ save_filename = filename
72
+ if file_count == 0:
73
+ # Missing required file
74
+ missing_files.append(required_file)
75
+ elif file_count == 1:
76
+ self.files.append(save_filename)
77
+ else:
78
+ # Duplicate file
79
+ duplicate_files.append(required_file)
88
80
 
89
- if missing_files:
90
- self.error = f'Missing required .geojson files: {", ".join(missing_files)}.'
91
- return False
81
+ # Process optional files
82
+ for optional_file in optional_files:
83
+ file_count = 0
84
+ for filename in geojson_files:
85
+ base_name = os.path.basename(filename)
86
+ if optional_file in base_name and base_name.endswith('.geojson'):
87
+ file_count += 1
88
+ save_filename = filename
89
+ if file_count == 1:
90
+ self.files.append(save_filename)
91
+ elif file_count > 1:
92
+ # Duplicate file
93
+ duplicate_files.append(optional_file)
92
94
 
93
- if duplicate_files:
94
- self.error = f'Multiple .geojson files of the same type found: {", ".join(duplicate_files)}.'
95
- return False
95
+ # Check for missing or duplicate files
96
+ if missing_files:
97
+ self.error = f'Missing required .geojson files: {", ".join(missing_files)}.'
98
+ return False
99
+
100
+ if duplicate_files:
101
+ self.error = f'Multiple .geojson files of the same type found: {", ".join(duplicate_files)}.'
102
+ return False
103
+
104
+ # Add OSW external extensions, GeoJSON files we know nothing about
105
+ self.externalExtensions.extend([item for item in geojson_files if item not in self.files])
96
106
 
97
- # Add OSW external extensions, GeoJSON files we know nothing about
98
- self.externalExtensions.extend([item for item in geojson_files if item not in self.files])
107
+ finally:
108
+ # Cleanup large lists and call garbage collector
109
+ del geojson_files, required_files, optional_files, missing_files, duplicate_files
110
+ gc.collect()
99
111
 
100
112
  return True
@@ -1 +1 @@
1
- __version__ = '0.2.6'
1
+ __version__ = '0.2.8'
@@ -1,9 +1,9 @@
1
1
  import os
2
+ import glob
2
3
  import shutil
3
4
  import tempfile
4
- from typing import Optional
5
5
  import zipfile36 as zipfile
6
- import glob
6
+ from typing import Optional
7
7
 
8
8
 
9
9
  class ZipFileHandler:
@@ -21,19 +21,19 @@ class ZipFileHandler:
21
21
  try:
22
22
  # Build the full pattern with the directory
23
23
  full_pattern = os.path.join(os.path.dirname(self.zip_file_path), file_pattern)
24
-
24
+
25
25
  # Find all files in the directory matching the pattern
26
26
  files_to_zip = glob.glob(full_pattern)
27
-
27
+
28
28
  # Create a zip file and add matching files to it
29
29
  with zipfile.ZipFile(self.zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
30
30
  for file in files_to_zip:
31
31
  archive_name = os.path.relpath(file, os.path.dirname(self.zip_file_path))
32
32
  zipf.write(file, arcname=archive_name)
33
-
33
+
34
34
  # Get the full path to the created zip file
35
35
  full_zip_path = os.path.abspath(self.zip_file_path)
36
-
36
+
37
37
  # Return the full path to the zip file
38
38
  return full_zip_path
39
39
  except Exception as e:
@@ -49,22 +49,21 @@ class ZipFileHandler:
49
49
 
50
50
  if len(zip_ref.namelist()) == 0:
51
51
  raise Exception('ZIP file is empty')
52
-
52
+
53
53
  internal_folder_name = self.find_internal_folder(zip_ref)
54
- return os.path.join(self.extracted_dir,internal_folder_name)
54
+ return os.path.join(self.extracted_dir, internal_folder_name)
55
55
  except Exception as e:
56
56
  self.error = f'Error extracting ZIP file: {e}'
57
-
57
+
58
58
  # finds the first folder available in the extracted folder.
59
59
  # returns empty if there are no folders inside
60
- def find_internal_folder(self, zip_ref: zipfile.ZipFile)-> str:
60
+ def find_internal_folder(self, zip_ref: zipfile.ZipFile) -> str:
61
61
  for filename in zip_ref.namelist():
62
- path = os.path.join(self.extracted_dir,filename)
63
- if(os.path.isdir(path)):
62
+ path = os.path.join(self.extracted_dir, filename)
63
+ if (os.path.isdir(path)):
64
64
  return filename
65
65
  return ''
66
66
 
67
-
68
67
  def remove_extracted_files(self) -> None:
69
68
  if self.extracted_dir and os.path.exists(self.extracted_dir):
70
69
  shutil.rmtree(self.extracted_dir)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-osw-validation
3
- Version: 0.2.6
3
+ Version: 0.2.8
4
4
  Summary: Python library for OSW validation
5
5
  Home-page: https://github.com/TaskarCenterAtUW/TDEI-python-lib-osw-validation
6
6
  Author: Sujata Misra
@@ -14,9 +14,9 @@ Classifier: Operating System :: OS Independent
14
14
  Requires-Python: >=3.10
15
15
  Description-Content-Type: text/markdown
16
16
  License-File: LICENSE
17
- Requires-Dist: jsonschema
18
- Requires-Dist: zipfile36
19
- Requires-Dist: geopandas
17
+ Requires-Dist: jsonschema-rs==0.26.1
18
+ Requires-Dist: zipfile36==0.0.12
19
+ Requires-Dist: geopandas==0.14.4
20
20
 
21
21
  # TDEI python lib OSW validation package
22
22
 
@@ -0,0 +1,10 @@
1
+ python_osw_validation/__init__.py,sha256=BrVyTquf9n4-US7d_FZBNEjyh24LaucSz4Zd65v2tfw,7946
2
+ python_osw_validation/extracted_data_validator.py,sha256=wZyCk8NlJv10cj_GrRTAiwm4cBhTAeDethjzJU-amoI,3877
3
+ python_osw_validation/version.py,sha256=1MeGsuS1PhEEHmvZ4CYVipAjr6XlyVy-M_a04LDWvEU,21
4
+ python_osw_validation/zipfile_handler.py,sha256=jXnP-8O5AAOBapuNF3-XdFVM1MHiPaWpl_wlbX-aqhY,2631
5
+ python_osw_validation/schema/opensidewalks.schema.json,sha256=i0iJwb_4Tq20BVUpkpgyM_7fm4SW_d_HNXKw0xul7OA,240987
6
+ python_osw_validation-0.2.8.dist-info/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
+ python_osw_validation-0.2.8.dist-info/METADATA,sha256=SkT5F02UhWcHiR__O_Y3Gs_OpCsd09R35bmD5g9CJA8,6141
8
+ python_osw_validation-0.2.8.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
9
+ python_osw_validation-0.2.8.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
10
+ python_osw_validation-0.2.8.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.44.0)
2
+ Generator: bdist_wheel (0.45.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,10 +0,0 @@
1
- python_osw_validation/__init__.py,sha256=CToPu6up1oroUOG7sl15uNclhwTznBOGBRlpeN9q1Eo,7351
2
- python_osw_validation/extracted_data_validator.py,sha256=1QFVVJRpkx8HfAWJmtJ2PxPBsD-UVsNk5I2VFzVJ5Ps,3333
3
- python_osw_validation/version.py,sha256=G3YzB5xTyZTVDHgjxzwfUZHPQbqRjfJO_4NfpO-O5Lg,21
4
- python_osw_validation/zipfile_handler.py,sha256=lCRraGcysxelVKswQw1r-i_9kGQGvRQk7hJkWUwiAPk,2692
5
- python_osw_validation/schema/opensidewalks.schema.json,sha256=i0iJwb_4Tq20BVUpkpgyM_7fm4SW_d_HNXKw0xul7OA,240987
6
- python_osw_validation-0.2.6.dist-info/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
- python_osw_validation-0.2.6.dist-info/METADATA,sha256=d7VByKt099S5QEjzVuT4K0Rveb1ZLNFi3Tn8MJXMsoc,6114
8
- python_osw_validation-0.2.6.dist-info/WHEEL,sha256=eOLhNAGa2EW3wWl_TU484h7q1UNgy0JXjjoqKoxAAQc,92
9
- python_osw_validation-0.2.6.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
10
- python_osw_validation-0.2.6.dist-info/RECORD,,