python-osw-validation 0.2.5__py3-none-any.whl → 0.2.7__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,10 +1,11 @@
1
1
  import os
2
+ import gc
2
3
  import json
3
- import jsonschema
4
- from typing import Dict, Any, Optional, List
4
+ import jsonschema_rs
5
5
  import geopandas as gpd
6
6
  from .zipfile_handler import ZipFileHandler
7
- from .extracted_data_validator import ExtractedDataValidator, OSW_dataset_files
7
+ from typing import Dict, Any, Optional, List
8
+ from .extracted_data_validator import ExtractedDataValidator, OSW_DATASET_FILES
8
9
  from .version import __version__
9
10
 
10
11
  SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
@@ -29,23 +30,24 @@ class OSWValidation:
29
30
  self.schema_file_path = schema_file_path
30
31
 
31
32
  def load_osw_schema(self, schema_path: str) -> Dict[str, Any]:
32
- '''Load OSW Schema'''
33
+ """Load OSW Schema"""
33
34
  try:
34
35
  with open(schema_path, 'r') as file:
35
36
  return json.load(file)
36
37
  except Exception as e:
37
38
  self.errors.append(f'Invalid or missing schema file: {e}')
38
39
  raise Exception(f'Invalid or missing schema file: {e}')
39
-
40
+
40
41
  def are_ids_unique(self, gdf):
41
42
  """Check for duplicate values in the _id field"""
42
43
  duplicates = gdf[gdf.duplicated('_id', keep=False)]['_id'].unique()
43
-
44
44
  is_valid = len(duplicates) == 0
45
-
46
45
  return is_valid, list(duplicates)
47
46
 
48
47
  def validate(self, max_errors=20) -> ValidationResult:
48
+ zip_handler = None
49
+ OSW_DATASET = {}
50
+ validator = None
49
51
  try:
50
52
  # Extract the zipfile
51
53
  zip_handler = ZipFileHandler(self.zipfile_path)
@@ -60,43 +62,43 @@ class OSWValidation:
60
62
  if not validator.is_valid():
61
63
  self.errors.append(validator.error)
62
64
  return ValidationResult(False, self.errors)
65
+
63
66
  for file in validator.files:
64
67
  file_path = os.path.join(file)
65
- if not self.validate_osw_errors(file_path, max_errors):
68
+ if not self.validate_osw_errors(file_path=str(file_path), max_errors=max_errors):
66
69
  break
67
70
 
68
71
  if self.errors:
69
- zip_handler.remove_extracted_files()
70
72
  return ValidationResult(False, self.errors)
71
73
 
72
74
  # Validate data integrity
73
- OSW_dataset = {}
74
75
  for file in validator.files:
75
76
  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), '')
77
- OSW_dataset[osw_file] = gpd.read_file(file_path)
77
+ osw_file = next(
78
+ (osw_file_any for osw_file_any in OSW_DATASET_FILES.keys() if osw_file_any in file_path), '')
79
+ OSW_DATASET[osw_file] = gpd.read_file(file_path)
78
80
 
79
81
  # 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
80
- for osw_file in OSW_dataset:
81
- is_valid, duplicates = self.are_ids_unique(OSW_dataset[osw_file])
82
+ for osw_file in OSW_DATASET:
83
+ is_valid, duplicates = self.are_ids_unique(OSW_DATASET[osw_file])
82
84
  if not is_valid:
83
85
  self.errors.append(f"Duplicate _id's found in {osw_file} : {duplicates}")
84
86
 
85
87
  # Create sets of node id's and foreign keys to be used in validation
86
- if "nodes" in OSW_dataset:
87
- node_ids = set(OSW_dataset['nodes']['_id'])
88
+ if 'nodes' in OSW_DATASET:
89
+ node_ids = set(OSW_DATASET['nodes']['_id'])
88
90
  else:
89
91
  node_ids = set()
90
92
 
91
- if "edges" in OSW_dataset:
92
- node_ids_edges_u = set(OSW_dataset['edges']['_u_id'])
93
- node_ids_edges_v = set(OSW_dataset['edges']['_v_id'])
93
+ if 'edges' in OSW_DATASET:
94
+ node_ids_edges_u = set(OSW_DATASET['edges']['_u_id'])
95
+ node_ids_edges_v = set(OSW_DATASET['edges']['_v_id'])
94
96
  else:
95
97
  node_ids_edges_u = set()
96
98
  node_ids_edges_v = set()
97
99
 
98
- if "zones" in OSW_dataset:
99
- node_ids_zones_w = set([item for sublist in OSW_dataset['zones']['_w_id'] for item in sublist])
100
+ if 'zones' in OSW_DATASET:
101
+ node_ids_zones_w = set([item for sublist in OSW_DATASET['zones']['_w_id'] for item in sublist])
100
102
  else:
101
103
  node_ids_zones_w = set()
102
104
 
@@ -104,26 +106,32 @@ class OSWValidation:
104
106
  unmatched = node_ids_edges_u - node_ids
105
107
  is_valid = len(unmatched) == 0
106
108
  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}")
109
+ self.errors.append(
110
+ 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
111
 
109
112
  # Do all node references in _v_id exist in nodes?
110
113
  unmatched = node_ids_edges_v - node_ids
111
114
  is_valid = len(unmatched) == 0
112
115
  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}")
116
+ self.errors.append(
117
+ 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
118
 
115
119
  # Do all node references in _w_id exist in nodes?
116
120
  unmatched = node_ids_zones_w - node_ids
117
121
  is_valid = len(unmatched) == 0
118
122
  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}")
123
+ self.errors.append(
124
+ 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
125
 
121
126
  # 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
- 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)]
127
+ for osw_file in OSW_DATASET:
128
+ invalid_geojson = OSW_DATASET[osw_file][
129
+ (OSW_DATASET[osw_file].geometry.type != OSW_DATASET_FILES[osw_file]['geometry']) | (
130
+ OSW_DATASET[osw_file].is_valid == False)]
124
131
  is_valid = len(invalid_geojson) == 0
125
132
  if not is_valid:
126
- self.errors.append(f"Invalid {osw_file} geometries found, id's of invalid geometries: {set(invalid_geojson['_id'])}")
133
+ self.errors.append(
134
+ f"Invalid {osw_file} geometries found, id's of invalid geometries: {set(invalid_geojson['_id'])}")
127
135
 
128
136
  # Validate OSW external extensions
129
137
  for file in validator.externalExtensions:
@@ -132,33 +140,45 @@ class OSWValidation:
132
140
  invalid_geojson = extensionFile[extensionFile.is_valid == False]
133
141
  is_valid = len(invalid_geojson) == 0
134
142
  if not is_valid:
135
- self.errors.append(f"Invalid geometries found in extension file {file}, list of invalid geometries: {invalid_geojson.to_json()}")
143
+ self.errors.append(
144
+ f"Invalid geometries found in extension file {file}, list of invalid geometries: {invalid_geojson.to_json()}")
136
145
 
137
146
  if self.errors:
138
- zip_handler.remove_extracted_files()
139
147
  return ValidationResult(False, self.errors)
140
148
  else:
141
149
  return ValidationResult(True)
142
150
  except Exception as e:
143
151
  self.errors.append(f'Unable to validate: {e}')
144
152
  return ValidationResult(False, self.errors)
153
+ finally:
154
+ del OSW_DATASET
155
+ if zip_handler:
156
+ zip_handler.remove_extracted_files()
157
+
158
+ # Force garbage collection to free memory
159
+ gc.collect()
160
+
161
+ # Additional memory cleanup for geopandas dataframes
162
+ if validator:
163
+ for osw_file in validator.files:
164
+ if osw_file in locals():
165
+ del osw_file
166
+ del validator
167
+ gc.collect()
145
168
 
146
169
  def load_osw_file(self, graph_geojson_path: str) -> Dict[str, Any]:
147
- '''Load OSW Data'''
170
+ """Load OSW Data"""
148
171
  with open(graph_geojson_path, 'r') as file:
149
172
  return json.load(file)
150
173
 
151
174
  def validate_osw_errors(self, file_path: str, max_errors: int) -> bool:
152
- '''Validate OSW Data against the schema and process all errors'''
175
+ """Validate OSW Data against the schema and process all errors"""
153
176
  geojson_data = self.load_osw_file(file_path)
154
- validator = jsonschema.Draft7Validator(self.load_osw_schema(self.schema_file_path))
177
+ validator = jsonschema_rs.Draft7Validator(self.load_osw_schema(self.schema_file_path))
155
178
 
156
179
  for error in validator.iter_errors(geojson_data):
157
180
  self.errors.append(f'Validation error: {error.message}')
158
- if len(self.errors) == max_errors:
159
- break
160
-
161
- if len(self.errors) >= max_errors:
162
- return False
181
+ if len(self.errors) >= max_errors:
182
+ return False
163
183
 
164
- return True
184
+ return len(self.errors) < max_errors
@@ -1,32 +1,33 @@
1
1
  import os
2
+ import gc
2
3
  import glob
3
4
 
4
-
5
- OSW_dataset_files = {"edges": {
6
- "required": False,
7
- "geometry": "LineString"
8
- },
9
- "nodes": {
10
- "required": False,
11
- "geometry": "Point"
12
- },
13
- "points": {
14
- "required": False,
15
- "geometry": "Point"
16
- },
17
- "lines": {
18
- "required": False,
19
- "geometry": "LineString"
20
- },
21
- "zones": {
22
- "required": False,
23
- "geometry": "Polygon"
24
- },
25
- "polygons": {
26
- "required": False,
27
- "geometry": "Polygon"
28
- }
29
- }
5
+ OSW_DATASET_FILES = {
6
+ "edges": {
7
+ "required": False,
8
+ "geometry": "LineString"
9
+ },
10
+ "nodes": {
11
+ "required": False,
12
+ "geometry": "Point"
13
+ },
14
+ "points": {
15
+ "required": False,
16
+ "geometry": "Point"
17
+ },
18
+ "lines": {
19
+ "required": False,
20
+ "geometry": "LineString"
21
+ },
22
+ "zones": {
23
+ "required": False,
24
+ "geometry": "Polygon"
25
+ },
26
+ "polygons": {
27
+ "required": False,
28
+ "geometry": "Polygon"
29
+ }
30
+ }
30
31
 
31
32
 
32
33
  class ExtractedDataValidator:
@@ -53,48 +54,59 @@ class ExtractedDataValidator:
53
54
  self.error = 'No .geojson files found in the specified directory or its subdirectories.'
54
55
  return False
55
56
 
56
- required_files = [key for key, value in OSW_dataset_files.items() if value['required']]
57
- optional_files = [key for key, value in OSW_dataset_files.items() if not value['required']]
57
+ required_files = [key for key, value in OSW_DATASET_FILES.items() if value['required']]
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
92
-
93
- if duplicate_files:
94
- self.error = f'Multiple .geojson files of the same type found: {", ".join(duplicate_files)}.'
95
- return False
96
-
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])
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)
94
+
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])
106
+
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.5'
1
+ __version__ = '0.2.7'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-osw-validation
3
- Version: 0.2.5
3
+ Version: 0.2.7
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,8 @@ 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~=4.19.1
18
- Requires-Dist: zipfile36~=0.1.3
19
- Requires-Dist: coverage~=7.5.1
17
+ Requires-Dist: jsonschema-rs
18
+ Requires-Dist: zipfile36
20
19
  Requires-Dist: geopandas
21
20
 
22
21
  # TDEI python lib OSW validation package
@@ -0,0 +1,10 @@
1
+ python_osw_validation/__init__.py,sha256=SKFTjvZC_TGYH45jVkdq-MctbZLMrX6ElXp88BzCfdg,7895
2
+ python_osw_validation/extracted_data_validator.py,sha256=wZyCk8NlJv10cj_GrRTAiwm4cBhTAeDethjzJU-amoI,3877
3
+ python_osw_validation/version.py,sha256=k14HNX-j7JGQmMcNd5V9YYE1rd2NN5QFLz4W-ttaFD0,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.7.dist-info/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
+ python_osw_validation-0.2.7.dist-info/METADATA,sha256=ZFW5vh8CHW1PU1WHpXtemdzhALazinWT79OaHNGCIDE,6117
8
+ python_osw_validation-0.2.7.dist-info/WHEEL,sha256=eOLhNAGa2EW3wWl_TU484h7q1UNgy0JXjjoqKoxAAQc,92
9
+ python_osw_validation-0.2.7.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
10
+ python_osw_validation-0.2.7.dist-info/RECORD,,
@@ -1,10 +0,0 @@
1
- python_osw_validation/__init__.py,sha256=8G-4lF_FjKhC1vdRZ5l0ak_kw4OCt5EBzTPvzsslolk,7301
2
- python_osw_validation/extracted_data_validator.py,sha256=Tdo3I5xz9bmzlZh9OH7Fp8WOcM88VZe4kCrzR2WwVWY,3894
3
- python_osw_validation/version.py,sha256=SXQZggCNtpYDwWAsfFLa0O_t3a-KL2cRKIMg40z4kgM,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.5.dist-info/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
- python_osw_validation-0.2.5.dist-info/METADATA,sha256=4wWQIp0V5f6Dc67eJRSlapacQ8KnAuUzweyALtlFLzs,6160
8
- python_osw_validation-0.2.5.dist-info/WHEEL,sha256=eOLhNAGa2EW3wWl_TU484h7q1UNgy0JXjjoqKoxAAQc,92
9
- python_osw_validation-0.2.5.dist-info/top_level.txt,sha256=GE81UPcDHEffJCxYu3M_iPz3Dt-O3axB73R5SLm_Veo,22
10
- python_osw_validation-0.2.5.dist-info/RECORD,,